-
Notifications
You must be signed in to change notification settings - Fork 56
/
index.js
487 lines (446 loc) · 14 KB
/
index.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
const TelegramBot = require('node-telegram-bot-api');
const downloadUtils = require('./download_tools/utils.js');
const dlVars = require('./download_tools/vars.js');
const ariaTools = require('./download_tools/aria-tools.js');
const constants = require('./.constants.js');
const msgTools = require('./msg-tools.js');
const driveList = require('./drive/drive-list.js');
const driveUtils = require('./drive/drive-utils.js');
const ping = require('./ping/ping.js');
const options = {
polling: true
};
const bot = new TelegramBot(constants.TOKEN, options);
var websocketOpened = false;
var statusInterval;
var hosts = ['https://api.telegram.org'];
initAria2();
bot.onText(/^\/start/, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
sendMessage(msg, 'You should know the commands already. Happy mirroring.');
}
});
bot.onText(/^\/ping/, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
ping(hosts).then(function(delta) {
sendMessage(msg, 'Ping time was ' + String(delta) + ' ms.');
console.log('Starting ping test. Ping time was ' + String(delta) + ' ms');
}).catch(function(err) {
console.error('Could not ping remote URL', err);
});
}
});
bot.onText(/^\/source/, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
sendMessage(msg, 'You can find my source code here : https://github.com/Yash-Garg/telegram-drive-bot');
}
});
bot.onText(/^\/mirrortar (.+)/i, (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
mirror(msg, match, true);
}
});
bot.onText(/^\/mirrorit (.+)/i, (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
mirror(msg, match);
}
});
bot.on('message', (msg) => {
if (dlVars.isDownloading && msg.chat.id === dlVars.tgChatId) {
if (dlVars.messagesSinceStart) {
if (dlVars.messagesSinceStart < 10) {
dlVars.messagesSinceStart++;
}
} else {
dlVars.messagesSinceStart = 1;
}
}
});
/**
* Start a new download operation. Only one is allowed at a time. Make sure
* that this is triggered by an authorized user, because this function itself
* does not check for that.
* @param {Object} msg The Message that triggered the download
* @param {Array} match Message matches
* @param {boolean} isTar Decides if this download should be archived before upload
*/
function mirror (msg, match, isTar) {
if (websocketOpened) {
if (dlVars.isDownloading) {
sendMessage(msg, dlVars.tgUsername + ' is mirroring something. Please wait else die.');
} else {
if (downloadUtils.isDownloadAllowed(match[1])) {
prepDownload(msg, match[1], isTar);
} else {
sendMessage(msg, `Download failed. Blacklisted URL.`);
}
}
} else {
sendMessage(msg, `Websocket isn't open. Can't download`);
}
}
bot.onText(/^\/mirroritStatus/i, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
sendStatusMessage(msg, undefined, 1);
}
});
function getStatus (msg, callback) {
var authorizedCode;
if (msg) {
authorizedCode = msgTools.isAuthorized(msg);
} else {
authorizedCode = 1;
}
if (authorizedCode > -1) {
if (dlVars.isDownloading) {
if (dlVars.isUploading) {
callback(null, 'Upload is in progress. Please wait.');
} else {
ariaTools.getStatus(dlVars.downloadGid, (err, message, filename, filesize) => {
if (!err) {
handleDisallowedFilename(filename);
callback(null, message);
} else {
console.log('status: ', err);
callback(err, null);
}
});
}
} else {
callback(null, 'No active download.');
}
} else {
callback(null, `You aren't qualified to use this bot here.`);
}
}
bot.onText(/^\/search (.+)/i, (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
driveList.listFiles(match[1], (err, res) => {
if (err) {
sendMessage(msg, 'Failed to search the list of files.');
} else {
sendMessage(msg, res, 60000);
}
});
}
});
bot.onText(/^\/getFolder/i, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
sendUnauthorizedMessage(msg);
} else {
sendMessage(msg,
'<a href = \'' + driveUtils.getFileLink(constants.GDRIVE_PARENT_DIR_ID, true) + '\'>Drive Mirror Folder</a>',
60000);
}
});
bot.onText(/^\/stopit/i, (msg) => {
var authorizedCode = msgTools.isAuthorized(msg);
if (authorizedCode > -1 && authorizedCode < 3) {
stopMirror(msg);
} else if (authorizedCode === 3) {
msgTools.isAdmin(bot, msg, (e, res) => {
if (res) {
stopMirror(msg);
} else {
sendMessage(msg, 'You do not have the permission to do that.');
}
});
} else {
sendMessage(msg, 'You cannot use this bot here.');
}
});
function stopMirror (msg) {
if (dlVars.isDownloading) {
if (dlVars.isUploading) {
if (msg) {
sendMessage(msg, 'Upload in progress. Cannot cancel.');
}
} else {
ariaTools.stopDownload(dlVars.downloadGid, () => {
// Not sending a message here, because a cancel will fire
// the onDownloadStop notification, which will notify the
// person who started the download
if (msg && dlVars.tgChatId !== msg.chat.id) {
// Notify if this is not the chat the download started in
sendMessage(msg, 'The download was cancelled.');
}
});
}
} else if (msg) {
sendMessage(msg, 'No active download.');
}
}
/**
* Cancels the download if its filename contains a string from
* constants.ARIA_FILTERED_FILENAMES. Call this on every status message update,
* because the file name might not become visible for the first few status
* updates, for example, in case of BitTorrents.
*
* @param {String} filename The name of the downloaded file/top level directory
* @returns {boolean} False if file name is disallowed, true otherwise,
* or if undetermined
*/
function handleDisallowedFilename (filename) {
if (dlVars.isDownloadAllowed === 0) return false;
if (dlVars.isDownloadAllowed === 1) return true;
if (!filename) return true;
var isAllowed = downloadUtils.isFilenameAllowed(filename);
if (isAllowed === 0) {
dlVars.isDownloadAllowed = 0;
if (dlVars.isDownloading && !dlVars.isUploading) {
cancelMirror();
}
return false;
} else if (isAllowed === 1) {
dlVars.isDownloadAllowed = 1;
}
return true;
}
function prepDownload (msg, match, isTar) {
sendMessage(msg, 'Preparing', -1, statusMessage => {
downloadUtils.setDownloadVars(msg, statusMessage, isTar);
download(match);
});
}
function download (match) {
ariaTools.addUri([match],
(err, gid) => {
if (err) {
console.log('Failure', err);
sendMessageReplyOriginal(`Failed to start the download. ${err['message']}`);
statusInterval = null;
msgTools.notifyExternal(false, gid, dlVars.tgChatId);
downloadUtils.cleanupDownload();
} else {
console.log(`download:${match} gid:${gid}`);
}
});
}
function sendMessage (msg, text, delay, callback) {
if (!delay) delay = 5000;
bot.sendMessage(msg.chat.id, text, {
reply_to_message_id: msg.message_id,
parse_mode: 'HTML'
})
.then((res) => {
if (callback) callback(res);
})
.catch((ignored) => { });
}
function sendUnauthorizedMessage (msg) {
sendMessage(msg, `You aren't authorized to use this bot here.`);
}
function sendMessageReplyOriginal (message) {
bot.sendMessage(dlVars.tgChatId, message, {
reply_to_message_id: dlVars.tgMessageId,
parse_mode: 'HTML'
})
.catch((ignored) => { });
}
function sendStatusMessage (msg) {
// Skipping 0, which is the reply to the download command message
var index = downloadUtils.indexOfStatus(msg.chat.id, 1);
getStatus(msg, (err, text) => {
if (!err) {
sendMessage(msg, text, 60000, message => {
downloadUtils.addStatus(message);
}, true);
}
});
}
function updateStatusMessage (msg, text) {
if (!text) {
getStatus(msg, (err, text) => {
if (!err) editMessage(msg, text);
});
} else {
editMessage(msg, text);
}
}
function editMessage (msg, text) {
if (msg && msg.chat && msg.chat.id && msg.message_id) {
bot.editMessageText(text, {
chat_id: msg.chat.id,
message_id: msg.message_id,
parse_mode: 'HTML'
})
.catch(ignored => { });
}
}
function updateAllStatus (message) {
if (message) {
dlVars.statusMsgsList.forEach(status => {
editMessage(status, message);
});
} else {
getStatus(null, (err, text) => {
if (err) return;
dlVars.statusMsgsList.forEach(status => {
editMessage(status, text);
});
});
}
}
/**
* Deletes the bot's original response to the download command, if less
* than 10 messages have been sent to the group the download started in,
* since the download was started. Also deletes if the bot doesn't have
* message read permissions.
**/
function deleteOrigReply () {
/* Reason: The download task has been completed, and a new status message
* has been sent. No need to clutter the group with dulpicate status.
*/
if (!dlVars.messagesSinceStart || dlVars.messagesSinceStart < 10) {
msgTools.deleteMsg(bot, dlVars.statusMsgsList[0], 0);
}
}
function cleanupDownload (gid, message) {
clearInterval(statusInterval);
statusInterval = null;
sendMessageReplyOriginal(message);
updateAllStatus(message);
deleteOrigReply();
msgTools.notifyExternal(false, gid, dlVars.tgChatId);
downloadUtils.cleanupDownload();
}
function initAria2 () {
ariaTools.openWebsocket((err) => {
if (err) {
console.log('A2C: Failed to open websocket. Exiting.');
process.exit(1);
} else {
websocketOpened = true;
console.log('A2C: Websocket opened');
}
});
ariaTools.setOnDownloadStart((gid) => {
dlVars.isDownloading = true;
dlVars.isUploading = false;
dlVars.downloadGid = gid;
console.log('start', gid);
// downloadUtils.setDownloadVars makes sure the first element in the list refers
// to the download command's message
updateStatusMessage(dlVars.statusMsgsList[0], 'Download started.');
ariaTools.getStatus(dlVars.downloadGid, (err, message, filename) => {
if (!err) {
handleDisallowedFilename(filename);
}
});
if (!statusInterval) {
statusInterval = setInterval(updateAllStatus, 4000);
}
});
ariaTools.setOnDownloadStop((gid) => {
console.log('stop', gid);
clearInterval(statusInterval);
statusInterval = null;
var message = 'Download stopped.';
if (dlVars.isDownloadAllowed === 0) {
message += ' Blacklisted file name.';
}
sendMessageReplyOriginal(message);
updateAllStatus(message);
deleteOrigReply();
msgTools.notifyExternal(false, gid, dlVars.tgChatId);
downloadUtils.cleanupDownload();
});
ariaTools.setOnDownloadComplete((gid) => {
ariaTools.getAriaFilePath(gid, (err, file) => {
if (err) {
console.log('onDownloadComplete: ' + JSON.stringify(err, null, 2));
var message = 'Upload failed. Could not get downloaded file.';
cleanupDownload(gid, message);
return;
}
if (file) {
ariaTools.getFileSize(gid, (err, size) => {
if (err) {
console.log('onDownloadComplete: ' + JSON.stringify(err, null, 2));
var message = 'Upload failed. Could not get file size.';
cleanupDownload(gid, message);
return;
}
var filename = downloadUtils.getFileNameFromPath(file);
dlVars.isUploading = true;
if (handleDisallowedFilename(filename)) {
console.log('onDownloadComplete: ' + file);
ariaTools.uploadFile(file, size, driveUploadCompleteCallback);
} else {
var reason = 'Upload failed. Blacklisted file name.';
cleanupDownload(gid, reason);
}
});
} else {
ariaTools.isDownloadMetadata(gid, (err, isMetadata) => {
if (err) {
console.log('onDownloadComplete: isMetadata: ' + JSON.stringify(err, null, 2));
var message = 'Upload failed. Could not check if the file is metadata.';
cleanupDownload(gid, message);
return;
}
if (isMetadata) {
console.log('onDownloadComplete: No files');
} else {
console.log('onDownloadComplete: No files - not metadata.');
var reason = 'Upload failed. Could not get files.';
cleanupDownload(gid, reason);
}
});
}
});
});
ariaTools.setOnDownloadError((gid) => {
console.log('error', gid);
clearInterval(statusInterval);
statusInterval = null;
var message = 'Download error.';
sendMessageReplyOriginal(message);
updateAllStatus(message);
deleteOrigReply();
msgTools.notifyExternal(false, gid, dlVars.tgChatId);
downloadUtils.cleanupDownload();
});
}
function driveUploadCompleteCallback (err, url, filePath, fileName, fileSize) {
clearInterval(statusInterval);
statusInterval = null;
var finalMessage;
if (err) {
var message;
try {
message = JSON.stringify(err, null, 2);
} catch (ignored) {
message = err;
}
console.log(`uploadFile: ${filePath}: ${message}`);
finalMessage = `Failed to upload <code>${fileName}</code> to Drive.${message}`;
msgTools.notifyExternal(false, dlVars.downloadGid, dlVars.tgChatId);
} else {
if (fileSize) {
var fileSizeStr = downloadUtils.formatSize(fileSize);
finalMessage = `<a href='${url}'>${fileName}</a> (${fileSizeStr})`;
} else {
finalMessage = `<a href='${url}'>${fileName}</a>`;
}
msgTools.notifyExternal(true, dlVars.downloadGid, url, dlVars.tgChatId);
}
sendMessageReplyOriginal(finalMessage);
updateAllStatus(finalMessage);
deleteOrigReply();
downloadUtils.cleanupDownload();
}