-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
350 lines (281 loc) · 11.1 KB
/
main.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
// Requirements
const { Telegraf } = require('telegraf');
const { google } = require('googleapis');
const drive = google.drive('v3');
const axios = require('axios');
require('dotenv').config();
// Init the Telegraf core class
const bot = new Telegraf(process.env.BOT_TOKEN);
// Upload folder IDs
folderId = process.env.DRIVE_ROOT;
// Debug bool
var DEBUG = !(process.env.NODE_ENV === "production");
/*****************************************************
* Bot Event Hooks
******************************************************/
// Start the bot up
bot.on('photo', async(ctx) => {
if (DEBUG) ctx.telegram.sendMessage(ctx.message.chat.id, `Photo submitted`);
var files = "";
try { files = ctx.update.message.photo; } catch (err) {
if (DEBUG) console.log(err);
return;
};
var fileId = files[1].file_id; // Telegram stores various different sizes of the photos. "1" is a large one
// Get the current date information
var ts = Date.now();
var date_ob = new Date(ts);
var day = date_ob.getDate();
var month = date_ob.getMonth() + 1;
var date = "39-" + month + "-" + day;
// Get the subdirectory ID
var parent_dir = await getSubDirectory("Photos");
// Use the file ID to call an axios http request to telegram's api to obtain the image
try {
ctx.telegram.getFileLink(fileId).then(downloadUrl => {
axios({ url: downloadUrl.toString(), responseType: 'stream' }).then(response => {
return new Promise((resolve, reject) => {
// Generate the file name and stream
var filename = date + " (" + ctx.update.message.from.first_name + " @ " + ctx.update.message.chat.title + ")" + ".jpg";
var stream = response.data;
// Upload the file to google drive
uploadFile(filename, stream, parent_dir);
});
}).catch();
})
} catch (err) {
if (DEBUG) console.log(err);
};
});
bot.on('video', async (ctx) => {
if (DEBUG) ctx.telegram.sendMessage(ctx.message.chat.id, `Video submitted`);
var files = "";
try { files = ctx.update.message.video; } catch (err) {
if (DEBUG) console.log(err);
return;
};
var fileId = files.file_id; // Telegram stores various different sizes of the photos. "1" is a large one
var fileName = files.file_name;
var mimeType = files.mime_type;
// Get the file extension
var extension = fileName.split(".")[1];
// Get the current date information
var ts = Date.now();
var date_ob = new Date(ts);
var day = date_ob.getDate();
var month = date_ob.getMonth() + 1;
var date = "39-" + month + "-" + day;
// Get the subdirectory ID
var parent_dir = await getSubDirectory("Videos");
// Use the file ID to call an axios http request to telegram's api to obtain the image
try {
ctx.telegram.getFileLink(fileId).then(downloadUrl => {
axios({ url: downloadUrl.toString(), responseType: 'stream' }).then(response => {
return new Promise((resolve, reject) => {
// Generate the file name and stream
var fileName = date + " (" + ctx.update.message.from.first_name + " @ " + ctx.update.message.chat.title + ")" + "." + extension;
var stream = response.data;
// Upload the file to google drive
uploadFile(fileName, stream, parent_dir);
});
}).catch();
})
} catch (err) {
if (DEBUG) console.log(err);
};
});
bot.on('document', async (ctx) => {
if (DEBUG) ctx.telegram.sendMessage(ctx.message.chat.id, `Document submitted`);
var files = "";
try { files = ctx.update.message.document; } catch (err) {
if (DEBUG) console.log(err);
return;
};
var fileId = files.file_id; // Telegram stores various different sizes of the photos. "1" is a large one
var fileName = files.file_name;
var mimeType = files.mime_type;
// Set the parent directory depending on the type of the file
var parent_dir = "";
if (mimeType.match(/^image/)) {
parent_dir = await getSubDirectory("Photos");
} else if (mimeType.match(/^video/)) {
parent_dir = await getSubDirectory("Videos");
} else { return; }
// Get the file extension
var extension = fileName.split(".")[1];
// Get the current date information
var ts = Date.now();
var date_ob = new Date(ts);
var day = date_ob.getDate();
var month = date_ob.getMonth() + 1;
var date = "39-" + month + "-" + day;
// Use the file ID to call an axios http request to telegram's api to obtain the image
try {
ctx.telegram.getFileLink(fileId).then(downloadUrl => {
axios({ url: downloadUrl.toString(), responseType: 'stream' }).then(response => {
return new Promise((resolve, reject) => {
// Generate the file name and stream
var fileName = date + " (" + ctx.update.message.from.first_name + " @ " + ctx.update.message.chat.title + ")" + "." + extension;
var stream = response.data;
// Upload the file to google drive
uploadFile(fileName, stream, parent_dir);
});
}).catch();
})
} catch (err) {
if (DEBUG) console.log(err);
};
});
bot.on('video_note', async (ctx) => {
if (DEBUG) ctx.telegram.sendMessage(ctx.message.chat.id, `Bubble submitted`);
var files = "";
try { files = ctx.update.message.video_note; } catch (err) {
if (DEBUG) console.log(err);
return;
};
var fileId = files.file_id; // Telegram stores various different sizes of the photos. "1" is a large one
// Get the current date information
var ts = Date.now();
var date_ob = new Date(ts);
var day = date_ob.getDate();
var month = date_ob.getMonth() + 1;
var date = "39-" + month + "-" + day;
// Get the subdirectory ID
var parent_dir = await getSubDirectory("Bubble Messages");
// Use the file ID to call an axios http request to telegram's api to obtain the image
try {
ctx.telegram.getFileLink(fileId).then(downloadUrl => {
axios({ url: downloadUrl.toString(), responseType: 'stream' }).then(response => {
return new Promise((resolve, reject) => {
// Generate the file name and stream
var fileName = date + " (" + ctx.update.message.from.first_name + " @ " + ctx.update.message.chat.title + ")" + ".mp4";
var stream = response.data;
// Upload the file to google drive
uploadFile(fileName, stream, parent_dir);
});
})
})
} catch (err) {
if (DEBUG) console.log(err);
};
});
/*****************************************************
* Directory Control
******************************************************/
// Create a folder if one doesn't already exist with a given name and parent
async function findOrCreateFolder(folderName, parent) {
// Obtain user credentials to use for the request
const auth = new google.auth.GoogleAuth({
keyFile: process.env.GOOGLE_KEYFILE,
scopes: 'https://www.googleapis.com/auth/drive',
});
google.options({ auth });
// Use the root folder as the parent if the "parent" parameter isn't set
var parent_id = folderId;
if (typeof parent !== "undefined") {
parent_id = parent;
}
// Search to find the root ID of the folder
var root_folder;
try {
// Search for the folder using the API
const res = await drive.files.list({
// For the query: Type = folder, and parent and name are matched
q: "'" + parent_id + "' in parents and mimeType = 'application/vnd.google-apps.folder' and name = '" + folderName + "'",
// Idk what these do but hey it works
fields: 'nextPageToken, files(id, name)',
spaces: 'drive',
supportsAllDrives: true,
supportsTeamDrives: true,
});
root_folder = res.data.files[0].id;
} catch (err) {
// Folder didn't exist so make it
root_folder = await createFolder(folderName, parent_id);
return root_folder;
}
return root_folder;
}
// Create a folder with a given name
async function createFolder(folderName, parent_dir) {
// Get credentials and build service
// TODO (developer) - Use appropriate auth mechanism for your app
// Obtain user credentials to use for the request
const auth = new google.auth.GoogleAuth({
keyFile: process.env.GOOGLE_KEYFILE,
scopes: 'https://www.googleapis.com/auth/drive',
});
google.options({ auth });
const fileMetadata = {
'name': folderName,
'mimeType': 'application/vnd.google-apps.folder',
parents: [parent_dir]
};
// Create the folder using the API
try {
const file = await drive.files.create({
resource: fileMetadata,
fields: 'id',
});
return file.data.id;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}
// Get the month's folder ID
async function getRootDirectory() {
// Get the name of the current month (probably a better way to do this but meh)
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const d = new Date();
const month = monthNames[d.getMonth()];
const year = d.getYear() + 17 - 100;
// Get the root directory
var root_folder = await findOrCreateFolder(month + " S" + year);
return root_folder
}
// Get a folder ID within the month's directory
async function getSubDirectory(folder_name) {
// Get the root directory for the month
var root_folder = await getRootDirectory();
// Get the folder within that root directory
var subdir_folder = await findOrCreateFolder(folder_name, root_folder);
return subdir_folder;
}
// Upload a file to the given location
async function uploadFile(filename, stream, parent_dir) {
// Obtain user credentials to use for the request
const auth = new google.auth.GoogleAuth({
keyFile: process.env.GOOGLE_KEYFILE,
scopes: 'https://www.googleapis.com/auth/drive',
});
google.options({ auth });
const resource = {
name: filename,
parents: [parent_dir]
}
// Create the file using the API
const res = await drive.files.create(
{
resource,
media: {
body: stream,
},
supportsAllDrives: true,
supportsTeamDrives: true,
}
);
if (DEBUG) console.log(res.data);
return res.data;
}
// Launch the bot
bot.launch();
var http = require('http');
var server_port = process.env.PORT;
var server_host = '0.0.0.0';
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('\n');
}).listen(server_port, server_host);