-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
271 lines (230 loc) · 8.08 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
/* jshint esversion: 6 */
const fs = require("fs");
let db = require('./usersdb');
let twdb = require('./target_word_playlist_data');
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const portNum = 3006;
const yt_credz = require('./yt-credz');
const google = require('googleapis');
const youtube = google.youtube('v3');
const OAuth2 = google.auth.OAuth2;
const redirect_url = process.argv[2] || 'http://localhost:'+portNum+'/app';
const request = require('request');
const parse_str = require('locutus/php/strings/parse_str');
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ SETUP GOOGLE OAUTH
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
let oauth2Client = new OAuth2(
yt_credz.clientId,
yt_credz.clientSecret,
redirect_url
);
console.log('int oauth2Client',oauth2Client);
let googleAuthURL = oauth2Client.generateAuthUrl({
scope: "https://www.googleapis.com/auth/youtube",
access_type: 'offline',//'online'
state: { status: 'loggedIn' }
});
function saveNewUserToDB( username, token ){
db[username] = token;
let string = JSON.stringify(db,null,'\t');
fs.writeFile(__dirname+'/usersdb.json',string,function(err) {
if(err) return console.error(err);
else console.log('added '+username+' to usersdb.json');
});
}
function getUserTokenFromDB( username ){
return db[username];
}
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ TARGETED WORD PLAYLIST DB
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
function arrHasData( arr ){
for (let i = 0; i < arr.length; i++) {
if( arr[i].length > 0 ) return true;
}
return false;
}
function addNewTargetWordPlaylist( o ){
if( typeof twdb[ o.playlist ]=="undefined" )
twdb[ o.playlist ] = {};
for (let i = 0; i < o.time.length; i++) {
if(o.time[i].length>0){
twdb[o.playlist][ o.list[i] ] = o.time[i];
}
}
console.log('ran add func', twdb[o.playlist]);
let string = JSON.stringify(twdb,null,'\t');
fs.writeFile(__dirname+'/target_word_playlist_data.json',string,function(err) {
if(err) return console.error(err);
else console.log('added '+o.playlist+' to target_word_playlist_data.json');
});
}
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . YOUTUBE STORYBOARDS
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
function getYTStoryBoardURLz( id, callback ){
let url = `http://www.youtube.com/get_video_info?video_id=${id}&asv=3&el=detailpage&hl=en_US`;
request( url, (err,res,body)=>{
if(err) return console.error(err);
// meta data to array
let vidNfo = [];
parse_str(body, vidNfo);
if( typeof vidNfo.storyboard_spec !== "undefined"){
// get storybaord specs specifically
let sb_spec = decodeURIComponent((vidNfo.storyboard_spec+'').replace(/\+/g, '%20'));
sb_spec = sb_spec.split('|');
// build base url
let baseUrl = sb_spec[0].split("$");
baseUrl = baseUrl[0] + '2/M';
// get sigh param
if( typeof sb_spec[3] == "undefined" ){
callback(null);
return;
}
let sigh = sb_spec[3].split('#');
sigh = sigh.pop();
// get num of imgs
let num = ( vidNfo.length_seconds >= 1200 ) ?
vidNfo.length_seconds/240 : 5;
// build url list
let urls = [];
for (let i = 0; i < num; i++) urls.push( baseUrl+i+'.jpg?sigh='+sigh );
// send data bax to client
callback(urls);
} else {
callback(null);
}
});
}
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ SOCKETS COMMUNIQUE
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
io.on('connection', function(socket){
// console.log('a user connected');
socket.emit('target word playlist data', twdb );
socket.on('refresh',(username)=>{
// THERE IS NO FUNCTION TO CALL THIS EVENT, READ BELOW:
// if i need to test refreshing access_token in the future
// from client console do: socket.emit('refresh');
// ^ this assumes user has already "logged in", ie. credz initally set
oauth2Client.refreshAccessToken(function(err, tokens) {
// your access_token is now refreshed and stored in oauth2Client
// IF NECESSARY TO USE THIS EVENT, WRIET LOGIC TO SAVE NEW TOKEN TO DB
// ^ TEST THIS LOGIC ( B4 GETTING RID OF OLD DB ENTRIES )
if(err) console.log("TOCKEN-ERR:",err);
console.log("TOKENS",tokens);
});
// SIDENOTE: refresh tokens only get created if access_type
// in googleAuthURL is set to 'offline'
});
// ..... client would like to confirm user ......
socket.on('get db user confirmation', (data)=>{
// check if user already in db
if( typeof db[data.username] == "object" ){
socket.emit('user confirmation from db','old_user');
} else {
socket.emit('user confirmation from db','new_user');
// create a token && generate an entry in the db
oauth2Client.getToken(data.gcode, function (err, tokens) {
if(err) console.log("GET-TOCKEN-ERR:",err);
saveNewUserToDB( data.username, tokens );
});
}
});
// ..... client would like a video's storyBoard ......
socket.on('get storyboard', (vidId)=>{
getYTStoryBoardURLz( vidId, (data)=>{
socket.emit('storyboard data',data);
});
});
// ..... client would like to add to playlist ......
// ..... via app.html ( main app )
socket.on('add to playlist', ( data )=>{
oauth2Client.setCredentials( getUserTokenFromDB(data.username) );
youtube.playlistItems.insert({
auth: oauth2Client,
part: 'snippet',
resource: {
snippet:{
playlistId: data.playlist,
resourceId: {
kind: "youtube#video",
videoId: data.vid
}
}
}
}, function(err, res) {
if(err) console.log(err);
// console.log(res);
socket.emit('playlist response',res);
});
});
// ..... client would like to add a list of videos to a playlist ......
// ...... via add.html ( url bulk list adder )
socket.on('add list to playlist', ( data )=>{
oauth2Client.setCredentials( getUserTokenFromDB(data.username) );
console.log('data.time',data.time, arrHasData(data.time));
if( arrHasData(data.time) ) addNewTargetWordPlaylist( data );
let cnt = 0;
function addAnother( id ){
youtube.playlistItems.insert({
auth: oauth2Client,
part: 'snippet',
resource: {
snippet:{
playlistId: data.playlist,
resourceId: {
kind: "youtube#video",
videoId: data.list[cnt]
}
}
}
}, function(err, res){
if(err) {
console.log(err);
socket.emit('list add response',`${err.code}:${err.errors[0].message}`);
cnt++;
if( cnt < data.list.length ) addAnother( cnt );
} else {
socket.emit('list add response',res.snippet.title);
cnt++;
if( cnt < data.list.length ) addAnother( cnt );
}
});
}
addAnother( cnt );
});
});
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ ROUTING
// ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~ . ~ * ~
// static files ---------------
// ----------------------------
app.use(express.static(__dirname +'/public'));
// templates ------------------
// ----------------------------
app.engine('html', require('hogan-express'));
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
// verbs ----------------------
// ----------------------------
app.get('/', function (req, res){
res.render('index', { message:'BB-YT-SCANNER',url:googleAuthURL });
});
app.get('/app', function (req, res){
res.render('app', { apiKey: yt_credz.apiKey });
});
app.get('/add', function (req, res){
res.render('add');
});
// listen ---------------------
// ----------------------------
let server = http.listen(portNum, function () {
let host = server.address().address;
let port = server.address().port;
console.log('listening at http://%s:%s', host, port);
});