-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathnode_helper.js
328 lines (303 loc) · 11 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
Node Helper module for MMM-MicrosoftToDo
Purpose: Microsoft's OAutht 2.0 Token API endpoint does not support CORS,
therefore we cannot make AJAX calls from the browser without disabling
webSecurity in Electron.
*/
var NodeHelper = require("node_helper");
const Log = require("logger");
const { add, formatISO9075, compareAsc, parseISO } = require("date-fns");
const { RateLimit } = require("async-sema");
module.exports = NodeHelper.create({
start: function () {
Log.info(`${this.name} node_helper started ...`);
},
socketNotificationReceived: function (notification, payload) {
if (notification === "FETCH_DATA") {
this.fetchData(payload);
} else if (notification === "COMPLETE_TASK") {
this.completeTask(payload.listId, payload.taskId, payload.config);
} else {
Log.warn(`${this.name} - did not process event: ${notification}`);
}
},
completeTask: function (listId, taskId, config) {
Log.info(
`${this.name} - completing task '${taskId}' from list '${listId}'`
);
// copy context to be available inside callbacks
const self = this;
var patchUrl = `https://graph.microsoft.com/v1.0/me/todo/lists/${listId}/tasks/${taskId}`;
const updateBody = {
id: taskId,
status: "completed"
};
const request = {
method: "PATCH",
body: JSON.stringify(updateBody),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${self.accessToken}`
}
};
fetch(patchUrl, request)
.then(self.checkFetchStatus)
.then((response) => response.json())
.then(self.checkBodyError)
.then((responseJson) => {
self.sendSocketNotification(
`TASK_COMPLETED_${config.id}`,
responseJson
);
})
.catch((error) => {
Log.error(`[MMM-MicrosoftToDo]: completeTask: ${patchUrl}`);
self.logError(error);
});
},
getTodos: function (config) {
// copy context to be available inside callbacks
const self = this;
// get access token
var tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
var refreshToken = config.oauth2RefreshToken;
const form = new URLSearchParams();
form.append("client_id", config.oauth2ClientId);
form.append(
"scope",
"offline_access user.read " +
(config.completeOnClick ? "tasks.readwrite" : "tasks.read")
);
form.append("refresh_token", refreshToken);
form.append("grant_type", "refresh_token");
form.append("client_secret", config.oauth2ClientSecret);
fetch(tokenUrl, {
method: "POST",
body: form
})
.then(self.checkFetchStatus)
.then((response) => response.json())
.then(self.checkBodyError)
.then((accessTokenJson) => {
var accessToken = accessTokenJson.access_token;
self.accessToken = accessToken;
self.fetchList(accessToken, config);
})
.catch((error) => {
Log.error(
`[MMM-MicrosoftToDo]: getTodos / get access token: ${tokenUrl}`
);
self.logError(error);
});
},
fetchList: function (accessToken, config) {
const self = this;
var filterClause = "";
const hasListNameInConfig =
config.listName !== undefined && config.listName !== "";
// filter by displayName, otherwise, get all the lists
if (hasListNameInConfig) {
// Get the list ID based on name
filterClause = `displayName eq '${config.listName}'`;
}
filterClause = encodeURIComponent(filterClause).replaceAll("'", "%27");
var filter = "";
if (filterClause !== "") {
filter = `&$filter=${filterClause}`;
}
Log.debug(`${this.name} - getting list using filter '${filter}'`);
// get ID of task folder
var getListUrl = `https://graph.microsoft.com/v1.0/me/todo/lists/?$top=200${filter}`;
fetch(getListUrl, {
method: "get",
headers: {
Authorization: "Bearer " + accessToken
}
})
.then(self.checkFetchStatus)
.then((response) => response.json())
.then(self.checkBodyError)
.then((responseData) => {
var listIds = [];
if (config.plannedTasks.enable) {
// default values from MMM-MicrosoftToDo.js are not considered as
// the 'plannedTasks' configuration is handled by a nested object,
// therefore setting default values here again
if (!config.plannedTasks.includedLists) {
config.plannedTasks.includedLists = [".*"];
}
// Filter out any lists that are in the `includedLists` collection
Log.debug(
`${this.name} - applying filter '${config.plannedTasks.includedLists}' to ${responseData.value.length} lists`
);
listIds = responseData.value
.filter(
(list) =>
config.plannedTasks.includedLists.findIndex(
(include) => list.displayName.match(include) !== null
) !== -1
)
.map((list) => list.id);
} else if (responseData.value.length > 0) {
if (!hasListNameInConfig) {
Log.debug(`${this.name} - using default list`);
// If there is no list name in the config and it's not plannedTasks, get the default list
const list = responseData.value.find(
(element) => element.wellknownListName === "defaultList"
);
if (list) {
listIds.push(list.id);
}
} else {
Log.debug(
`${this.name} - using lists that match filter '${filter}'`
);
listIds.push(responseData.value[0].id);
}
}
if (listIds.length > 0) {
self.getTasks(accessToken, config, listIds);
} else {
self.logErrorObject({
error: `"${config.listName}" task folder not found`,
errorDescription: `The task folder "${config.listName}" could not be found.`
});
}
}) // function callback for task folders
.catch((error) => {
Log.error(`[MMM-MicrosoftToDo]: fetchList ${getListUrl}`);
self.logError(error);
});
},
fetchData: function (config) {
this.getTodos(config);
},
getTasks: function (accessToken, config, listIds) {
const self = this;
Log.debug(`${this.name} - getting tasks for ${listIds.length} list(s)`);
const limit = RateLimit(2);
// TODO: Iterate through ALL the lists. If plannedTasks, filter out those without
var promises = listIds.map(async (listId) => {
const promiseSelf = self;
var orderBy =
// sorting by subject is not supported anymore in API v1, hence falling back to created time
(config.orderBy === "subject" ? "&$orderby=createdDateTime" : "") +
(config.orderBy === "createdDate" ? "&$orderby=createdDateTime" : "") +
(config.orderBy === "importance" ? "&$orderby=importance desc" : "") +
(config.orderBy === "dueDate" ? "&$orderby=duedatetime/datetime" : "");
var filterClause = "status ne 'completed'";
if (config.plannedTasks.enable) {
// default values from MMM-MicrosoftToDo.js are not considered as
// the 'plannedTasks' configuration is handled by a nested object,
// therefore setting default values here again
if (!config.plannedTasks.duration) {
config.plannedTasks.duration = { weeks: 2 };
}
// need to ignore time zone, as the API expects a date time without
// time zone
var pastDate = formatISO9075(
add(Date.now(), config.plannedTasks.duration)
);
filterClause += ` and duedatetime/datetime lt '${pastDate}' and duedatetime/datetime ne null`;
}
filterClause = encodeURIComponent(filterClause).replaceAll("'", "%27");
var listUrl = `https://graph.microsoft.com/v1.0/me/todo/lists/${listId}/tasks?$top=${config.itemLimit}&$filter=${filterClause}${orderBy}`;
Log.debug(`${this.name} - getting tasks for list '${listId}'`);
await limit();
return fetch(listUrl, {
method: "get",
headers: {
Authorization: `Bearer ${accessToken}`
}
})
.then(promiseSelf.checkFetchStatus)
.then((response) => response.json())
.then(promiseSelf.checkBodyError)
.then((responseData) => {
var tasks = [];
if (
responseData.value !== null &&
responseData.value !== undefined &&
responseData.value.length > 0
) {
tasks = responseData.value.map((element) => {
var parsedDate;
if (element !== undefined && element.dueDateTime !== undefined) {
parsedDate = parseISO(element.dueDateTime.dateTime);
}
return {
id: element.id,
title: element.title,
dueDateTime: element.dueDateTime,
recurrence: element.recurrence,
listId: listId,
parsedDate: parsedDate
};
});
}
return tasks;
}) // function callback for task folders
.catch(promiseSelf.logError);
});
Log.debug(`[MMM-MicrosoftToDo] - waiting on ${promises.length} promises`);
Promise.all(promises)
.then((taskArray) => {
Log.debug(
`[MMM-MicrosoftToDo] - processing ${taskArray.length} return values`
);
var returnTasks = [];
taskArray.forEach((element) => {
if (element !== null && element !== undefined && element.length > 0) {
element.forEach((task) => returnTasks.push(task));
}
});
returnTasks.sort(self.taskSortCompare);
if (returnTasks.length > config.itemLimit) {
returnTasks = returnTasks.slice(0, config.itemLimit - 1);
}
Log.debug(
`[MMM-MicrosoftToDo] - returning ${returnTasks.length} tasks`
);
self.sendSocketNotification(`DATA_FETCHED_${config.id}`, returnTasks);
})
.catch(self.logError);
},
taskSortCompare: function (firstTask, secondTask) {
if (firstTask.parsedDate === undefined) {
return 1;
}
if (secondTask.parsedDate === undefined) {
return -1;
}
return compareAsc(firstTask.parsedDate, secondTask.parsedDate);
},
checkFetchStatus: function (response) {
if (response.ok) {
return response;
} else {
Log.error(response);
throw Error(
`checkFetchStatus failed with status '${
response.statusText
}' ${JSON.stringify(response)}`
);
}
},
checkBodyError: function (json) {
if (json && json.error) {
Log.error(json);
throw Error(
`checkBodyError failed with status '${json.error}' ${JSON.stringify(
json
)}`
);
}
return json;
},
logError: function (error) {
Log.error(`[MMM-MicrosoftToDo]: ${error}`);
},
logErrorObject: function (errorObject) {
Log.error(`[MMM-MicrosoftToDo]: ${JSON.stringify(errorObject)}`);
}
});