-
Notifications
You must be signed in to change notification settings - Fork 2
/
node_helper.js
90 lines (87 loc) · 3.12 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
const NodeHelper = require("node_helper");
const Trakt = require("trakt.tv");
const moment = require("moment");
const fs = require("fs");
var importtoken;
module.exports = NodeHelper.create({
start: function() {
var events = [];
this.fetchers = [];
console.log("Starting node helper for: " + this.name);
},
createFetcher: function(client_id, client_secret, days) {
var self = this;
let options = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: null,
api_url: null
};
const trakt = new Trakt(options);
function importoldtoken() {
return new Promise(function (fulfill, reject){
try {
importtoken = require('./token.json');
fulfill();
} catch (ex) {
reject(ex);
}
});
}
importoldtoken().catch(function(){
return trakt.get_codes().then(function(poll) {
self.log('Trakt Access Code: ' + poll.user_code);
self.sendSocketNotification("OAuth", {
code: poll.user_code
});
return trakt.poll_access(poll);
}).catch(error => {
self.errorLog(error, new Error());
return Promise.reject(error);
}).then(function(){
importtoken = trakt.export_token();
fs.writeFile("./modules/MMM-trakt/token.json", JSON.stringify(importtoken), "utf8", function (err,data) {
if (err) {
return self.errorLog(err, new Error());
}
});
});
}).then(function(){
trakt.import_token(importtoken).then(newTokens => {
self.log(importtoken);
self.debugLog(trakt);
trakt.calendars.my.shows({
start_date: moment().subtract(1, 'd').format("YYYY-MM-DD"),
days: days+2,
extended: 'full'
}).then(shows => {
self.sendSocketNotification("SHOWS", {
shows: shows
});
}).catch(error => {
self.errorLog(error, new Error());
});
});
}).catch(error => {
self.errorLog(error, new Error());
});
},
socketNotificationReceived: function(notification, payload) {
this.debug = payload.debug;
if (notification === "PULL") {
this.createFetcher(payload.client_id, payload.client_secret, payload.days);
}
},
log: function (msg) {
console.log("[" + (new Date(Date.now())).toLocaleTimeString() + "] - " + this.name + " - : ", msg);
},
debugLog: function (msg) {
if (this.debug) {
console.log("[" + (new Date(Date.now())).toLocaleTimeString() + "] - DEBUG - " + this.name + " - : ", msg);
}
},
errorLog: function (error, errorObject) {
var stack = errorObject.stack.toString().split(/\r\n|\n/); // Line number
console.log("[" + (new Date(Date.now())).toLocaleTimeString() + "] - ERROR " + this.name + " : ", error, " - [" + stack[1] + "]");
}
});