-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
374 lines (351 loc) · 11.5 KB
/
server.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
//NPM Packages
var fs = require("fs"),
readJson = require("r-json"),
Logger = require("bug-killer"),
express = require("express"),
bodyParser = require("body-parser"),
wget = require("node-wget");
(Youtube = require("youtube-api")),
(app = express()),
(path = require("path")),
(db = require("./db"));
require("dotenv").config();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
// Download client secret file from google developers console
const CREDENTIALS = readJson(`${__dirname}/client_secret.json`);
var oauth = Youtube.authenticate({
type: "oauth",
client_id: CREDENTIALS.web.client_id,
client_secret: CREDENTIALS.web.client_secret,
redirect_url: CREDENTIALS.web.redirect_uris[0]
});
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.get("/authorize", function(req, res) {
fs.readFile(process.cwd() + "/.credentials/youtube-nodejs.json", function(
err,
tokens
) {
if (err) {
let authUrl = oauth.generateAuthUrl({
access_type: "offline",
prompt: "consent",
scope: [
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtubepartner",
"https://www.googleapis.com/auth/youtube.force-ssl"
]
});
res.redirect(authUrl);
} else {
res.send("Already authorized");
}
});
});
// Handle oauth2 callback
app.get("/oauth2callback", function(req, res) {
Logger.log(
"Trying to get the token using the following code: " + req.query.code
);
oauth.getToken(req.query.code, (err, tokens) => {
if (err) {
return console.log(err);
} else {
oauth.setCredentials(tokens);
console.log("Credentials is set");
storeToken(tokens);
res.send("Authorized Successfully");
}
});
});
// Check if we have previously stored a token.
app.post("/send_recording", (req, res) => {
fs.readFile(process.cwd() + "/.credentials/youtube-nodejs.json", function(
err,
tokens
) {
console.log("*** " + req.body.payload.object + "***");
oauth.setCredentials(JSON.parse(tokens));
var file_name = makeid(6);
var topic = req.body.payload.object.topic;
var recording_start =
req.body.payload.object.recording_files[0].recording_start;
var recording_end =
req.body.payload.object.recording_files[0].recording_end;
var play_url = req.body.payload.object.recording_files[0].play_url;
var status = req.body.payload.object.recording_files[0].status;
var download_url = req.body.payload.object.recording_files[0].download_url;
var recording_start_time = new Date(recording_start);
var s_date = ("0" + recording_start_time.getDate()).slice(-2);
var s_month = ("0" + (recording_start_time.getMonth() + 1)).slice(-2);
var s_year = recording_start_time.getFullYear();
var s_hours = recording_start_time.getHours();
var s_minutes = recording_start_time.getMinutes();
var s_seconds = recording_start_time.getSeconds();
// prints date & time in YYYY-MM-DD HH:MM:SS format
var recording_st =
s_year +
"-" +
s_month +
"-" +
s_date +
"T" +
s_hours +
":" +
s_minutes +
":" +
s_seconds +
"Z";
var recording_end_time = new Date(recording_end);
var e_date = ("0" + recording_end_time.getDate()).slice(-2);
var e_month = ("0" + (recording_end_time.getMonth() + 1)).slice(-2);
var e_year = recording_end_time.getFullYear();
var e_hours = recording_end_time.getHours();
var e_minutes = recording_end_time.getMinutes();
var e_seconds = recording_end_time.getSeconds();
// prints date & time in YYYY-MM-DD HH:MM:SS format
var recording_et =
e_year +
"-" +
e_month +
"-" +
e_date +
"T" +
e_hours +
":" +
e_minutes +
":" +
e_seconds +
"Z";
var meta_data = {
file_name: file_name,
topic: topic,
recording_start: recording_st,
recording_end: recording_et,
play_url: play_url,
download_url: download_url,
status: status
};
//Create datbase connection
db.getConnection(function(err, connections) {
if (err) {
console.log("*** Cannot establish a connection with the database ***");
console.log(err);
} else {
console.log("*** New connection established with the database ***");
var sql =
`SELECT * FROM uploaded_video_status WHERE download_url = '` +
download_url +
`'`;
connections.query(sql, function(err, result, fields) {
if (err) {
console.log(err);
}
//This condition is to check whether duplicates records doesn't ger inserted.
if (result.length == 0) {
var sql =
`INSERT INTO uploaded_video_status
(file_name, topic, recording_start, recording_end, download_url, upload_status, youtube_url, sync)
VALUES
("` +
file_name +
`" ,"` +
topic +
`", "` +
recording_st +
`", "` +
recording_et +
`", "` +
download_url +
`", '', '', '')`;
connections.query(sql, function(err, result, fields) {
if (err) {
console.log(err);
}
console.log("*** Video record inserted ***");
//Upload videos to the youtube.
upload_video(wget, fs, meta_data, db, Youtube, res);
});
} else {
console.log("*** Cannot be uploaded ***");
}
});
connections.release();
}
});
});
res.sendStatus(200);
});
/**
* This function downloads that recording on server, saves its meta-data and upload that recording to Youtube Channel.
*
* @param {*} wget
* @param {*} fs
* @param {*} meta_data
* @param {*} db
* @param {*} Youtube
* @param {*} res
*/
function upload_video(wget, fs, meta_data, db, Youtube, res) {
console.log("*** In Upload Video Method ***");
wget(
{
url: meta_data.download_url,
dest: "downloads/" + meta_data.file_name + ".mp4", // destination path or path with filenname, default is ./
timeout: 100000 // duration to wait for request fulfillment in milliseconds, default is 10 seconds
},
function(error, response, body) {
if (error) {
console.log("*** error - wget ***");
console.log(error); // error encountered
} else {
console.log("*** Video downloaded on server ***");
db.getConnection(function(err, connections) {
if (err) {
console.log(err);
console.log(
"*** Cannot establish a connection with the database ***"
);
} else {
console.log("*** Now Uploading Video ***");
var sql =
`SELECT * FROM uploaded_video_status WHERE download_url = '` +
meta_data.download_url +
`'`;
connections.query(sql, function(err, result, fields) {
if (err) {
console.log(err);
throw err;
}
if (result.length > 0 && result.upload_status == undefined) {
Youtube.videos.insert(
{
resource: {
// Video title and description
snippet: {
title:
meta_data.topic + " " + meta_data.recording_start,
description:
meta_data.recording_start +
" " +
meta_data.recording_end +
" " +
meta_data.play_url +
" " +
meta_data.status
},
// I don't want to spam my subscribers
status: {
privacyStatus: "private"
}
},
// This is for the callback function
part: "snippet,status",
// Create the readable stream to upload the video
media: {
body: fs.createReadStream(
"downloads/" + meta_data.file_name + ".mp4"
)
}
},
(err, data) => {
if (err) {
console.log("*** youtube error" + err + "***");
return;
} else {
console.log("Video uploaded to youtube channel.");
var url = "https://www.youtube.com/watch?v=" + data.id;
var sql =
`UPDATE uploaded_video_status SET upload_status = 'uploaded', youtube_url = '` +
url +
`' WHERE download_url = '` +
meta_data.download_url +
`'`;
connections.query(sql, function(err, result, fields) {
if (err) {
console.log(err);
throw err;
}
console.log("Video record updated in sql table.");
});
// After Uploading deletes file from server.
fs.unlink(
"downloads/" + meta_data.file_name + ".mp4",
err => {
if (err) {
console.log(err);
throw err;
}
console.log(
"Removed from downloads/" +
meta_data.file_name +
".mp4"
);
}
);
}
}
);
}
connections.release();
return true;
});
}
});
}
}
);
}
/**
* Stores token in folder .credentials/youtube-nodejs.json file
*
* @param {*} token
*/
function storeToken(token) {
TOKEN_PATH = process.cwd() + "/.credentials/youtube-nodejs.json";
try {
fs.mkdirSync(process.cwd() + "/.credentials/");
} catch (err) {
if (err.code != "EEXIST") {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token), err => {
if (err) throw err;
console.log("Token stored to " + TOKEN_PATH);
});
}
/**
* Makes an unique id
*
* @param {*} length
*/
function makeid(length) {
var result = "";
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
// Listening Port - 8080
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log("Express is working on port " + port);
});
// 404 Error Handling
app.use(function(req, res, next) {
return res.status(404).send({
message: "Page Not found."
});
});
// 500 Error Handling
app.use(function(err, req, res, next) {
return res.status(500).send({ error: err });
});