-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnode_helper.js
147 lines (121 loc) · 3.48 KB
/
node_helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const http = require('http');
// only available in MagicMirror context
const NodeHelper = require('node_helper');
const Log = require('logger');
const ONE_MINUTE_MS = 60 * 1000;
const TEN_MINUTES_MS = 10 * ONE_MINUTE_MS;
const ONE_DAY_MS = 1 * 24 * 60 * ONE_MINUTE_MS;
const Notifications = {
CONFIG: 'CONFIG',
DATA: 'DATA',
ERROR: 'ERROR',
};
const Types = {
MOVIE: 'movie',
EPISODE: 'episode',
SEASON: 'season',
};
const PlexTypes = {
[Types.MOVIE]: '1',
[Types.TV]: '2',
};
const fetchData = (url) => {
return new Promise((resolve, reject) => {
http
.get(
url,
{
headers: {
Accept: 'application/json',
},
},
(res) => {
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
const data = JSON.parse(responseBody);
resolve(data);
});
},
)
.on('error', (err) => {
reject(err);
});
});
};
module.exports = NodeHelper.create({
config: {},
updateTimer: null,
// Override start method.
start: function () {
Log.log(`Starting node helper for: ${this.name}`);
},
async socketNotificationReceived(notification, payload) {
Log.info(`${this.name}: socketNotificationReceived ${notification}`);
if (notification === Notifications.CONFIG && !this.client) {
this.config = payload;
// validate types
for (const type of payload.types) {
if (!Object.values(Types).includes(type)) {
Log.error(`${this.name}: Invalid type '${type}' found`);
}
}
// Process fetch for the first time
this.process();
}
},
scheduleNextFetch(delayMs) {
clearTimeout(this.updateTimer);
this.updateTimer = setTimeout(() => {
this.process();
}, Math.max(delayMs, TEN_MINUTES_MS));
},
async process() {
try {
const plexItemsByType = await Promise.all(
Object.values(PlexTypes).map((plexType) =>
this.fetchFromPlex(plexType),
),
);
const items = plexItemsByType.flat();
for (const type of this.config.types) {
const typeItems = items.filter((item) => item.type === type);
this.sendSocketNotification(Notifications.DATA, {
type,
items: typeItems.slice(0, this.config.limit),
});
}
} catch (error) {
Log.error(error);
this.sendSocketNotification(Notifications.ERROR, {
error: error.message,
});
}
// schedule the next fetch
this.scheduleNextFetch(this.config.updateIntervalInMinute * ONE_MINUTE_MS);
},
async fetchFromPlex(plexType) {
const url = new URL(
`http://${this.config.hostname}:${this.config.port}/hubs/home/recentlyAdded`,
);
url.searchParams.append('type', plexType);
if (this.config.token) {
url.searchParams.append('X-Plex-Token', this.config.token);
}
Log.info(`${this.name}: fetching ${url}`);
const data = await fetchData(url);
const now = new Date();
let newerThanDate =
this.config.newerThanDay > 0
? new Date(now.getTime() - this.config.newerThanDay * ONE_DAY_MS)
: new Date(0);
const items = data.MediaContainer.Metadata.filter((item) => {
const itemAddedDate = new Date(item.addedAt * 1000);
return itemAddedDate >= newerThanDate;
});
Log.info(`${this.name}: found ${items.length} items for type ${plexType}`);
return items;
},
});