This repository has been archived by the owner on Mar 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
habitSync.js
333 lines (295 loc) · 10.3 KB
/
habitSync.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
329
330
331
332
333
#!/usr/bin/env node
var habitapi = require('habitrpg-api');
var request = require('superagent');
var async = require('async');
var fs = require('fs');
var _ = require('lodash');
var util = require('util');
var history = {};
//
// options.uid: HabitRPG UserId
// options.token: HabitRPG API Token
// options.todoist: Todoist API Token
// options.historyPath: Directory for history
//
function habitSync(options) {
if(!options) {
throw new Error("Options are required");
}
if(!options.uid) {
throw new Error("No HabitRPG User Id found");
}
if (!options.token) {
throw new Error("No HabitRPG API Token found");
}
if (!options.todoist) {
throw new Error("No Todoist API Token found");
}
if (options.historyPath) {
this.historyPath = options.historyPath + '/.todoist-habitrpg.json';
} else {
// Defaults
if(process.platform == "win32") {
this.historyPath = process.env.HOMEPATH + '/.todoist-habitrpg.json'
} else {
this.historyPath = process.env.HOME + '/.todoist-habitrpg.json'
}
}
this.uid = options.uid;
this.token = options.token;
this.todoist = options.todoist;
}
habitSync.prototype.run = function(done) {
var self = this;
history = self.readHistoryFromFile(self.historyPath);
if(!history.tasks) {
history.tasks = {};
}
var oldHistory = _.cloneDeep(history);
async.waterfall([
function(cb) {
self.getHabitAttributeIds(cb);
},
function(attributes, cb) {
habitAttributes = attributes;
self.getTodoistSync(cb);
},
function(res, cb) {
history.sync_token = res.body.sync_token;
self.updateHistoryForTodoistItems(res.body.items);
var changedTasks = self.findTasksThatNeedUpdating(history, oldHistory);
self.syncItemsToHabitRpg(changedTasks, cb);
}
], function(err, newHistory) {
if(err) {
return done(err);
}
fs.writeFileSync(self.historyPath, JSON.stringify(newHistory));
done();
});
};
habitSync.prototype.findTasksThatNeedUpdating = function(newHistory, oldHistory) {
var self = this;
var needToUpdate = [];
_.forEach(newHistory.tasks, function(item) {
var old = oldHistory.tasks[item.todoist.id];
var updateLabels = false;
if(old) {
updateLabels = self.checkTodoistLabels(old.todoist.labels, item.todoist.labels);
}
if(!old || !old.todoist || old.todoist.content != item.todoist.content ||
old.todoist.checked != item.todoist.checked ||
old.todoist.due_date_utc != item.todoist.due_date_utc ||
old.todoist.is_deleted != item.todoist.is_deleted ||
updateLabels) {
needToUpdate.push(item);
}
});
return needToUpdate;
};
habitSync.prototype.updateHistoryForTodoistItems = function(items) {
var self = this;
var habit = new habitapi(self.uid, self.token, null, 'v2');
_.forEach(items, function(item) {
if(history.tasks[item.id]) {
if(item.is_deleted) {
// TODO: Determine if you want to delete the task in the habit sync function
var habitId = history.tasks[item.id].habitrpg.id;
habit.deleteTask(habitId, function(response, error){});
// Deletes record from sync history
delete history.tasks[item.id];
} else {
history.tasks[item.id].todoist = item;
}
} else if(!item.is_deleted) {
// Only adds item to history if it was not deleted before syncing to habitrpg
history.tasks[item.id] = {todoist: item};
}
});
};
habitSync.prototype.readHistoryFromFile = function(path) {
var history = {};
if(fs.existsSync(path)) {
var data = fs.readFileSync(path, 'utf8');
history = JSON.parse(data);
}
return history;
};
habitSync.prototype.getTodoistSync = function(cb) {
var self = this;
var sync_token = history.sync_token || 0;
request.get('https://todoist.com/API/v7/sync')
.send('token=' + self.todoist)
.send('sync_token=' + sync_token)
.send('resource_types=["all"]')
.end(function(err, res) {
cb(err,res);
});
};
habitSync.prototype.syncItemsToHabitRpg = function(items, cb) {
var self = this
var habit = new habitapi(self.uid, self.token, null, 'v2');
// Cannot execute in parallel. See: https://github.com/HabitRPG/habitrpg/issues/2301
async.eachSeries(items, function(item, next) {
async.waterfall([
function(cb) {
var dueDate,
attribute;
if(item.todoist.due_date_utc) {
dueDate = new Date(item.todoist.due_date_utc);
}
var taskType = self.parseTodoistRepeatingDate(item.todoist.date_string);
var repeat = taskType.repeat;
var task = {
text: item.todoist.content,
dateCreated: new Date(item.todoist.date_added),
date: dueDate,
type: taskType.type,
repeat: taskType.repeat,
completed: item.todoist.checked == true
};
if (item.todoist.labels.length > 0) {
attribute = self.checkForAttributes(item.todoist.labels);
}
if(attribute) {
task.attribute = attribute;
}
if(item.habitrpg && item.habitrpg.id) {
if(task.type == "todo") {
// Checks if the complete status has changed
if((task.completed != item.habitrpg.completed && item.habitrpg.completed !== undefined) ||
(task.completed === true && item.habitrpg.completed === undefined)) {
var direction = task.completed === true;
habit.updateTaskScore(item.habitrpg.id, direction, function(response, error){ });
// Need to set dateCompleted on todo's that are checked
if(direction) {
task.dateCompleted = new Date();
} else if (!direction) {
task.dateCompleted = "";
}
}
} else if(task.type == "daily") {
var oldDate = new Date(item.habitrpg.date);
// Checks if the due date has changed, indicating that it was clicked in Todoist
if(task.date > oldDate) {
var direction = true;
task.completed = true;
habit.updateTaskScore(item.habitrpg.id, direction, function(response, error){ });
} else if(item.habitrpg.completed) {
task.completed = true;
}
}
habit.updateTask(item.habitrpg.id, task, function(err, res) {
cb(err, res);
});
} else {
if(task.type == "todo" && task.completed) {
task.dateCompleted = new Date();
}
habit.createTask(task, function(err, res) {
cb(err, res);
});
}
},
function(res, cb) {
history.tasks[item.todoist.id] = {
todoist: item.todoist,
habitrpg: res.body
};
// Adds date to habitrpg record if type is daily
if(res.body && res.body.type == "daily") {
history.tasks[item.todoist.id].habitrpg.date = new Date(item.todoist.due_date_utc);
} else if (!res.body) {
// TODO: Remove this once GH issue #44 actually gets fixed.
console.error('ERROR: Body is undefined. Please file an issue with this. res:' + util.inspect(res));
}
cb();
}
], next);
}, function(err) {
cb(err, history);
});
};
habitSync.prototype.getHabitAttributeIds = function(callback) {
// Gets a list of label ids and puts
// them in an object if they correspond
// to HabitRPG attributes (str, int, etc)
var self = this;
var labels = {};
request.post('https://api.todoist.com/API/getLabels')
.send('token=' + self.todoist)
.end(function(err, res) {
var labelObject = res.body;
for(var l in labelObject) {
labels[l] = labelObject[l].id;
}
var attributes = {str: [], int: [], con: [], per: []};
for(var l in labels) {
if (l == 'str' || l == 'strength' ||
l == 'physical' || l == 'phy') {
attributes.str.push(labels[l]);
} else if (l == 'int' || l == 'intelligence' ||
l == 'mental' || l == 'men') {
attributes.int.push(labels[l]);
} else if (l == 'con' || l == 'constitution' ||
l == 'social' || l == 'soc') {
attributes.con.push(labels[l]);
} else if (l == 'per' || l == 'perception' ||
l == 'other' || l == 'oth') {
attributes.per.push(labels[l]);
}
}
callback(null, attributes);
});
};
habitSync.prototype.checkForAttributes = function(labels) {
// Cycle through todoist labels
// For each label id, check it against the ids stored in habitAttributes
// If a match is found, return it
for(var label in labels) {
for(var att in habitAttributes) {
for(var num in habitAttributes[att]) {
if(habitAttributes[att][num] == labels[label]) {
return att;
}
}
}
}
};
habitSync.prototype.checkTodoistLabels = function(oldLabel, newLabel) {
// Compares ids of todoist labels to determine
// if the item needs updating
if(oldLabel.length != newLabel.length) {
return true;
}
for(var i in oldLabel) {
if(oldLabel[i] != newLabel[i]) {
return true;
}
}
return false;
};
habitSync.prototype.parseTodoistRepeatingDate = function(dateString) {
var type = "todo";
var repeat;
if(!dateString) return {type: type, repeat: repeat};
var noStartDate = !(dateString.match(/(after|starting|last|\d+(st|nd|rd|th)|(first|second|third))/i));
var needToParse = dateString.match(/^ev(ery)? [^\d]/i) || dateString === "daily";
if(needToParse && noStartDate) {
type = 'daily';
var everyday = (!!(dateString.match(/^ev(ery)? [^(week)]?(?:day|night)/i)) || dateString === "daily");
var weekday = !!(dateString.match(/^ev(ery)? (week)?day/i));
var weekend = !!(dateString.match(/^ev(ery)? (week)?end/i));
repeat = {
"su": everyday || weekend || !!(dateString.match(/\bs($| |,|u)/i)),
"s": everyday || weekend || !!(dateString.match(/\bsa($| |,|t)/i)),
"f": everyday || weekday || !!(dateString.match(/\bf($| |,|r)/i)),
"th": everyday || weekday || !!(dateString.match(/\bth($| |,|u)/i)),
"w": everyday || weekday || (!!(dateString.match(/\bw($| |,|e)/i)) && !weekend), // Otherwise also matches weekend
"t": everyday || weekday || !!(dateString.match(/\bt($| |,|u)/i)),
"m": everyday || weekday || !!(dateString.match(/\bm($| |,|o)/i))
};
}
return {type: type, repeat: repeat};
};
module.exports = habitSync;