-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
321 lines (272 loc) · 9.82 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
const path = require('path');
const http = require('http');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
var randomWords = require('random-words');
var express = require('express');
var bodyparser = require('body-parser');
const router = express.Router();
const {decode} = require('html-entities');
const cors = require('cors')
const bcrypt = require('bcryptjs');
const socketManager = require('./utils/socketManager');
const roomExpTime = 60*60*24;
const searchExpTime = 60*15;
const redisMongoQueries = require('./utils/redisMongoQueries');
const { promisify } = require("util");
const ytsr = require('ytsr');
const e = require('express');
const request = require('request');
// const cheerio = require('cheerio');
require('dotenv').config();
// const { google } = require('googleapis');
// const { title } = require('process');
// const { youtube } = require("googleapis/build/src/apis/youtube");
// const { youtubeAnalytics } = require("googleapis/build/src/apis/youtubeAnalytics");
const youtubedl = require('youtube-dl');
// const expressLayouts = require('express-ejs-layouts');
const RoomModel = require('./models/room');
const {v4: uuidV4} = require('uuid');
// const isUuid = require('isuuid');
const socketio = require('socket.io');
var jsonParser = bodyparser.json();
// var urlencodedParser = bodyparser.urlencoded({ extended: false });
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
var app = express();
require('./config/passport')(passport);
const server = http.createServer(app);
var port = process.env.PORT || '0.0.0.0';
// var redisPort = process.env.REDIS_PORT || 6379;
const redisClient = redisMongoQueries.createRedisClient();
const getRoomFromRedis = promisify(redisClient.hgetall).bind(redisClient);
const getKeysFromRedis = promisify(redisClient.keys).bind(redisClient);
redisClient.on('connect', _=>{
console.log("Connected to redis");
});
const dbURI = 'mongodb+srv://'+process.env.DB_USERNAME+':'+process.env.DB_PASS+'@cluster0.agmjg.mongodb.net/'+process.env.DB_NAME+'?retryWrites=true&w=majority';
mongoose.connect(dbURI, {useNewUrlParser: true, useUnifiedTopology: true})
.then((result)=>{
server.listen(port, function(){
// RoomModel.find().then((result)=>{
// if(!rooms) console.log("FATAL ERROR! Could not find rooms!");
// }).catch((err)=>{
// console.log(`Failed to get rooms from DB\n${err}`);
// });
console.log('Connected to DB...');
console.log(`Server listening...`);
console.log("Server start date/time: "+new Date().toLocaleDateString() + " / " + new Date().toLocaleTimeString());
console.log("======");
});
}).catch(err=>console.log(err));
// app.use(expressLayouts);
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(cors())
app.use(express.static('public'));
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next)=>{
res.locals.successMessage = req.flash('successMessage');
res.locals.errorMessage = req.flash('errorMessage');
res.locals.error = req.flash('error');
next();
});
app.use('/', require('./routes/index'));
app.use('/images', require('./routes/images'));
app.use('/user', require('./routes/user'));
app.use(router);
// app.use(bodyparser.json());
// app.use(bodyparser.urlencoded({extended: true}));
const NSFW_THUMBNAIL = 'https://buddyviewer.com/images/thumbs/nsfw_thumb.jpg';
const io = socketManager.createIO(server);
class RoomSecurity{
static OPEN = 0;
static LOCKED = 1;
static PRIVATE = 2;
}
const defaultDescription = "A lovely room for watching videos! Join!";
const defaultSecuritySetting = RoomSecurity.OPEN;
io.on('connection', socket=>{
console.log(socket.id, 'has connected')
socketManager.initIO(socket);
});
app.post('/check-saved-roomID', (req, res)=>{
// console.log("GET FIRED");
// const shouldRedirect = isUuid(req.body.currRoomID) && redisMongoQueries.findRoom(req.body.storedRoomID);
// res.send(shouldRedirect);
res.send("This shouldn't be happening. /check-saved-roomID");
});
app.get('/room/', (req, res)=>{
res.redirect('/');
});
app.get('/room/:roomID', (req, res)=>{
// const currRoomID = req.params.roomID;
// console.log(`ID IS ${currRoomID}`);
redisMongoQueries.findRoom(req.params.roomID)
.then(room=>{
if(room){
res.render('room', {roomID: room.roomID});
} else {
console.log("Someone tried to enter a room that didn't exist.");
res.redirect('/');
}
})
.catch(err=>{
console.log(err);
res.redirect('/');
});
});
app.post('/create-new-room', (req, res)=>{
const {securitySetting, roomDescription} = req.body;
let roomName = req.body.roomName || randomWords();
let securityResult = RoomSecurity.PRIVATE;
switch(securitySetting){
case "open":
securityResult = RoomSecurity.OPEN;
break;
case "locked":
securityResult = RoomSecurity.LOCKED;
break;
case "private":
securityResult = RoomSecurity.PRIVATE;
break;
}
if(roomName.includes(' ')){
roomName = roomName.split(' ').join('');
}
if(roomName.length > 50){
roomName = roomName.substring(0, 50);
}
const rawID = uuidV4();
// console.log("SECURITY SETTING: "+securitySetting+`(${securityResult})`);
redisMongoQueries.createEmptyRoom(securityResult, roomName, roomDescription, rawID)
.then(({roomID})=>{
// console.log(`Creating room ${roomID}`);
// if(!req.body.roomName)
// res.send({roomID})
// else
res.redirect(`/room/${roomID}`);
})
.catch(err=> console.log(err));
});
class CustomStates{
static UNSTARTED = -1;
static ENDED = 0;
static PLAYING = 1;
static PAUSED = 2;
static BUFFERING = 3;
static CUED = 5;
//Below are my custom values
static SEEKING = 6;
}
class VideoSource{
static YOUTUBE = 0;
static VIMEO = 2;
static SPOTIFY = 3;
static OTHERONE = 4;
}
class YouTubeSearchManager{
static searchResults = [];
}
app.post('/get-rooms-list', (req, res)=>{
redisMongoQueries.getRoomsList(res, true);
});
app.post('/getYouTubeInfo', (req, res)=>{
const options = [];
ytsrGetOneResult(req.body.videoID, res);
});
app.post('/otherone', (req, res)=>{
//Validate the options before starting the search.
const options = req.body.options ? req.body.options : [];
youtubedl.getInfo(req.body.query, options, (error, info)=>{
if (error || !info){
console.log('==============');
console.log(`Error looking for otherone video ${req.query}.`);
console.log('VVVVVVVVVVVVVVVV');
console.log(`${error}`);
console.log('==============');
res.send({error});
} else {
const resultData = {
videoSource: VideoSource.OTHERONE,
videoState: CustomStates.PLAYING,
videoTitle: info.title || 'Internet Video',
videoTime: 0,
videoID: info.url,
playRate: 1,
thumbnail: NSFW_THUMBNAIL,
videoDuration: undefined
};
redisMongoQueries.updateRoomState(resultData, req.body.roomID);
res.send(resultData);
}
// {
// id: info.id,
// title: info.title,
// url: info.url,
// thumbnail: info.thumbnail,
// description: info.description,
// filename: info._filename,
// format_id: info.format_id
// }
});
});
async function ytsrSearch(query, res){
try{
const searchResults = await ytsr(query, {pages: 1});
const searchData = searchResults.items.filter(item=>item.type === 'video');
searchData.forEach(item=>{
// console.log(JSON.stringify(item, null, 2));
item.thumbnail = item.bestThumbnail.url;
item.videoID = item.id;
item.title = decode(item.title);
item.videoTitle = item.title;
item.channelTitle = decode(item.author.name);
item.description = decode(item.description);
});
res.send(searchData);
} catch (error){
logFailure('get search results', error);
res.send(null);
}
}
async function ytsrGetOneResult(query, res){
if(!query) return;
try{
const searchResults = await ytsr(query, {pages: 1});
const searchData = searchResults.items.filter(item=>item.type === 'video');
const item = searchData[0];
item.thumbnail = item.bestThumbnail.url;
item.videoID = item.id;
item.title = decode(item.title);
item.videoTitle = item.title;
item.channelTitle = decode(item.author.name);
item.description = decode(item.description);
res.send(item);
} catch(error){
res.send(null);
}
}
app.post('/search', function(req, response){
ytsrSearch(req.body.query, response);
});
app.post('/get-search-results', function(req, res){
const results = YouTubeSearchManager.searchResults[req.body.user_id];
if(results){
// results.forEach(result=>console.log(`${new Date().toLocaleTimeString()} Result is: ${JSON.stringify(result, null, 2)}`));
YouTubeSearchManager.searchResults[req.body.user_id] = null;
}// if(results) YouTubeSearchManager.searchResults[req.body.user_id] = null;
res.send(results);
});
app.post('/room-password/:roomID', (req, res)=>{
});