diff --git a/server/app.js b/server/app.js index 58935e10..b28e7027 100644 --- a/server/app.js +++ b/server/app.js @@ -1,146 +1,155 @@ -var cluster = require('cluster'), -net = require('net'), -path = require('path'), -//publicPath = path.join(__dirname, 'public'), -http = require('http'), -port = 8080, -//farmhash = require('farmhash'), -uniqid = require('uniqid'), -num_processes = require('os').cpus().length; +var cluster = require("cluster"), + net = require("net"), + path = require("path"), + //publicPath = path.join(__dirname, 'public'), + http = require("http"), + port = 8080, + //farmhash = require('farmhash'), + uniqid = require("uniqid"), + num_processes = require("os").cpus().length; -publicPath = path.join(__dirname, 'public'); +publicPath = path.join(__dirname, "public"); pathThumbnails = __dirname; - try { - var redis = require("redis"); - var client = redis.createClient({host: "localhost", port: 6379}); - client.on("error", function (err) { - console.log("Couldn't connect to redis-server, assuming non-clustered run"); - num_processes = 1; - startSingle(false, false); - client.quit(); - }); - client.on("connect", function() { - startClustered(true); - client.quit(); - }); -} catch(e) { + var redis = require("redis"); + var client = redis.createClient({ host: "localhost", port: 6379 }); + client.on("error", function(err) { console.log("Couldn't connect to redis-server, assuming non-clustered run"); num_processes = 1; startSingle(false, false); + client.quit(); + }); + client.on("connect", function() { + startClustered(true); + client.quit(); + }); +} catch (e) { + console.log("Couldn't connect to redis-server, assuming non-clustered run"); + num_processes = 1; + startSingle(false, false); } function startClustered(redis_enabled) { - //Found https://stackoverflow.com/questions/40885592/use-node-js-cluster-with-socket-io-chat-application - if (cluster.isMaster) { - var workers = []; - var spawn = function(i) { - workers[i] = cluster.fork(); - workers[i].on('exit', function(code, signal) { - if(code == 1) { - process.exit(1); - return; - } - console.log('respawning worker', i); - spawn(i); - }); - }; - - for (var i = 0; i < num_processes; i++) { - spawn(i); + //Found https://stackoverflow.com/questions/40885592/use-node-js-cluster-with-socket-io-chat-application + if (cluster.isMaster) { + var workers = []; + var spawn = function(i) { + workers[i] = cluster.fork(); + workers[i].on("exit", function(code, signal) { + if (code == 1) { + process.exit(1); + return; } + console.log("respawning worker", i); + spawn(i); + }); + }; - var worker_index = function(ip, len) { - //console.log(ip); - var s = ''; - if(ip == undefined) ip = uniqid.time(); - for (var i = 0, _len = ip.length; i < _len; i++) { - if(!isNaN(ip[i])) { - s += ip[i]; - } - } - return Number(s)%len; - //eturn farmhash.fingerprint32(ip) % len; - }; - - var server = net.createServer({ pauseOnConnect: true }, function(connection, a) { - var worker = workers[worker_index(connection.remoteAddress, num_processes)]; - worker.send('sticky-session:connection', connection); - }).listen(port); - } else { - startSingle(true, redis_enabled); + for (var i = 0; i < num_processes; i++) { + spawn(i); } + + var worker_index = function(ip, len) { + //console.log(ip); + var s = ""; + if (ip == undefined) ip = uniqid.time(); + for (var i = 0, _len = ip.length; i < _len; i++) { + if (!isNaN(ip[i])) { + s += ip[i]; + } + } + return Number(s) % len; + //eturn farmhash.fingerprint32(ip) % len; + }; + + var server = net + .createServer({ pauseOnConnect: true }, function(connection, a) { + var worker = + workers[worker_index(connection.remoteAddress, num_processes)]; + worker.send("sticky-session:connection", connection); + }) + .listen(port); + } else { + startSingle(true, redis_enabled); + } } function startSingle(clustered, redis_enabled) { - var server; - var client = require('./apps/client.js'); + var server; + var client = require("./apps/client.js"); + try { + var cert_config = require(path.join( + path.join(__dirname, "config"), + "cert_config.js" + )); + var fs = require("fs"); + var privateKey = fs.readFileSync(cert_config.privateKey).toString(); + var certificate = fs.readFileSync(cert_config.certificate).toString(); + var ca = fs.readFileSync(cert_config.ca).toString(); + var credentials = { + key: privateKey, + cert: certificate, + ca: ca + }; + var https = require("https"); + server = https.Server(credentials, routingFunction); + } catch (err) { + console.log("Starting without https (probably on localhost)"); + server = http.createServer(routingFunction); + } + + if (clustered) { + server.listen(onListen); + } else { + server.listen(port, onListen); + } + + var socketIO = client.socketIO; + + if (redis_enabled) { + var redis = require("socket.io-redis"); try { - var cert_config = require(path.join(path.join(__dirname, 'config'), 'cert_config.js')); - var fs = require('fs'); - var privateKey = fs.readFileSync(cert_config.privateKey).toString(); - var certificate = fs.readFileSync(cert_config.certificate).toString(); - var ca = fs.readFileSync(cert_config.ca).toString(); - var credentials = { - key: privateKey, - cert: certificate, - ca: ca - }; - var https = require('https'); - server = https.Server(credentials, routingFunction); - } catch(err){ - console.log("Starting without https (probably on localhost)"); - server = http.createServer(routingFunction); + socketIO.adapter(redis({ host: "localhost", port: 6379 })); + } catch (e) { + console.log("No redis-server to connect to.."); } + } + socketIO.listen(server); - if(clustered) { - server.listen(onListen); - } else { - server.listen(port, onListen); + process.on("message", function(message, connection) { + if (message !== "sticky-session:connection") { + return; } - - var socketIO = client.socketIO; - - if(redis_enabled) { - var redis = require('socket.io-redis'); - try { - socketIO.adapter(redis({ host: 'localhost', port: 6379 })); - } catch(e) { - console.log("No redis-server to connect to.."); - } - } - socketIO.listen(server); - - process.on('message', function(message, connection) { - if (message !== 'sticky-session:connection') { - return; - } - server.emit('connection', connection); - connection.resume(); - }); + server.emit("connection", connection); + connection.resume(); + }); } function onListen() { - console.log("Started with pid [" + process.pid + "]"); + console.log("Started with pid [" + process.pid + "]"); } function routingFunction(req, res, next) { - var client = require('./apps/client.js'); - var admin = require('./apps/admin.js'); - try { - var url = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : req.headers.host.split(":")[0]; - var subdomain = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'].split(".") : req.headers.host.split(":")[0].split("."); + var client = require("./apps/client.js"); + var admin = require("./apps/admin.js"); + try { + var url = req.headers["x-forwarded-host"] + ? req.headers["x-forwarded-host"] + : req.headers.host.split(":")[0]; + var subdomain = req.headers["x-forwarded-host"] + ? req.headers["x-forwarded-host"].split(".") + : req.headers.host.split(":")[0].split("."); - if(subdomain.length > 1 && subdomain[0] == "admin") { - admin(req, res, next); - } else { - client(req, res, next); - } - } catch(e) { - console.log("Bad request for " + req.headers.host + req.url, e); - res.statusCode = 500; - res.write('Bad request'); //write a response to the client - res.end(); //end the response + if (subdomain.length > 1 && subdomain[0] == "admin") { + admin(req, res, next); + } else { + client(req, res, next); } + } catch (e) { + console.log("Bad request for " + req.headers.host + req.url, e); + res.statusCode = 500; + res.write("Bad request"); //write a response to the client + res.end(); //end the response + } } diff --git a/server/apps/admin.js b/server/apps/admin.js index e4c4e9c1..fc96fbfd 100644 --- a/server/apps/admin.js +++ b/server/apps/admin.js @@ -1,252 +1,268 @@ -var express = require('express'); +var express = require("express"); var app = express(); -const path = require('path'); -const publicPath = path.join(__dirname + "", '../public'); -var exphbs = require('express-handlebars'); +const path = require("path"); +const publicPath = path.join(__dirname + "", "../public"); +var exphbs = require("express-handlebars"); var hbs = exphbs.create({ - defaultLayout: publicPath + '/layouts/admin/main', - layoutsDir: publicPath + '/layouts', - partialsDir: publicPath + '/partials' + defaultLayout: publicPath + "/layouts/admin/main", + layoutsDir: publicPath + "/layouts", + partialsDir: publicPath + "/partials" }); -var passport = require('passport'); -var mpromise = require('mpromise'); -var LocalStrategy = require('passport-local').Strategy; -var mongoose = require('mongoose'); -var mongo_db_cred = require(pathThumbnails + '/config/mongo_config.js'); -var mongojs = require('mongojs'); +var passport = require("passport"); +var mpromise = require("mpromise"); +var LocalStrategy = require("passport-local").Strategy; +var mongoose = require("mongoose"); +var mongo_db_cred = require(pathThumbnails + "/config/mongo_config.js"); +var mongojs = require("mongojs"); var db = mongojs(mongo_db_cred.config); var token_db = mongojs("tokens"); -var bodyParser = require('body-parser'); -var session = require('express-session'); -var MongoStore = require('connect-mongo')(session); -var api = require(pathThumbnails + '/routing/admin/api.js'); +var bodyParser = require("body-parser"); +var session = require("express-session"); +var MongoStore = require("connect-mongo")(session); +var api = require(pathThumbnails + "/routing/admin/api.js"); -var compression = require('compression'); -var User = require(pathThumbnails + '/models/user.js'); -var url = 'mongodb://' + mongo_db_cred.host + '/' + mongo_db_cred.users; +var compression = require("compression"); +var User = require(pathThumbnails + "/models/user.js"); +var url = "mongodb://" + mongo_db_cred.host + "/" + mongo_db_cred.users; mongoose.connect(url); +app.engine("handlebars", hbs.engine); +app.set("view engine", "handlebars"); +app.use(compression({ filter: shouldCompress })); -app.engine('handlebars', hbs.engine); -app.set('view engine', 'handlebars'); -app.use(compression({filter: shouldCompress})) +function shouldCompress(req, res) { + if (req.headers["x-no-compression"]) { + // don't compress responses with this request header + return false; + } -function shouldCompress (req, res) { - if (req.headers['x-no-compression']) { - // don't compress responses with this request header - return false; - } - - // fallback to standard filter function - return compression.filter(req, res); + // fallback to standard filter function + return compression.filter(req, res); } -app.set('trust proxy', '127.0.0.1'); +app.set("trust proxy", "127.0.0.1"); -var bodyParser = require('body-parser'); +var bodyParser = require("body-parser"); var cookieParser = require("cookie-parser"); -var referrerPolicy = require('referrer-policy'); -var helmet = require('helmet'); -var featurePolicy = require('feature-policy'); -app.use(featurePolicy({ +var referrerPolicy = require("referrer-policy"); +var helmet = require("helmet"); +var featurePolicy = require("feature-policy"); +app.use( + featurePolicy({ features: { - fullscreen: ["*"], - //vibrate: ["'none'"], - payment: ["'none'"], - microphone: ["'none'"], - camera: ["'none'"], - speaker: ["*"], - syncXhr: ["'self'"], - //notifications: ["'self'"] + fullscreen: ["*"], + //vibrate: ["'none'"], + payment: ["'none'"], + microphone: ["'none'"], + camera: ["'none'"], + speaker: ["*"], + syncXhr: ["'self'"] + //notifications: ["'self'"] } -})); -app.use(helmet({ - frameguard: false, -})); -app.use(referrerPolicy({ policy: 'origin-when-cross-origin' })); -app.enable('view cache'); -app.set('views', publicPath); -app.use( bodyParser.json() ); // to support JSON-encoded bodies -app.use(bodyParser.urlencoded({ + }) +); +app.use( + helmet({ + frameguard: false + }) +); +app.use(referrerPolicy({ policy: "origin-when-cross-origin" })); +app.enable("view cache"); +app.set("views", publicPath); +app.use(bodyParser.json()); // to support JSON-encoded bodies +app.use( + bodyParser.urlencoded({ extended: true -})); -app.use(session({ + }) +); +app.use( + session({ secret: mongo_db_cred.secret, resave: true, saveUninitialized: true, store: new MongoStore({ - url: url, - useNewUrlParser: true, - collection: 'sessions', - ttl: mongo_db_cred.expire + url: url, + useNewUrlParser: true, + collection: "sessions", + ttl: mongo_db_cred.expire }) -})); // session secret + }) +); // session secret app.use(passport.initialize()); app.use(passport.session()); // persistent login sessions //app.use('/assets', express.static(publicPath + '/assets')); passport.serializeUser(function(user, done) { - done(null, user.id); + done(null, user.id); }); - - // used to deserialize the user passport.deserializeUser(function(id, done) { - User.findById(id, function(err, user) { - done(err, user); - }); + User.findById(id, function(err, user) { + done(err, user); + }); }); -passport.use('local-signup', new LocalStrategy({ - // by default, local strategy uses username and password, we will override with username - usernameField : 'username', - passwordField : 'password', - passReqToCallback : true // allows us to pass back the entire request to the callback -}, -function(req, username, password, done) { - // asynchronous - // User.findOne wont fire unless data is sent back - process.nextTick(function() { - +passport.use( + "local-signup", + new LocalStrategy( + { + // by default, local strategy uses username and password, we will override with username + usernameField: "username", + passwordField: "password", + passReqToCallback: true // allows us to pass back the entire request to the callback + }, + function(req, username, password, done) { + // asynchronous + // User.findOne wont fire unless data is sent back + process.nextTick(function() { // find a user whose username is the same as the forms username // we are checking to see if the user trying to login already exists var token = req.body.token; - token_db.collection("tokens").find({token: token}, function(err, docs){ - if(docs.length == 1){ - token_db.collection("tokens").remove({token: token}, function(err, docs){ - User.findOne({ 'username' : username }, function(err, user) { - // if there are any errors, return the error - if (err) - return done(err); + token_db + .collection("tokens") + .find({ token: token }, function(err, docs) { + if (docs.length == 1) { + token_db + .collection("tokens") + .remove({ token: token }, function(err, docs) { + User.findOne({ username: username }, function(err, user) { + // if there are any errors, return the error + if (err) return done(err); - // check to see if theres already a user with that username - if (user) { - return done(null, false); - } else { + // check to see if theres already a user with that username + if (user) { + return done(null, false); + } else { + // if there is no user with that username + // create the user + var newUser = new User(); - // if there is no user with that username - // create the user - var newUser = new User(); + // set the user's local credentials + newUser.username = username; + newUser.password = newUser.generateHash(password); - // set the user's local credentials - newUser.username = username; - newUser.password = newUser.generateHash(password); - - // save the user - newUser.save(function(err) { - if (err) - throw err; - return done(null, newUser); - }); - } - - }); + // save the user + newUser.save(function(err) { + if (err) throw err; + return done(null, newUser); + }); + } + }); }); } else { - return done(null, false); + return done(null, false); } - }); - }); + }); + }); + } + ) +); -})); +passport.use( + "local-login", + new LocalStrategy( + { + // by default, local strategy uses username and password, we will override with email + usernameField: "username", + passwordField: "password", + passReqToCallback: true // allows us to pass back the entire request to the callback + }, + function(req, username, password, done) { + // callback with email and password from our form -passport.use('local-login', new LocalStrategy({ - // by default, local strategy uses username and password, we will override with email - usernameField : 'username', - passwordField : 'password', - passReqToCallback : true // allows us to pass back the entire request to the callback -}, function(req, username, password, done) { // callback with email and password from our form - - // find a user whose email is the same as the forms email - // we are checking to see if the user trying to login already exists - User.findOne({ 'username' : username }, function(err, user) { + // find a user whose email is the same as the forms email + // we are checking to see if the user trying to login already exists + User.findOne({ username: username }, function(err, user) { // if there are any errors, return the error before anything else - if (err) - return done(err); + if (err) return done(err); // if no user is found, return the message - if (!user) - return done(null, false); // req.flash is the way to set flashdata using connect-flash + if (!user) return done(null, false); // req.flash is the way to set flashdata using connect-flash // if the user is found but the password is wrong - if (!user.validPassword(password)) - return done(null, false); // create the loginMessage and save it to session as flashdata + if (!user.validPassword(password)) return done(null, false); // create the loginMessage and save it to session as flashdata // all is well, return successful user return done(null, user); - }); - -})); - -app.post('/signup', passport.authenticate('local-signup', { - successRedirect : '/', // redirect to the secure profile section - failureRedirect : '/signup', // redirect back to the signup page if there is an error - failureFlash : true // allow flash messages -})); - -app.post('/login', passport.authenticate('local-login', { - successRedirect : '/', // redirect to the secure profile section - failureRedirect : '/login#failed', // redirect back to the signup page if there is an error - failureFlash : true // allow flash messages -})); - -app.use('/login', isLoggedInTryingToLogIn, function(req, res) { - var data = { - where_get: "not_authenticated" - }; - - res.render('layouts/admin/not_authenticated', data); -}); - -app.use('/signup', isLoggedInTryingToLogIn, function(req, res) { - var data = { - where_get: "not_authenticated" - }; - - res.render('layouts/admin/not_authenticated', data); -}); - -app.use('/', api); - -app.use('/logout', function(req, res) { - req.logout(); - res.redirect('/login'); -}); - -app.use('/assets/admin/authenticated', function(req, res, next) { - if(!req.isAuthenticated()) { - res.sendStatus(403); - return; + }); } + ) +); + +app.post( + "/signup", + passport.authenticate("local-signup", { + successRedirect: "/", // redirect to the secure profile section + failureRedirect: "/signup", // redirect back to the signup page if there is an error + failureFlash: true // allow flash messages + }) +); + +app.post( + "/login", + passport.authenticate("local-login", { + successRedirect: "/", // redirect to the secure profile section + failureRedirect: "/login#failed", // redirect back to the signup page if there is an error + failureFlash: true // allow flash messages + }) +); + +app.use("/login", isLoggedInTryingToLogIn, function(req, res) { + var data = { + where_get: "not_authenticated" + }; + + res.render("layouts/admin/not_authenticated", data); +}); + +app.use("/signup", isLoggedInTryingToLogIn, function(req, res) { + var data = { + where_get: "not_authenticated" + }; + + res.render("layouts/admin/not_authenticated", data); +}); + +app.use("/", api); + +app.use("/logout", function(req, res) { + req.logout(); + res.redirect("/login"); +}); + +app.use("/assets/admin/authenticated", function(req, res, next) { + if (!req.isAuthenticated()) { + res.sendStatus(403); + return; + } + return next(); +}); + +app.use("/assets", express.static(publicPath + "/assets")); + +app.use("/", isLoggedIn, function(req, res) { + var data = { + where_get: "authenticated", + year: new Date().getYear() + 1900 + }; + + res.render("layouts/admin/authenticated", data); +}); + +function isLoggedInTryingToLogIn(req, res, next) { + if (!req.isAuthenticated()) { return next(); -}); - -app.use('/assets', express.static(publicPath + '/assets')); - -app.use('/', isLoggedIn, function(req, res) { - var data = { - where_get: "authenticated", - year: new Date().getYear()+1900, - }; - - res.render('layouts/admin/authenticated', data); -}); - -function isLoggedInTryingToLogIn(req, res, next){ - if(!req.isAuthenticated()){ - return next(); - } - res.redirect("/"); + } + res.redirect("/"); } function isLoggedIn(req, res, next) { - if (req.isAuthenticated()) - return next(); - res.redirect('/login'); + if (req.isAuthenticated()) return next(); + res.redirect("/login"); } //app.listen(default_port); diff --git a/server/apps/client.js b/server/apps/client.js index b863e040..6df020a1 100755 --- a/server/apps/client.js +++ b/server/apps/client.js @@ -1,185 +1,207 @@ -VERSION = require(pathThumbnails + '/VERSION.js'); +VERSION = require(pathThumbnails + "/VERSION.js"); var secure = false; -var path = require('path'); +var path = require("path"); try { - var cert_config = require(path.join(path.join(__dirname, '../config/'), 'cert_config.js')); - var fs = require('fs'); - var privateKey = fs.readFileSync(cert_config.privateKey).toString(); - var certificate = fs.readFileSync(cert_config.certificate).toString(); - var ca = fs.readFileSync(cert_config.ca).toString(); - var credentials = { - key: privateKey, - cert: certificate, - ca: ca - }; - secure = true; -} catch(err){} + var cert_config = require(path.join( + path.join(__dirname, "../config/"), + "cert_config.js" + )); + var fs = require("fs"); + var privateKey = fs.readFileSync(cert_config.privateKey).toString(); + var certificate = fs.readFileSync(cert_config.certificate).toString(); + var ca = fs.readFileSync(cert_config.ca).toString(); + var credentials = { + key: privateKey, + cert: certificate, + ca: ca + }; + secure = true; +} catch (err) {} var add = ""; -var express = require('express'); +var express = require("express"); var app = express(); -var compression = require('compression'); -var exphbs = require('express-handlebars'); -var cors = require('cors'); -var Functions = require(pathThumbnails + '/handlers/functions.js'); +var compression = require("compression"); +var exphbs = require("express-handlebars"); +var cors = require("cors"); +var Functions = require(pathThumbnails + "/handlers/functions.js"); var hbs = exphbs.create({ - defaultLayout: publicPath + '/layouts/client/main', - layoutsDir: publicPath + '/layouts/client', - partialsDir: publicPath + '/partials', - helpers: { - if_equal: function(a, b, opts) { - if (a == b) { - return opts.fn(this) - } else { - return opts.inverse(this) - } - }, - decodeString: function(s) { - if(s == undefined) return s; - return Functions.decodeChannelName(s); - } - + defaultLayout: publicPath + "/layouts/client/main", + layoutsDir: publicPath + "/layouts/client", + partialsDir: publicPath + "/partials", + helpers: { + if_equal: function(a, b, opts) { + if (a == b) { + return opts.fn(this); + } else { + return opts.inverse(this); + } + }, + decodeString: function(s) { + if (s == undefined) return s; + return Functions.decodeChannelName(s); } + } }); -var uniqid = require('uniqid'); -app.use(compression({filter: shouldCompress})) +var uniqid = require("uniqid"); +app.use(compression({ filter: shouldCompress })); -function shouldCompress (req, res) { - if (req.headers['x-no-compression']) { - // don't compress responses with this request header - return false; - } +function shouldCompress(req, res) { + if (req.headers["x-no-compression"]) { + // don't compress responses with this request header + return false; + } - // fallback to standard filter function - return compression.filter(req, res); + // fallback to standard filter function + return compression.filter(req, res); } -app.engine('handlebars', hbs.engine); -app.set('view engine', 'handlebars'); -app.enable('view cache'); -app.set('views', publicPath); -app.set('trust proxy', '127.0.0.1'); +app.engine("handlebars", hbs.engine); +app.set("view engine", "handlebars"); +app.enable("view cache"); +app.set("views", publicPath); +app.set("trust proxy", "127.0.0.1"); -var bodyParser = require('body-parser'); +var bodyParser = require("body-parser"); var cookieParser = require("cookie-parser"); -var referrerPolicy = require('referrer-policy'); -var helmet = require('helmet'); -var featurePolicy = require('feature-policy'); -app.use(featurePolicy({ +var referrerPolicy = require("referrer-policy"); +var helmet = require("helmet"); +var featurePolicy = require("feature-policy"); +app.use( + featurePolicy({ features: { - fullscreen: ["*"], - //vibrate: ["'none'"], - payment: ["'none'"], - microphone: ["'none'"], - camera: ["'none'"], - speaker: ["*"], - syncXhr: ["'self'"], - //notifications: ["'self'"] + fullscreen: ["*"], + //vibrate: ["'none'"], + payment: ["'none'"], + microphone: ["'none'"], + camera: ["'none'"], + speaker: ["*"], + syncXhr: ["'self'"] + //notifications: ["'self'"] } -})); -app.use(helmet({ - frameguard: false, -})); -app.use(referrerPolicy({ policy: 'origin-when-cross-origin' })); -app.use( bodyParser.json() ); // to support JSON-encoded bodies -app.use(bodyParser.urlencoded({ // to support URL-encoded bodies + }) +); +app.use( + helmet({ + frameguard: false + }) +); +app.use(referrerPolicy({ policy: "origin-when-cross-origin" })); +app.use(bodyParser.json()); // to support JSON-encoded bodies +app.use( + bodyParser.urlencoded({ + // to support URL-encoded bodies extended: true -})); + }) +); app.use(cookieParser()); //app.set('json spaces', 2); -io = require('socket.io')({ - pingTimeout: 25000, - //path: '/zoff', - //"origins": ("https://zoff.me:443*,https://zoff.me:8080*,zoff.me:8080*,https://remote.zoff.me:443*,https://remote.zoff.me:8080*,https://fb.zoff.me:443*,https://fb.zoff.me:8080*,https://admin.zoff.me:443*,https://admin.zoff.me:8080*, http://localhost:8080*")}); +io = require("socket.io")({ + pingTimeout: 25000 + //path: '/zoff', + //"origins": ("https://zoff.me:443*,https://zoff.me:8080*,zoff.me:8080*,https://remote.zoff.me:443*,https://remote.zoff.me:8080*,https://fb.zoff.me:443*,https://fb.zoff.me:8080*,https://admin.zoff.me:443*,https://admin.zoff.me:8080*, http://localhost:8080*")}); }); -var socketIO = require(pathThumbnails +'/handlers/io.js'); +var socketIO = require(pathThumbnails + "/handlers/io.js"); socketIO(); app.socketIO = io; - /* Globally needed "libraries" and files */ -var router = require(pathThumbnails + '/routing/client/router.js'); -var api_file = require(pathThumbnails + '/routing/client/api.js'); +var router = require(pathThumbnails + "/routing/client/router.js"); +var api_file = require(pathThumbnails + "/routing/client/api.js"); var api = api_file.router; api_file.sIO = app.socketIO; -var ico_router = require(pathThumbnails + '/routing/client/icons_routing.js'); +var ico_router = require(pathThumbnails + "/routing/client/icons_routing.js"); -app.get('/robots.txt', function (req, res) { - res.type('text/plain'); - res.send("User-agent: *\nAllow: /$\nDisallow: /"); +app.get("/robots.txt", function(req, res) { + res.type("text/plain"); + res.send("User-agent: *\nAllow: /$\nDisallow: /"); }); -app.use(function (req, res, next) { - var cookie = req.cookies._uI; - var skipElements = ["/_embed", "/assets/manifest.json", "/apple-touch-icon.png"]; - if(skipElements.indexOf(req.originalUrl) > -1) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - next(); +app.use(function(req, res, next) { + var cookie = req.cookies._uI; + var skipElements = [ + "/_embed", + "/assets/manifest.json", + "/apple-touch-icon.png" + ]; + if (skipElements.indexOf(req.originalUrl) > -1) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + next(); + } else { + if (req.originalUrl.split("/").length > 3) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + next(); } else { - if(req.originalUrl.split("/").length > 3) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - next(); - } else { - if (cookie === undefined) { - try { - //console.error((new Date), "originalUrl", req.originalUrl); - //console.error((new Date), "couldn't fetch cookie for some reason, maybe no cookie exists?", req.get('origin'), "couldn't fetch cookie for some reason, maybe no cookie exists?"); - - } catch(e) { - //console.error((new Date), "couldn't fetch origin"); - } - var user_name = Functions.hash_pass(Functions.rndName(uniqid.time(), 15)); - res.cookie('_uI', user_name, { - maxAge: 365 * 10000 * 3600000, - httpOnly: true, - secure: secure, - //sameSite: true, - }); - } else { - //process.stderr.write((new Date), "couldn't fetch cookie for some reason, maybe no cookie exists?", req, "couldn't fetch cookie for some reason, maybe no cookie exists?"); - res.cookie('_uI', cookie, { - maxAge: 365 * 10000 * 3600000, - httpOnly: true, - secure: secure, - //sameSite: true, - }); - } - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - next(); + if (cookie === undefined) { + try { + //console.error((new Date), "originalUrl", req.originalUrl); + //console.error((new Date), "couldn't fetch cookie for some reason, maybe no cookie exists?", req.get('origin'), "couldn't fetch cookie for some reason, maybe no cookie exists?"); + } catch (e) { + //console.error((new Date), "couldn't fetch origin"); } + var user_name = Functions.hash_pass( + Functions.rndName(uniqid.time(), 15) + ); + res.cookie("_uI", user_name, { + maxAge: 365 * 10000 * 3600000, + httpOnly: true, + secure: secure + //sameSite: true, + }); + } else { + //process.stderr.write((new Date), "couldn't fetch cookie for some reason, maybe no cookie exists?", req, "couldn't fetch cookie for some reason, maybe no cookie exists?"); + res.cookie("_uI", cookie, { + maxAge: 365 * 10000 * 3600000, + httpOnly: true, + secure: secure + //sameSite: true, + }); + } + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + next(); } + } }); -app.use('/service-worker.js', function(req, res) { - res.sendFile(publicPath + '/service-worker.js'); +app.use("/service-worker.js", function(req, res) { + res.sendFile(publicPath + "/service-worker.js"); }); -app.use('/', ico_router); -app.use('/', api); -app.use('/', cors(), router); +app.use("/", ico_router); +app.use("/", api); +app.use("/", cors(), router); -app.use('/assets/js', function(req, res, next) { - res.sendStatus(403); - return; +app.use("/assets/js", function(req, res, next) { + res.sendStatus(403); + return; }); -app.use('/assets/admin', function(req, res, next) { - res.sendStatus(403); - return; +app.use("/assets/admin", function(req, res, next) { + res.sendStatus(403); + return; }); -app.use('/assets', express.static(publicPath + '/assets')); +app.use("/assets", express.static(publicPath + "/assets")); -app.use(function (req, res, next) { - res.status(404); - res.redirect("/404"); -}) +app.use(function(req, res, next) { + res.status(404); + res.redirect("/404"); +}); module.exports = app; diff --git a/server/config/api_key.example.js b/server/config/api_key.example.js index 1ccbf75d..80858fde 100644 --- a/server/config/api_key.example.js +++ b/server/config/api_key.example.js @@ -1,8 +1,8 @@ var api_key = { - "youtube": "xxxx", - "soundcloud": "xx", + youtube: "xxxx", + soundcloud: "xx" // This can be excluded if you don't have a soundcloud key }; try { - module.exports = api_key; -} catch(e) {} + module.exports = api_key; +} catch (e) {} diff --git a/server/handlers/aggregates.js b/server/handlers/aggregates.js index 2c16bdd3..28cff999 100644 --- a/server/handlers/aggregates.js +++ b/server/handlers/aggregates.js @@ -1,59 +1,62 @@ var toShowConfig = { - "addsongs": true, - "adminpass": 1, - "allvideos": 1, - "frontpage": 1, - "longsongs": 1, - "removeplay": 1, - "shuffle": 1, - "skip": 1, - "startTime": 1, - "userpass": 1, - "vote": 1, - "toggleChat": { $ifNull: [ "$toggleChat", true ] }, - "strictSkip": { $ifNull: [ "$strictSkip", false ] }, - "strictSkipNumber": { $ifNull: [ "$strictSkipNumber", 10 ] }, - "description": { $ifNull: [ "$description", "" ] }, - "thumbnail": { $ifNull: [ "$thumbnail", "" ] }, - "rules": { $ifNull: [ "$rules", "" ] }, - "_id": 0 + addsongs: true, + adminpass: 1, + allvideos: 1, + frontpage: 1, + longsongs: 1, + removeplay: 1, + shuffle: 1, + skip: 1, + startTime: 1, + userpass: 1, + vote: 1, + toggleChat: { $ifNull: ["$toggleChat", true] }, + strictSkip: { $ifNull: ["$strictSkip", false] }, + strictSkipNumber: { $ifNull: ["$strictSkipNumber", 10] }, + description: { $ifNull: ["$description", ""] }, + thumbnail: { $ifNull: ["$thumbnail", ""] }, + rules: { $ifNull: ["$rules", ""] }, + _id: 0 }; var project_object = { - "_id": 0, - "id": 1, - "added": 1, - "now_playing": 1, - "title": 1, - "votes": 1, - "start": 1, - "duration": 1, - "end": 1, - "type": 1, - "source": { $ifNull: [ "$source", "youtube" ] }, - "thumbnail": { - $ifNull: [ "$thumbnail", { - $concat : [ "https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"] - } ] - }, - "tags": { $ifNull: [ "$tags", [] ] }, + _id: 0, + id: 1, + added: 1, + now_playing: 1, + title: 1, + votes: 1, + start: 1, + duration: 1, + end: 1, + type: 1, + source: { $ifNull: ["$source", "youtube"] }, + thumbnail: { + $ifNull: [ + "$thumbnail", + { + $concat: ["https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"] + } + ] + }, + tags: { $ifNull: ["$tags", []] } }; var toShowChannel = { - start: 1, - end: 1, - added: 1, - id: 1, - title: 1, - votes: 1, - duration: 1, - type: 1, - _id: 0, - tags: 1, - now_playing: 1, - type: 1, - source: 1, - thumbnail: 1, + start: 1, + end: 1, + added: 1, + id: 1, + title: 1, + votes: 1, + duration: 1, + type: 1, + _id: 0, + tags: 1, + now_playing: 1, + type: 1, + source: 1, + thumbnail: 1 }; module.exports.project_object = project_object; diff --git a/server/handlers/chat.js b/server/handlers/chat.js index 4f76fe0e..77425f12 100644 --- a/server/handlers/chat.js +++ b/server/handlers/chat.js @@ -1,480 +1,912 @@ -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var crypto = require('crypto'); -var Filter = require('bad-words'); -var filter = new Filter({ placeHolder: 'x'}); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var crypto = require("crypto"); +var Filter = require("bad-words"); +var filter = new Filter({ placeHolder: "x" }); /*var filter = { clean: function(str) { return str; } }*/ -var db = require(pathThumbnails + '/handlers/db.js'); +var db = require(pathThumbnails + "/handlers/db.js"); function get_history(channel, all, socket) { - var query = {}; - if(all) { - query = { - all: true, - }; - } else { - query = { - all: false, - channel: channel, - }; - } - //channel = channel.replace(/ /g,''); - var pass = ""; - if(!query.all) { - Functions.getSessionAdminUser(Functions.getSession(socket), channel, function(userpass) { - if(userpass != "" || pass == undefined) { - pass = userpass - } else { - pass = crypto.createHash('sha256').update(Functions.decrypt_string(pass)).digest('base64') + var query = {}; + if (all) { + query = { + all: true + }; + } else { + query = { + all: false, + channel: channel + }; + } + //channel = channel.replace(/ /g,''); + var pass = ""; + if (!query.all) { + Functions.getSessionAdminUser( + Functions.getSession(socket), + channel, + function(userpass) { + if (userpass != "" || pass == undefined) { + pass = userpass; + } else { + pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(pass)) + .digest("base64"); + } + db.collection(channel + "_settings").find({ id: "config" }, function( + err, + conf + ) { + if (conf.length > 0) { + if (conf[0].userpass == "" || conf[0].userpass == pass) { + getAndSendLogs(channel, all, socket, pass, query); } - db.collection(channel + "_settings").find({id: "config"}, function(err, conf) { - if(conf.length > 0) { - if(conf[0].userpass == "" || conf[0].userpass == pass) { - getAndSendLogs(channel, all, socket, pass, query); - } - } - }); + } }); - } else { - getAndSendLogs(channel, all, socket, pass, query); - } + } + ); + } else { + getAndSendLogs(channel, all, socket, pass, query); + } } function getAndSendLogs(channel, all, socket, pass, query) { - //channel = channel.replace(/ /g,''); - db.collection("chat_logs").find(query, { - from: 1, - createdAt: 1, - all: 1, - channel: 1, - msg: 1, - icon: 1, - _id: 0 - }).sort({createdAt: 1}).limit(20, function(err, docs) { - socket.emit("chat_history", {all: all, data: docs}); + //channel = channel.replace(/ /g,''); + db.collection("chat_logs") + .find(query, { + from: 1, + createdAt: 1, + all: 1, + channel: 1, + msg: 1, + icon: 1, + _id: 0 + }) + .sort({ createdAt: 1 }) + .limit(20, function(err, docs) { + socket.emit("chat_history", { all: all, data: docs }); }); } function chat(msg, guid, offline, socket) { - if(typeof(msg) !== 'object' || !msg.hasOwnProperty('data') || - !msg.hasOwnProperty('channel') || typeof(msg.data) != "string" || typeof(msg.channel) != "string") { - var result = { - data: { - expected: "string", - got: msg.hasOwnProperty("data") ? typeof(msg.data) : undefined, - }, - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined - } - }; - socket.emit('update_required', result); - return; - } - var coll = msg.channel.toLowerCase();//.replace(/ /g,''); - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); + if ( + typeof msg !== "object" || + !msg.hasOwnProperty("data") || + !msg.hasOwnProperty("channel") || + typeof msg.data != "string" || + typeof msg.channel != "string" + ) { + var result = { + data: { + expected: "string", + got: msg.hasOwnProperty("data") ? typeof msg.data : undefined + }, + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined + } + }; + socket.emit("update_required", result); + return; + } + var coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); - checkIfUserIsBanned(coll, socket, guid, function() { - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { - if(userpass != "" || msg.pass == undefined) { - msg.pass = userpass; - } else { - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - db.collection(coll + "_settings").find(function(err, conf){ - if(conf.length > 0 && (conf[0].hasOwnProperty("toggleChat") && !conf[0].toggleChat)) { - socket.emit('chat', {from: "System", msg: ": Chat for this channel has been disabled.", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } else if(conf.length > 0 && (conf[0].userpass == undefined || conf[0].userpass == "" || (msg.hasOwnProperty('pass') && conf[0].userpass == msg.pass))) { - var data = msg.data; + checkIfUserIsBanned(coll, socket, guid, function() { + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass + ) { + if (userpass != "" || msg.pass == undefined) { + msg.pass = userpass; + } else { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + db.collection(coll + "_settings").find(function(err, conf) { + if ( + conf.length > 0 && + (conf[0].hasOwnProperty("toggleChat") && !conf[0].toggleChat) + ) { + socket.emit("chat", { + from: "System", + msg: ": Chat for this channel has been disabled.", + icon: "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; + } else if ( + conf.length > 0 && + (conf[0].userpass == undefined || + conf[0].userpass == "" || + (msg.hasOwnProperty("pass") && conf[0].userpass == msg.pass)) + ) { + var data = msg.data; - Functions.check_inlist(coll, guid, socket, offline, function() { - if(data == "/who") { - db.collection("user_names").distinct("name", {channels: coll}, function(err, docs) { - var userAdd = "s"; - if(docs.length == 1) userAdd = ""; - socket.emit('chat', {from: "System", msg: ": User" + userAdd + " in channel are: " + docs.join(", "), icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - }); - } else if(data !== "" && data !== undefined && data !== null && - data.length < 151 && data.replace(/\s/g, '').length){ - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 1) { - var splitData = data.split(" "); - if((data.startsWith("/ban") && splitData.length >= 3) || (data.startsWith("/unban") && splitData.length >= 2)) { - if(splitData[1].length > 0) { - var passToCompare = Functions.hash_pass(adminpass); - if(passToCompare == conf[0].adminpass) { - db.collection("user_names").find({name: splitData[1]}, function(err, name) { - if(name.length == 1) { - if(data.startsWith("/ban") && splitData.length >= 3) { - var reason = splitData.slice(2, splitData.length).join(" "); - var connection_id = name[0].connection_id; - var yourSelf = Functions.hash_pass(socket.handshake.headers["user-agent"] + socket.handshake.address + socket.handshake.headers["accept-language"]); - if(connection_id != yourSelf) { - db.collection(coll + "_banned_chat").update({ - connection_id: connection_id - }, { - connection_id: connection_id, - by: docs[0].name, - reason: reason - }, { - upsert: true - }, function(err, results) { - io.to(coll).emit('chat', {from: "System", msg: ": " + docs[0].name + " has banned " + splitData[1] + " for: " + reason, icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - }); - } else { - socket.emit('chat', {from: "System", msg: ": I'm sorry but you can't ban yourself..", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } - } else if(data.startsWith("/unban")) { - db.collection(coll + "_banned_chat").remove({connection_id: name[0].connection_id}, function(err, results) { - if(results.hasOwnProperty("n") && results.n == 1 && results.hasOwnProperty("deletedCount") && results.deletedCount == 1) { - io.to(coll).emit('chat', {from: "System", msg: ": " + docs[0].name + " has unbanned " + splitData[1], icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } else { - socket.emit('chat', {from: "System", msg: ": Cannot find anyone with that username in this chat.", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } - - }) - } else if(data.startsWith("/ban") && splitData.length < 3) { - socket.emit('chat', {from: "System", msg: ": You are doing that command wrong. its /ban USERNAME", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } - } else { - socket.emit('chat', {from: "System", msg: ": No user by that name.", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } - }); - } else { - socket.emit('chat', {from: "System", msg: ": You are not logged in as an admin to the channel, don't try any funnybusiness.", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } - } else { - socket.emit('chat', {from: "System", msg: ": You are doing that command wrong. its /ban USERNAME REASON or /unban USERNAME", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - return; - } - } else { - db.collection("registered_users").find({"_id": docs[0].name}, function(err, n) { - var icon = false; - if(n.length > 0 && n[0].icon) { - icon = n[0].icon; - } - db.collection("chat_logs").insert({ "createdAt": new Date(), all: false, channel: coll, from: docs[0].name, msg: ": " + data, icon: icon }); - io.to(coll).emit('chat', {from: docs[0].name, msg: ": " + data, icon: icon}); + Functions.check_inlist( + coll, + guid, + socket, + offline, + function() { + if (data == "/who") { + db.collection("user_names").distinct( + "name", + { channels: coll }, + function(err, docs) { + var userAdd = "s"; + if (docs.length == 1) userAdd = ""; + socket.emit("chat", { + from: "System", + msg: + ": User" + + userAdd + + " in channel are: " + + docs.join(", "), + icon: "https://zoff.me/assets/images/favicon-32x32.png" + }); + } + ); + } else if ( + data !== "" && + data !== undefined && + data !== null && + data.length < 151 && + data.replace(/\s/g, "").length + ) { + db.collection("user_names").find({ guid: guid }, function( + err, + docs + ) { + if (docs.length == 1) { + var splitData = data.split(" "); + if ( + (data.startsWith("/ban") && splitData.length >= 3) || + (data.startsWith("/unban") && splitData.length >= 2) + ) { + if (splitData[1].length > 0) { + var passToCompare = Functions.hash_pass(adminpass); + if (passToCompare == conf[0].adminpass) { + db.collection("user_names").find( + { name: splitData[1] }, + function(err, name) { + if (name.length == 1) { + if ( + data.startsWith("/ban") && + splitData.length >= 3 + ) { + var reason = splitData + .slice(2, splitData.length) + .join(" "); + var connection_id = name[0].connection_id; + var yourSelf = Functions.hash_pass( + socket.handshake.headers["user-agent"] + + socket.handshake.address + + socket.handshake.headers[ + "accept-language" + ] + ); + if (connection_id != yourSelf) { + db.collection(coll + "_banned_chat").update( + { + connection_id: connection_id + }, + { + connection_id: connection_id, + by: docs[0].name, + reason: reason + }, + { + upsert: true + }, + function(err, results) { + io.to(coll).emit("chat", { + from: "System", + msg: + ": " + + docs[0].name + + " has banned " + + splitData[1] + + " for: " + + reason, + icon: + "https://zoff.me/assets/images/favicon-32x32.png" }); + return; + } + ); + } else { + socket.emit("chat", { + from: "System", + msg: + ": I'm sorry but you can't ban yourself..", + icon: + "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; + } + } else if (data.startsWith("/unban")) { + db.collection(coll + "_banned_chat").remove( + { connection_id: name[0].connection_id }, + function(err, results) { + if ( + results.hasOwnProperty("n") && + results.n == 1 && + results.hasOwnProperty( + "deletedCount" + ) && + results.deletedCount == 1 + ) { + io.to(coll).emit("chat", { + from: "System", + msg: + ": " + + docs[0].name + + " has unbanned " + + splitData[1], + icon: + "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; + } else { + socket.emit("chat", { + from: "System", + msg: + ": Cannot find anyone with that username in this chat.", + icon: + "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; + } } - } else if(docs.length == 0){ - get_name(guid, {announce: false, channel: coll, message: data, all: false, socket: socket}); + ); + } else if ( + data.startsWith("/ban") && + splitData.length < 3 + ) { + socket.emit("chat", { + from: "System", + msg: + ": You are doing that command wrong. its /ban USERNAME", + icon: + "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; } - }); + } else { + socket.emit("chat", { + from: "System", + msg: ": No user by that name.", + icon: + "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; + } + } + ); + } else { + socket.emit("chat", { + from: "System", + msg: + ": You are not logged in as an admin to the channel, don't try any funnybusiness.", + icon: + "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; } - }, "place 1"); - } else { - socket.emit('auth_required'); - } - }); - }); + } else { + socket.emit("chat", { + from: "System", + msg: + ": You are doing that command wrong. its /ban USERNAME REASON or /unban USERNAME", + icon: + "https://zoff.me/assets/images/favicon-32x32.png" + }); + return; + } + } else { + db.collection("registered_users").find( + { _id: docs[0].name }, + function(err, n) { + var icon = false; + if (n.length > 0 && n[0].icon) { + icon = n[0].icon; + } + db.collection("chat_logs").insert({ + createdAt: new Date(), + all: false, + channel: coll, + from: docs[0].name, + msg: ": " + data, + icon: icon + }); + io.to(coll).emit("chat", { + from: docs[0].name, + msg: ": " + data, + icon: icon + }); + } + ); + } + } else if (docs.length == 0) { + get_name(guid, { + announce: false, + channel: coll, + message: data, + all: false, + socket: socket + }); + } + }); + } + }, + "place 1" + ); + } else { + socket.emit("auth_required"); + } + }); }); + }); } function all_chat(msg, guid, offline, socket) { - if(typeof(msg) !== 'object' || !msg.hasOwnProperty("channel") || - !msg.hasOwnProperty("data") || typeof(msg.data) != "string" || - typeof(msg.channel) != "string") { - var result = { - data: { - expected: "string", - got: msg.hasOwnProperty("data") ? typeof(msg.data) : undefined, - }, - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined - } - }; - socket.emit('update_required', result); - return; - } - var coll = msg.channel.toLowerCase();//.replace(/ /g,''); - var data = msg.data; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - Functions.check_inlist(coll, guid, socket, offline, function() { - if(data !== "" && data !== undefined && data !== null && - data.length < 151 && data.replace(/\s/g, '').length){ - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 1) { - db.collection("registered_users").find({"_id": docs[0].name}, function(err, n) { - var icon = false; - if(n.length > 0 && n[0].icon) { - icon = n[0].icon; - } - db.collection("chat_logs").insert({ "createdAt": new Date(), all: true, channel: coll, from: docs[0].name, msg: ": " + data, icon: icon }, function(err, docs) {}); - io.sockets.emit('chat.all', {from: docs[0].name, msg: ": " + data, channel: coll, icon: icon}); - }); - } else if(docs.length == 0) { - get_name(guid, {announce: false, channel: coll, message: data, all: true, socket: socket}); + if ( + typeof msg !== "object" || + !msg.hasOwnProperty("channel") || + !msg.hasOwnProperty("data") || + typeof msg.data != "string" || + typeof msg.channel != "string" + ) { + var result = { + data: { + expected: "string", + got: msg.hasOwnProperty("data") ? typeof msg.data : undefined + }, + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + } + }; + socket.emit("update_required", result); + return; + } + var coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + var data = msg.data; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + Functions.check_inlist( + coll, + guid, + socket, + offline, + function() { + if ( + data !== "" && + data !== undefined && + data !== null && + data.length < 151 && + data.replace(/\s/g, "").length + ) { + db.collection("user_names").find({ guid: guid }, function(err, docs) { + if (docs.length == 1) { + db.collection("registered_users").find( + { _id: docs[0].name }, + function(err, n) { + var icon = false; + if (n.length > 0 && n[0].icon) { + icon = n[0].icon; } + db.collection("chat_logs").insert( + { + createdAt: new Date(), + all: true, + channel: coll, + from: docs[0].name, + msg: ": " + data, + icon: icon + }, + function(err, docs) {} + ); + io.sockets.emit("chat.all", { + from: docs[0].name, + msg: ": " + data, + channel: coll, + icon: icon + }); + } + ); + } else if (docs.length == 0) { + get_name(guid, { + announce: false, + channel: coll, + message: data, + all: true, + socket: socket }); - } - }, "place 2"); + } + }); + } + }, + "place 2" + ); } function checkIfChatEnabled(channel, socket, callback) { - if(channel == "" || channel == undefined) callback(); - else { - db.collection(channel + "_settings").find(function(err, docs){ - if(docs.length > 0 && (docs[0].hasOwnProperty("toggleChat") && !docs[0].toggleChat)) { - socket.emit('chat', {from: "System", msg: ": Chat for this channel has been disabled.", icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - callback(false); - } else { - callback(true); - } + if (channel == "" || channel == undefined) callback(); + else { + db.collection(channel + "_settings").find(function(err, docs) { + if ( + docs.length > 0 && + (docs[0].hasOwnProperty("toggleChat") && !docs[0].toggleChat) + ) { + socket.emit("chat", { + from: "System", + msg: ": Chat for this channel has been disabled.", + icon: "https://zoff.me/assets/images/favicon-32x32.png" }); - } + callback(false); + } else { + callback(true); + } + }); + } } function checkIfUserIsBanned(channel, socket, guid, callback, callback_error) { - var connection_id = Functions.hash_pass(socket.handshake.headers["user-agent"] + socket.handshake.address + socket.handshake.headers["accept-language"]); - db.collection(channel + "_banned_chat").find({$or: [{connection_id: connection_id}, {connection_id: guid}]}, function(err, docs) { - if(docs.length == 0) callback(); - else { - db.collection("user_names").findAndModify({query: {guid, guid}, update: {$addToSet:{channels: channel}}}, function(e, d){ - socket.emit('chat', {from: "System", msg: ": You can't chat in this channel, you are banned. The reason is: " + docs[0].reason, icon: "https://zoff.me/assets/images/favicon-32x32.png"}); - if(typeof(callback_error) == "function") callback_error(); - else return; + var connection_id = Functions.hash_pass( + socket.handshake.headers["user-agent"] + + socket.handshake.address + + socket.handshake.headers["accept-language"] + ); + db.collection(channel + "_banned_chat").find( + { $or: [{ connection_id: connection_id }, { connection_id: guid }] }, + function(err, docs) { + if (docs.length == 0) callback(); + else { + db.collection("user_names").findAndModify( + { + query: { guid, guid }, + update: { $addToSet: { channels: channel } } + }, + function(e, d) { + socket.emit("chat", { + from: "System", + msg: + ": You can't chat in this channel, you are banned. The reason is: " + + docs[0].reason, + icon: "https://zoff.me/assets/images/favicon-32x32.png" }); - } - }) + if (typeof callback_error == "function") callback_error(); + else return; + } + ); + } + } + ); } function namechange(data, guid, socket, tried, callback) { - checkIfChatEnabled(data.channel, socket, function(enabled) { - if(!enabled) { - callback(false); + checkIfChatEnabled(data.channel, socket, function(enabled) { + if (!enabled) { + callback(false); + return; + } + checkIfUserIsBanned( + data.channel, + socket, + guid, + function() { + var pw = ""; + var new_password; + var first = false; + Functions.getSessionChatPass(Functions.getSession(socket), function( + name, + pass + ) { + var fetched = false; + if (data.hasOwnProperty("first") && data.first) { + pw = pass; + name = name; + data.name = name; + data.password = pass; + new_password = false; + if (name == "" || pass == "") { + if (typeof callback == "function") callback(true); + return; + } + fetched = true; + password = pw; + } else { + var name = data.name; + if (data.hasOwnProperty("first")) { + first = data.first; + } + if (data.hasOwnProperty("password")) { + pw = data.password; + new_password = false; + } else if ( + data.hasOwnProperty("new_password") && + data.hasOwnProperty("old_password") + ) { + pw = data.old_password; + new_password = Functions.decrypt_string(data.new_password); + } + password = Functions.decrypt_string(pw); + password = Functions.hash_pass(password); + doubled = true; + } + + if (name == "") { + if (typeof callback == "function") callback(true); return; - } - checkIfUserIsBanned(data.channel, socket, guid, function() { - var pw = ""; - var new_password; - var first = false; - Functions.getSessionChatPass(Functions.getSession(socket), function(name, pass) { - var fetched = false; - if(data.hasOwnProperty("first") && data.first) { - pw = pass; - name = name; - data.name = name; - data.password = pass; - new_password = false; - if(name == "" || pass == "") { - if(typeof(callback) == "function") callback(true); - return; + } + + db.collection("registered_users").find( + { _id: name.toLowerCase() }, + function(err, docs) { + var accepted_password = false; + var icon = false; + if (docs.length == 0) { + if (new_password) { + if (typeof callback == "function") callback(true); + return; + } + accepted_password = true; + Functions.setSessionChatPass( + Functions.getSession(socket), + name.toLowerCase(), + data.password, + function() { + db.collection("registered_users").update( + { _id: name.toLowerCase() }, + { $set: { password: password } }, + { upsert: true }, + function() {} + ); + } + ); + } else if (docs[0].password == password) { + if (docs[0].icon) { + icon = docs[0].icon; + } + accepted_password = true; + if (new_password) { + Functions.setSessionChatPass( + Functions.getSession(socket), + name.toLowerCase(), + data.new_password, + function() { + db.collection("registered_users").update( + { _id: name.toLowerCase(), password: password }, + { + $set: { password: Functions.hash_pass(new_password) } + }, + function() {} + ); } - fetched = true; - password = pw; + ); } else { - var name = data.name; - if(data.hasOwnProperty("first")) { - first = data.first; - } - if(data.hasOwnProperty("password")) { - pw = data.password; - new_password = false; - } else if(data.hasOwnProperty("new_password") && data.hasOwnProperty("old_password")) { - pw = data.old_password; - new_password = Functions.decrypt_string(data.new_password); - } - password = Functions.decrypt_string(pw); - password = Functions.hash_pass(password); - doubled = true; + Functions.setSessionChatPass( + Functions.getSession(socket), + name.toLowerCase(), + fetched + ? data.password + : Functions.hash_pass( + Functions.decrypt_string(data.password) + ), + function() {} + ); } - - if(name == "") { - if(typeof(callback) == "function") callback(true); - return; - } - - - db.collection("registered_users").find({"_id": name.toLowerCase()}, function(err, docs) { - var accepted_password = false; - var icon = false; - if(docs.length == 0) { - if(new_password) { - if(typeof(callback) == "function") callback(true); - return; - } - accepted_password = true; - Functions.setSessionChatPass(Functions.getSession(socket), name.toLowerCase(), data.password, function() { - db.collection("registered_users").update({"_id": name.toLowerCase()}, {$set: {password: password}}, {upsert: true}, function() { - }); - }); - } else if(docs[0].password == password) { - if(docs[0].icon) { - icon = docs[0].icon; - } - accepted_password = true; - if(new_password) { - Functions.setSessionChatPass(Functions.getSession(socket), name.toLowerCase(), data.new_password, function() { - - db.collection("registered_users").update({"_id": name.toLowerCase(), password: password}, {$set: {password: Functions.hash_pass(new_password)}}, function() { - - }); - }); - } else { - Functions.setSessionChatPass(Functions.getSession(socket), name.toLowerCase(), fetched ? data.password : Functions.hash_pass(Functions.decrypt_string(data.password)), function() { - }); - } + } + if (accepted_password) { + db.collection("user_names").find({ guid: guid }, function( + err, + names + ) { + if ( + names.length > 0 || + (docs.length != 0 && docs[0].password == password) + ) { + var no_name = false; + if (names.length == 0) no_name = true; + if (!no_name) { + var old_name = names[0].name; + db.collection("user_names").update( + { _id: "all_names" }, + { $pull: { names: old_name } }, + function() {} + ); } - if(accepted_password) { - - db.collection("user_names").find({"guid": guid}, function(err, names) { - if(names.length > 0 || (docs.length != 0 && docs[0].password == password)) { - var no_name = false; - if(names.length == 0) no_name = true; - if(!no_name) { - var old_name = names[0].name; - db.collection("user_names").update({"_id": "all_names"}, {$pull: {names: old_name}}, function() {}); - } - var connection_id = Functions.hash_pass(socket.handshake.headers["user-agent"] + socket.handshake.address + socket.handshake.headers["accept-language"]); - var updateElement = {$set: {name: name, icon: icon, connection_id: connection_id}}; - if(data.hasOwnProperty("channel") && data.channel != "") { - updateElement["$addToSet"] = {channels: data.channel}; - } - db.collection("user_names").update({"guid": guid}, updateElement, {upsert: true}, function(err, docs) { - db.collection("user_names").update({"_id": "all_names"}, {$addToSet: {names: name}}, function(err, docs) { - //socket.emit('name', {type: "name", accepted: true}); - if(old_name != name && !first && !no_name) { - if(data.hasOwnProperty("channel") && typeof(data.channel) == "string") { - io.to(data.channel).emit('chat', {from: old_name, msg: " changed name to " + name}); - io.sockets.emit('chat.all', {from: old_name , msg: " changed name to " + name, channel: data.channel}); - } - } - if(callback != undefined && typeof(callback) == "function") callback(true); - }); + var connection_id = Functions.hash_pass( + socket.handshake.headers["user-agent"] + + socket.handshake.address + + socket.handshake.headers["accept-language"] + ); + var updateElement = { + $set: { + name: name, + icon: icon, + connection_id: connection_id + } + }; + if (data.hasOwnProperty("channel") && data.channel != "") { + updateElement["$addToSet"] = { channels: data.channel }; + } + db.collection("user_names").update( + { guid: guid }, + updateElement, + { upsert: true }, + function(err, docs) { + db.collection("user_names").update( + { _id: "all_names" }, + { $addToSet: { names: name } }, + function(err, docs) { + //socket.emit('name', {type: "name", accepted: true}); + if (old_name != name && !first && !no_name) { + if ( + data.hasOwnProperty("channel") && + typeof data.channel == "string" + ) { + io.to(data.channel).emit("chat", { + from: old_name, + msg: " changed name to " + name }); - } else { - if(tried < 3 || tried == undefined) { - if(tried == undefined) { - tried = 1; - } - namechange(data, guid, socket, tried + 1); - } + io.sockets.emit("chat.all", { + from: old_name, + msg: " changed name to " + name, + channel: data.channel + }); + } } - }); - } else { - Functions.removeSessionChatPass(Functions.getSession(socket), function() { - socket.emit('name', {type: "name", accepted: false}); - }); + if ( + callback != undefined && + typeof callback == "function" + ) + callback(true); + } + ); + } + ); + } else { + if (tried < 3 || tried == undefined) { + if (tried == undefined) { + tried = 1; + } + namechange(data, guid, socket, tried + 1); } + } }); - }); - }, callback); - }); + } else { + Functions.removeSessionChatPass( + Functions.getSession(socket), + function() { + socket.emit("name", { type: "name", accepted: false }); + } + ); + } + } + ); + }); + }, + callback + ); + }); } function removename(guid, coll, socket) { - //coll = coll.replace(/ /g,''); - checkIfChatEnabled(coll, socket, function(enabled) { - if(!enabled) return; - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 1) { - var old_name = docs[0].name; - Functions.removeSessionChatPass(Functions.getSession(socket), function() { - db.collection("user_names").update({"_id": "all_names"}, {$pull: {names: old_name}}, function(err, updated) { - db.collection("user_names").remove({"guid": guid}, function(err, removed) { - get_name(guid, {announce: true, old_name: old_name, channel: coll, socket: socket}); - }); - }); + //coll = coll.replace(/ /g,''); + checkIfChatEnabled(coll, socket, function(enabled) { + if (!enabled) return; + db.collection("user_names").find({ guid: guid }, function(err, docs) { + if (docs.length == 1) { + var old_name = docs[0].name; + Functions.removeSessionChatPass( + Functions.getSession(socket), + function() { + db.collection("user_names").update( + { _id: "all_names" }, + { $pull: { names: old_name } }, + function(err, updated) { + db.collection("user_names").remove({ guid: guid }, function( + err, + removed + ) { + get_name(guid, { + announce: true, + old_name: old_name, + channel: coll, + socket: socket + }); }); - } - }); + } + ); + } + ); + } }); + }); } function generate_name(guid, announce_payload, second, round, channel) { - if(round == undefined) round = 0; - var tmp_name = Functions.rndName(second ? second : guid, Math.floor(8 + round)); - db.collection("registered_users").find({"_id": tmp_name}, function(err, docs) { - if(docs.length == 0) { - db.collection("user_names").update({"_id": "all_names"}, {$addToSet: {names: tmp_name}}, {upsert: true}, function(err, updated) { - if(updated.nModified == 1 || (updated.hasOwnProperty("upserted") && updated.hasOwnProperty("n") && updated.n == 1)) { - var connection_id = Functions.hash_pass(announce_payload.socket.handshake.headers["user-agent"] + announce_payload.socket.handshake.address + announce_payload.socket.handshake.headers["accept-language"]); - var updateElement = {$set: {name: tmp_name, icon: false, connection_id: connection_id}}; - if(channel != undefined && channel != "") { - updateElement["$addToSet"] = {channels: channel}; - } - if(announce_payload.hasOwnProperty("channel") && announce_payload.channel != "") { - updateElement["$addToSet"] = {channels: announce_payload.channel}; - } - db.collection("user_names").update({"guid": guid}, updateElement, {upsert: true}, function(err, update){ - name = tmp_name; - if(announce_payload.announce) { - io.to(announce_payload.channel).emit('chat', {from: announce_payload.old_name, msg: " changed name to " + name}); - io.sockets.emit('chat.all', {from: announce_payload.old_name , msg: " changed name to " + name, channel: announce_payload.channel}); - } else if(announce_payload.message && !announce_payload.all) { - io.to(announce_payload.channel).emit('chat', {from: name, msg: ": " + announce_payload.message}); - } else if(announce_payload.message && announce_payload.all) { - io.sockets.emit('chat.all', {from: name, msg: ": " + announce_payload.message, channel: announce_payload.channel}); - } - }); - } else { - generate_name(guid, announce_payload, tmp_name, round + 0.25, channel); + if (round == undefined) round = 0; + var tmp_name = Functions.rndName( + second ? second : guid, + Math.floor(8 + round) + ); + db.collection("registered_users").find({ _id: tmp_name }, function( + err, + docs + ) { + if (docs.length == 0) { + db.collection("user_names").update( + { _id: "all_names" }, + { $addToSet: { names: tmp_name } }, + { upsert: true }, + function(err, updated) { + if ( + updated.nModified == 1 || + (updated.hasOwnProperty("upserted") && + updated.hasOwnProperty("n") && + updated.n == 1) + ) { + var connection_id = Functions.hash_pass( + announce_payload.socket.handshake.headers["user-agent"] + + announce_payload.socket.handshake.address + + announce_payload.socket.handshake.headers["accept-language"] + ); + var updateElement = { + $set: { + name: tmp_name, + icon: false, + connection_id: connection_id + } + }; + if (channel != undefined && channel != "") { + updateElement["$addToSet"] = { channels: channel }; + } + if ( + announce_payload.hasOwnProperty("channel") && + announce_payload.channel != "" + ) { + updateElement["$addToSet"] = { + channels: announce_payload.channel + }; + } + db.collection("user_names").update( + { guid: guid }, + updateElement, + { upsert: true }, + function(err, update) { + name = tmp_name; + if (announce_payload.announce) { + io.to(announce_payload.channel).emit("chat", { + from: announce_payload.old_name, + msg: " changed name to " + name + }); + io.sockets.emit("chat.all", { + from: announce_payload.old_name, + msg: " changed name to " + name, + channel: announce_payload.channel + }); + } else if (announce_payload.message && !announce_payload.all) { + io.to(announce_payload.channel).emit("chat", { + from: name, + msg: ": " + announce_payload.message + }); + } else if (announce_payload.message && announce_payload.all) { + io.sockets.emit("chat.all", { + from: name, + msg: ": " + announce_payload.message, + channel: announce_payload.channel + }); } - }) - } else { - generate_name(guid, announce_payload, tmp_name, round + 0.25, channel); + } + ); + } else { + generate_name( + guid, + announce_payload, + tmp_name, + round + 0.25, + channel + ); + } } - }) + ); + } else { + generate_name(guid, announce_payload, tmp_name, round + 0.25, channel); + } + }); } function get_name(guid, announce_payload, first) { - if(!announce_payload.announce && announce_payload.hasOwnProperty("socket")) { - Functions.getSessionChatPass(Functions.getSession(announce_payload.socket), function(name, pass) { - if(name == "" || pass == "") { - get_name_generate(guid, announce_payload, first, announce_payload.channel); - return; - } - db.collection("registered_users").find({"_id": name.toLowerCase()}, function(err, docs) { - if(docs[0].password == Functions.hash_pass(Functions.decrypt_string(pass))) { - var icon = false; - if(docs[0].icon) { - icon = docs[0].icon; + if (!announce_payload.announce && announce_payload.hasOwnProperty("socket")) { + Functions.getSessionChatPass( + Functions.getSession(announce_payload.socket), + function(name, pass) { + if (name == "" || pass == "") { + get_name_generate( + guid, + announce_payload, + first, + announce_payload.channel + ); + return; + } + db.collection("registered_users").find( + { _id: name.toLowerCase() }, + function(err, docs) { + if ( + docs[0].password == + Functions.hash_pass(Functions.decrypt_string(pass)) + ) { + var icon = false; + if (docs[0].icon) { + icon = docs[0].icon; + } + Functions.setSessionChatPass( + Functions.getSession(announce_payload.socket), + name.toLowerCase(), + pass, + function() {} + ); + var connection_id = Functions.hash_pass( + announce_payload.socket.handshake.headers["user-agent"] + + announce_payload.socket.handshake.address + + announce_payload.socket.handshake.headers["accept-language"] + ); + var updateElement = { + $set: { name: name, icon: icon, connection_id: connection_id } + }; + if ( + announce_payload.hasOwnProperty("channel") && + announce_payload.channel != "" + ) + updateElement["$addToSet"] = { + channel: announce_payload.channel + }; + db.collection("user_names").update( + { guid: guid }, + updateElement, + { upsert: true }, + function(err, docs) { + db.collection("user_names").update( + { _id: "all_names" }, + { $addToSet: { names: name } }, + function(err, docs) { + name = name; } - Functions.setSessionChatPass(Functions.getSession(announce_payload.socket), name.toLowerCase(), pass, function() { - }); - var connection_id = Functions.hash_pass(announce_payload.socket.handshake.headers["user-agent"] + announce_payload.socket.handshake.address + announce_payload.socket.handshake.headers["accept-language"]); - var updateElement = {$set: {name: name, icon: icon, connection_id: connection_id}}; - if(announce_payload.hasOwnProperty("channel") && announce_payload.channel != "") updateElement["$addToSet"] = {channel: announce_payload.channel}; - db.collection("user_names").update({"guid": guid}, updateElement, {upsert: true}, function(err, docs) { - db.collection("user_names").update({"_id": "all_names"}, {$addToSet: {names: name}}, function(err, docs) { - name = name; - }); - }); + ); } - }); - }); - } else { - get_name_generate(guid, announce_payload, first, announce_payload.channel); - } + ); + } + } + ); + } + ); + } else { + get_name_generate(guid, announce_payload, first, announce_payload.channel); + } } function get_name_generate(guid, announce_payload, first, channel) { - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 0) { - generate_name(guid, announce_payload, undefined); - } else { - name = docs[0].name; - } - }); + db.collection("user_names").find({ guid: guid }, function(err, docs) { + if (docs.length == 0) { + generate_name(guid, announce_payload, undefined); + } else { + name = docs[0].name; + } + }); } module.exports.get_history = get_history; diff --git a/server/handlers/db.js b/server/handlers/db.js index a4f57d6c..d66d68c2 100644 --- a/server/handlers/db.js +++ b/server/handlers/db.js @@ -1,39 +1,84 @@ -var path = require('path'); +var path = require("path"); try { - var mongo_config = require(path.join(path.join(__dirname, '../config/'), 'mongo_config.js')); -} catch(e) { - console.log("Error - missing file"); - console.log("Seems you forgot to create the file mongo_config.js in /server/config/. Have a look at mongo_config.example.js."); - process.exit(1); + var mongo_config = require(path.join( + path.join(__dirname, "../config/"), + "mongo_config.js" + )); +} catch (e) { + console.log( + "(!) Missing file - /config/mongo_config.js. Have a look at /config/mongo_config.example.js. The server won't run without this existing." + ); + process.exit(1); } -var mongojs = require('mongojs'); -var db = mongojs('mongodb://' + mongo_config.host + '/' + mongo_config.config); -var connected_db = mongojs('mongodb://' + mongo_config.host + '/user_credentials'); +var mongojs = require("mongojs"); +var db = mongojs("mongodb://" + mongo_config.host + "/" + mongo_config.config); +var connected_db = mongojs( + "mongodb://" + mongo_config.host + "/user_credentials" +); var ObjectId = mongojs.ObjectId; -db.collection("chat_logs").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 600 }, function(){}); -db.collection("timeout_api").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 120 }, function(){}); -db.collection("api_links").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 86400 }, function(){}); -db.on('connected', function(err) { - console.log("connected"); +db.collection("chat_logs").createIndex( + { createdAt: 1 }, + { expireAfterSeconds: 600 }, + function() {} +); +db.collection("timeout_api").createIndex( + { createdAt: 1 }, + { expireAfterSeconds: 120 }, + function() {} +); +db.collection("api_links").createIndex( + { createdAt: 1 }, + { expireAfterSeconds: 86400 }, + function() {} +); +db.on("connected", function(err) { + console.log("connected"); }); -db.on('error',function(err) { - console.log("\n" + new Date().toString() + "\n Database error: ", err); +db.on("error", function(err) { + console.log("\n" + new Date().toString() + "\n Database error: ", err); }); - -db.on('error',function(err) { - console.log("\n" + new Date().toString() + "\n Database error: ", err); +db.on("error", function(err) { + console.log("\n" + new Date().toString() + "\n Database error: ", err); }); /* Resetting usernames, and connected users */ -db.collection("unique_ids").update({"_id": "unique_ids"}, {$set: {unique_ids: []}}, {multi: true, upsert: true}, function(err, docs){}); -db.collection("user_names").remove({"guid": {$exists: true}}, {multi: true, upsert: true}, function(err, docs){}); -db.collection("user_names").update({"_id": "all_names"}, {$set: {names: []}}, {multi: true, upsert: true}, function(err, docs){}); -db.collection("connected_users").update({users: {$exists: true}}, {$set: {users: []}}, {multi: true, upsert: true}, function(err, docs){}); -db.collection("connected_users").update({"_id": "total_users"}, {$set: {total_users: []}}, {multi: true, upsert: true}, function(err, docs) {}); -db.collection("frontpage_lists").update({viewers: {$ne: 0}}, {$set: {"viewers": 0}}, {multi: true, upsert: true}, function(err, docs) {}); - +db.collection("unique_ids").update( + { _id: "unique_ids" }, + { $set: { unique_ids: [] } }, + { multi: true, upsert: true }, + function(err, docs) {} +); +db.collection("user_names").remove( + { guid: { $exists: true } }, + { multi: true, upsert: true }, + function(err, docs) {} +); +db.collection("user_names").update( + { _id: "all_names" }, + { $set: { names: [] } }, + { multi: true, upsert: true }, + function(err, docs) {} +); +db.collection("connected_users").update( + { users: { $exists: true } }, + { $set: { users: [] } }, + { multi: true, upsert: true }, + function(err, docs) {} +); +db.collection("connected_users").update( + { _id: "total_users" }, + { $set: { total_users: [] } }, + { multi: true, upsert: true }, + function(err, docs) {} +); +db.collection("frontpage_lists").update( + { viewers: { $ne: 0 } }, + { $set: { viewers: 0 } }, + { multi: true, upsert: true }, + function(err, docs) {} +); module.exports = db; diff --git a/server/handlers/frontpage.js b/server/handlers/frontpage.js index d010c0b6..2818a272 100644 --- a/server/handlers/frontpage.js +++ b/server/handlers/frontpage.js @@ -1,104 +1,143 @@ -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var db = require(pathThumbnails + '/handlers/db.js'); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var db = require(pathThumbnails + "/handlers/db.js"); function frontpage_lists(msg, socket) { - if(msg == undefined || !msg.hasOwnProperty('version') || msg.version != VERSION || msg.version == undefined) { - var result = { - version: { - expected: VERSION, - got: msg.hasOwnProperty("version") ? msg.version : undefined, - } - }; - socket.emit('update_required', result); - return; - } + if ( + msg == undefined || + !msg.hasOwnProperty("version") || + msg.version != VERSION || + msg.version == undefined + ) { + var result = { + version: { + expected: VERSION, + got: msg.hasOwnProperty("version") ? msg.version : undefined + } + }; + socket.emit("update_required", result); + return; + } - db.collection("frontpage_lists").find({frontpage:true}, function(err, docs){ - db.collection("connected_users").find({"_id": "total_users"}, function(err, tot){ - socket.compress(true).emit("playlists", {channels: docs, viewers: tot[0].total_users.length}); + db.collection("frontpage_lists").find({ frontpage: true }, function( + err, + docs + ) { + db.collection("connected_users").find({ _id: "total_users" }, function( + err, + tot + ) { + socket + .compress(true) + .emit("playlists", { + channels: docs, + viewers: tot[0].total_users.length }); }); + }); } function get_frontpage_lists(callback) { - var project_object = { - "_id": 1, - "count": 1, - "frontpage": 1, - "id": 1, - "title": 1, - "viewers": 1, - "accessed": 1, - "pinned": { $ifNull: [ "$pinned", 0 ] }, - "description": { - $ifNull: [ {$cond: { - "if": { - "$or": [ - { "$eq": [ "$description", ""] }, - { "$eq": [ "$description", null] }, - { "$eq": [ "$description", undefined] } - ] - }, - then: "This list has no description", - else: "$description" - }}, "This list has no description"] - + var project_object = { + _id: 1, + count: 1, + frontpage: 1, + id: 1, + title: 1, + viewers: 1, + accessed: 1, + pinned: { $ifNull: ["$pinned", 0] }, + description: { + $ifNull: [ + { + $cond: { + if: { + $or: [ + { $eq: ["$description", ""] }, + { $eq: ["$description", null] }, + { $eq: ["$description", undefined] } + ] + }, + then: "This list has no description", + else: "$description" + } }, - "thumbnail": { - $ifNull: [ {$cond: { - "if": { - "$or": [ - { "$eq": [ "$thumbnail", ""] }, - { "$eq": [ "$thumbnail", null] }, - { "$eq": [ "$thumbnail", undefined] } - ] - }, - then: { - $concat : [ "https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"] - }, - else: "$thumbnail" - }}, { $concat : [ "https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"]}] - + "This list has no description" + ] + }, + thumbnail: { + $ifNull: [ + { + $cond: { + if: { + $or: [ + { $eq: ["$thumbnail", ""] }, + { $eq: ["$thumbnail", null] }, + { $eq: ["$thumbnail", undefined] } + ] + }, + then: { + $concat: ["https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"] + }, + else: "$thumbnail" + } + }, + { $concat: ["https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"] } + ] + } + }; + db.collection("frontpage_lists").aggregate( + [ + { + $match: { + frontpage: true, + count: { $gt: 3 } } - }; - db.collection("frontpage_lists").aggregate([ - { - "$match": { - frontpage: true, - count: {$gt: 3}, - } - }, - { - "$project": project_object - }, - { - "$sort" : { - "pinned": -1, - "viewers": -1, - "accessed": -1, - "count": -1, - "title": 1 - } - }, - ], callback); + }, + { + $project: project_object + }, + { + $sort: { + pinned: -1, + viewers: -1, + accessed: -1, + count: -1, + title: 1 + } + } + ], + callback + ); } function update_frontpage(coll, id, title, thumbnail, source, callback) { - //coll = coll.replace(/ /g,''); - db.collection("frontpage_lists").find({_id: coll}, function(e, doc) { - var updateObject = { - id: id, - title: title, - accessed: Functions.get_time() - }; -if(doc.length > 0 && ((doc[0].thumbnail != "" && doc[0].thumbnail != undefined && (doc[0].thumbnail.indexOf("https://i1.sndcdn.com") > -1 || doc[0].thumbnail.indexOf("https://w1.sndcdn.com") > -1 || doc[0].thumbnail.indexOf("https://img.youtube.com") > -1)) || (doc[0].thumbnail == "" || doc[0].thumbnail == undefined))) { - updateObject.thumbnail = thumbnail; - if(thumbnail == undefined) updateObject.thumbnail = ""; - } - db.collection("frontpage_lists").update({_id: coll}, {$set: updateObject - },{upsert: true}, function(err, returnDocs){ - if(typeof(callback) == "function") callback(); - }); - }); + //coll = coll.replace(/ /g,''); + db.collection("frontpage_lists").find({ _id: coll }, function(e, doc) { + var updateObject = { + id: id, + title: title, + accessed: Functions.get_time() + }; + if ( + doc.length > 0 && + ((doc[0].thumbnail != "" && + doc[0].thumbnail != undefined && + (doc[0].thumbnail.indexOf("https://i1.sndcdn.com") > -1 || + doc[0].thumbnail.indexOf("https://w1.sndcdn.com") > -1 || + doc[0].thumbnail.indexOf("https://img.youtube.com") > -1)) || + (doc[0].thumbnail == "" || doc[0].thumbnail == undefined)) + ) { + updateObject.thumbnail = thumbnail; + if (thumbnail == undefined) updateObject.thumbnail = ""; + } + db.collection("frontpage_lists").update( + { _id: coll }, + { $set: updateObject }, + { upsert: true }, + function(err, returnDocs) { + if (typeof callback == "function") callback(); + } + ); + }); } module.exports.get_frontpage_lists = get_frontpage_lists; diff --git a/server/handlers/functions.js b/server/handlers/functions.js index da8ec299..b0664447 100644 --- a/server/handlers/functions.js +++ b/server/handlers/functions.js @@ -1,482 +1,685 @@ -var path = require('path'); +var path = require("path"); try { - var mongo_config = require(path.join(path.join(__dirname, '../config/'), 'mongo_config.js')); -} catch(e) { - console.log("Error - missing file"); - console.log("Seems you forgot to create the file mongo_config.js in /server/config/. Have a look at mongo_config.example.js."); - process.exit(1); + var mongo_config = require(path.join( + path.join(__dirname, "../config/"), + "mongo_config.js" + )); +} catch (e) { + console.log( + "(!) Missing file - /config/mongo_config.js. Have a look at /config/mongo_config.example.js. The server won't run without this existing." + ); + process.exit(1); } -var mongojs = require('mongojs'); -var connected_db = mongojs('mongodb://' + mongo_config.host + '/user_credentials'); -var crypto = require('crypto'); -var db = require(pathThumbnails + '/handlers/db.js'); -var uniqid = require('uniqid'); -var Filter = require('bad-words'); -var filter = new Filter({ placeHolder: 'x'}); +var mongojs = require("mongojs"); +var connected_db = mongojs( + "mongodb://" + mongo_config.host + "/user_credentials" +); +var crypto = require("crypto"); +var db = require(pathThumbnails + "/handlers/db.js"); +var uniqid = require("uniqid"); +var Filter = require("bad-words"); +var filter = new Filter({ placeHolder: "x" }); -var Chat = require(pathThumbnails + '/handlers/chat.js'); +var Chat = require(pathThumbnails + "/handlers/chat.js"); function encodeChannelName(str) { - var _fn = encodeURIComponent; - str = filter.clean(str); - var toReturn = _fn(str); - toReturn = toReturn.replace(/_/g, "%5F"); - toReturn = toReturn.replace(/'/g, "%27"); - toReturn = toReturn.replace(/%26amp%3B/g, "%26").replace(/%26amp%3b/g, "%26"); - toReturn = toReturn.toLowerCase(); - return toReturn; + var _fn = encodeURIComponent; + str = filter.clean(str); + var toReturn = _fn(str); + toReturn = toReturn.replace(/_/g, "%5F"); + toReturn = toReturn.replace(/'/g, "%27"); + toReturn = toReturn.replace(/%26amp%3B/g, "%26").replace(/%26amp%3b/g, "%26"); + toReturn = toReturn.toLowerCase(); + return toReturn; } function decodeChannelName(str) { - var _fn = decodeURIComponent; - str = str.toUpperCase(); - var toReturn = _fn(str.replace(/%5F/g, "_").replace(/%27/g, "'")); - toReturn = filter.clean(toReturn); - return toReturn.toLowerCase(); + var _fn = decodeURIComponent; + str = str.toUpperCase(); + var toReturn = _fn(str.replace(/%5F/g, "_").replace(/%27/g, "'")); + toReturn = filter.clean(toReturn); + return toReturn.toLowerCase(); } function remove_unique_id(short_id) { - db.collection("unique_ids").update({"_id": "unique_ids"}, {$pull: {unique_ids: short_id}}, function(err, docs) {}); + db.collection("unique_ids").update( + { _id: "unique_ids" }, + { $pull: { unique_ids: short_id } }, + function(err, docs) {} + ); } function remove_name_from_db(guid, channel) { - // Use temporary, with caution. Can bottleneck in large quantity of users. - // - // Find a way of indexing users in lists in a clever way, to avoid the search here - db.collection("connected_users").find({"_id": "total_users"}, function(err, all_users) { - var hasOne = all_users[0].total_users.some(function(v){ return v.indexOf(guid)>=0 }); - if(!hasOne) { - db.collection("user_names").find({"guid": guid}, function(err, user){ - if(user.length == 1){ - db.collection("user_names").update({"_id": "all_names"}, {$pull: {names: user[0].name}}, function(err, updated) { - db.collection("user_names").remove({"guid": guid}, function(err, removed) { }); - }); - } - }); - } else { - if(channel == undefined || channel == "") return; - db.collection("user_names").update({"guid": guid}, {$pull: {channels: channel}}, function(err, docs) { - //console.log("Pulled user from current channel"); - }); - } + // Use temporary, with caution. Can bottleneck in large quantity of users. + // + // Find a way of indexing users in lists in a clever way, to avoid the search here + db.collection("connected_users").find({ _id: "total_users" }, function( + err, + all_users + ) { + var hasOne = all_users[0].total_users.some(function(v) { + return v.indexOf(guid) >= 0; }); + if (!hasOne) { + db.collection("user_names").find({ guid: guid }, function(err, user) { + if (user.length == 1) { + db.collection("user_names").update( + { _id: "all_names" }, + { $pull: { names: user[0].name } }, + function(err, updated) { + db.collection("user_names").remove({ guid: guid }, function( + err, + removed + ) {}); + } + ); + } + }); + } else { + if (channel == undefined || channel == "") return; + db.collection("user_names").update( + { guid: guid }, + { $pull: { channels: channel } }, + function(err, docs) { + //console.log("Pulled user from current channel"); + } + ); + } + }); } function isUrl(str) { - var pattern = new RegExp("\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" + - "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov" + - "|mil|biz|info|mobi|name|aero|jobs|museum" + - "|travel|[a-z]{2}))(:[\\d]{1,5})?" + - "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" + - "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + - "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" + - "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + - "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + - "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b"); - if(!pattern.test(str)) { - return false; - } else { - return true; - } + var pattern = new RegExp( + "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" + + "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov" + + "|mil|biz|info|mobi|name|aero|jobs|museum" + + "|travel|[a-z]{2}))(:[\\d]{1,5})?" + + "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" + + "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" + + "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + + "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b" + ); + if (!pattern.test(str)) { + return false; + } else { + return true; + } } function getSession(socket) { - try { - /*var cookieParser = require("cookie-parser"); + try { + /*var cookieParser = require("cookie-parser"); var cookie = require("cookie"); var parsedCookies = cookie.parse(socket.handshake.headers.cookie); return parsedCookies["_uI"];*/ - if(socket.cookie_id == undefined) throw "Undefined error"; - return socket.cookie_id; - } catch(e) { - // Returning "sessiong"-based on place of connection - return hash_pass(socket.handshake.headers["user-agent"] + socket.handshake.address + socket.handshake.headers["accept-language"]); - //return "empty"; - } + if (socket.cookie_id == undefined) throw "Undefined error"; + return socket.cookie_id; + } catch (e) { + // Returning "sessiong"-based on place of connection + return hash_pass( + socket.handshake.headers["user-agent"] + + socket.handshake.address + + socket.handshake.headers["accept-language"] + ); + //return "empty"; + } } -function remove_from_array(array, element){ - if(contains(array, element)){ - var index = array.indexOf(element); - if(index != -1) - array.splice(index, 1); - } +function remove_from_array(array, element) { + if (contains(array, element)) { + var index = array.indexOf(element); + if (index != -1) array.splice(index, 1); + } } function generate_channel_name(res) { - var trying_id = uniqid.time().toLowerCase(); - db.collection("frontpage_lists").find({frontpage: {$exists: true }, "_id": trying_id }, {"_id": 1}, function(err, docs){ - if(docs.length == 0) { - res.send(trying_id); - return; - } - generate_channel_name(res); - }); + var trying_id = uniqid.time().toLowerCase(); + db.collection("frontpage_lists").find( + { frontpage: { $exists: true }, _id: trying_id }, + { _id: 1 }, + function(err, docs) { + if (docs.length == 0) { + res.send(trying_id); + return; + } + generate_channel_name(res); + } + ); } function get_short_id(socket) { - var new_short_id = uniqid.time().toLowerCase(); + var new_short_id = uniqid.time().toLowerCase(); - socket.join(new_short_id); - socket.emit("id", new_short_id); + socket.join(new_short_id); + socket.emit("id", new_short_id); } -function check_inlist(coll, guid, socket, offline, callback, double_check) -{ - if(coll == undefined) { - if(typeof(callback) == "function") callback(); - return; - } - //coll = coll.replace(/ /g,''); - if(!offline && coll != undefined){ - db.collection("connected_users").update({"_id": coll}, {$addToSet:{users: guid}}, {upsert: true}, function(err, updated) { - if(updated.nModified > 0 || updated.upserted != undefined) { - db.collection("connected_users").find({"_id": coll}, function(err, new_doc) { - db.collection("frontpage_lists").update({"_id": coll}, {$set: {"viewers": new_doc[0].users.length}}, function(){ - if(new_doc[0].users == undefined || new_doc[0].users.length == undefined) { - io.to(coll).emit("viewers", 1); - } else { - io.to(coll).emit("viewers", new_doc[0].users.length); +function check_inlist(coll, guid, socket, offline, callback, double_check) { + if (coll == undefined) { + if (typeof callback == "function") callback(); + return; + } + //coll = coll.replace(/ /g,''); + if (!offline && coll != undefined) { + db.collection("connected_users").update( + { _id: coll }, + { $addToSet: { users: guid } }, + { upsert: true }, + function(err, updated) { + if (updated.nModified > 0 || updated.upserted != undefined) { + db.collection("connected_users").find({ _id: coll }, function( + err, + new_doc + ) { + db.collection("frontpage_lists").update( + { _id: coll }, + { $set: { viewers: new_doc[0].users.length } }, + function() { + if ( + new_doc[0].users == undefined || + new_doc[0].users.length == undefined + ) { + io.to(coll).emit("viewers", 1); + } else { + io.to(coll).emit("viewers", new_doc[0].users.length); + } + Chat.namechange( + { initial: true, first: true, channel: coll }, + guid, + socket, + false, + function(enabled) { + db.collection("user_names").find({ guid: guid }, function( + err, + docs + ) { + if (docs.length == 1) { + var icon = ""; + if (docs[0].icon != undefined) icon = docs[0].icon; + db.collection("user_names").update( + { guid: guid }, + { $addToSet: { channels: coll } }, + function(err, doc) {} + ); + if (enabled) { + socket.broadcast.to(coll).emit("chat", { + from: docs[0].name, + icon: icon, + msg: " joined" + }); } - Chat.namechange({initial: true, first:true, channel: coll}, guid, socket, false, function(enabled) { - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 1) { - var icon = ""; - if(docs[0].icon != undefined) icon = docs[0].icon; - db.collection("user_names").update({"guid": guid}, {$addToSet:{channels: coll}}, function(err, doc){}); - if(enabled) { - socket.broadcast.to(coll).emit('chat', {from: docs[0].name, icon: icon, msg: " joined"}); - } - } else if(docs.length == 0) { - //console.log("User doesn't have a name for some reason."); - //console.log("guid", guid); - //console.log("channel", coll); - //console.log("Trying to get a chat-name"); - Chat.get_name(guid, {announce: false, socket: socket, channel: coll}); - } - }); - db.collection("connected_users").update({"_id": "total_users"}, {$addToSet: {total_users: guid + coll}}, function(err, docs){ - if(callback != undefined && typeof(callback) == "function") callback(); - }); + } else if (docs.length == 0) { + //console.log("User doesn't have a name for some reason."); + //console.log("guid", guid); + //console.log("channel", coll); + //console.log("Trying to get a chat-name"); + Chat.get_name(guid, { + announce: false, + socket: socket, + channel: coll }); + } }); - }); - } else { - db.collection("connected_users").find({"_id": coll}, function(err, new_doc) { - io.to(coll).emit("viewers", new_doc[0].users.length); - }); - if(callback != undefined && typeof(callback) == "function") callback(); - } - }); - - } else { - if(offline) { - db.collection("connected_users").update({"_id": "offline_users"}, {$addToSet: {users: guid}}, function(err, docs){}); + db.collection("connected_users").update( + { _id: "total_users" }, + { $addToSet: { total_users: guid + coll } }, + function(err, docs) { + if ( + callback != undefined && + typeof callback == "function" + ) + callback(); + } + ); + } + ); + } + ); + }); } else { - db.collection("connected_users").update({"_id": coll}, {$addToSet: {users: guid}}, function(err, docs){}); + db.collection("connected_users").find({ _id: coll }, function( + err, + new_doc + ) { + io.to(coll).emit("viewers", new_doc[0].users.length); + }); + if (callback != undefined && typeof callback == "function") + callback(); } - // - if(coll != undefined && coll != "") { - db.collection("connected_users").update({"_id": "total_users"}, {$addToSet: {total_users: guid + coll}}, function(err, docs) {}); - } - if(callback != undefined && typeof(callback) == "function") callback(); + } + ); + } else { + if (offline) { + db.collection("connected_users").update( + { _id: "offline_users" }, + { $addToSet: { users: guid } }, + function(err, docs) {} + ); + } else { + db.collection("connected_users").update( + { _id: coll }, + { $addToSet: { users: guid } }, + function(err, docs) {} + ); } + // + if (coll != undefined && coll != "") { + db.collection("connected_users").update( + { _id: "total_users" }, + { $addToSet: { total_users: guid + coll } }, + function(err, docs) {} + ); + } + if (callback != undefined && typeof callback == "function") callback(); + } } function rndName(seed, len) { - var vowels = ['a', 'e', 'i', 'o', 'u']; - consts = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y']; - len = Math.floor(len); - word = ''; - is_vowel = false; - var arr; - try { - for (var i = 0; i < len; i++) { - if (is_vowel) arr = vowels; - else arr = consts; - is_vowel = !is_vowel; - word += arr[(seed[i%seed.length].charCodeAt()+i) % (arr.length-1)]; - } - } catch(e) { - return rndName(uniqid.time().toLowerCase(), len); + var vowels = ["a", "e", "i", "o", "u"]; + consts = [ + "b", + "c", + "d", + "f", + "g", + "h", + "j", + "k", + "l", + "m", + "n", + "p", + "r", + "s", + "t", + "v", + "w", + "x", + "y" + ]; + len = Math.floor(len); + word = ""; + is_vowel = false; + var arr; + try { + for (var i = 0; i < len; i++) { + if (is_vowel) arr = vowels; + else arr = consts; + is_vowel = !is_vowel; + word += arr[(seed[i % seed.length].charCodeAt() + i) % (arr.length - 1)]; } - return word; + } catch (e) { + return rndName(uniqid.time().toLowerCase(), len); + } + return word; } -function removeEmojis (string) { - //https://stackoverflow.com/a/41164278/4266467 - var regex = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/g; - return string.replace(regex, ''); +function removeEmojis(string) { + //https://stackoverflow.com/a/41164278/4266467 + var regex = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/g; + return string.replace(regex, ""); } -function decrypt_string(pw){ - try { - return Buffer.from(pw, 'base64').toString('ascii') - } catch(e) { - return ""; - } +function decrypt_string(pw) { + try { + return Buffer.from(pw, "base64").toString("ascii"); + } catch (e) { + return ""; + } } -function get_time() -{ - var d = new Date(); - var time = Math.floor(d.getTime() / 1000); - return time; +function get_time() { + var d = new Date(); + var time = Math.floor(d.getTime() / 1000); + return time; } function contains(a, obj) { - try{ - var i = a.length; - while (i--) { - if (a[i] === obj) { - return true; - } - } - return false; - }catch(e){ - return false; + try { + var i = a.length; + while (i--) { + if (a[i] === obj) { + return true; + } } + return false; + } catch (e) { + return false; + } } function hash_pass(adminpass, hex) { - if(adminpass == undefined || adminpass == "") return ""; - if(hex) return crypto.createHash('sha256').update(adminpass).digest('hex'); - return crypto.createHash('sha256').update(adminpass).digest('base64'); + if (adminpass == undefined || adminpass == "") return ""; + if (hex) + return crypto + .createHash("sha256") + .update(adminpass) + .digest("hex"); + return crypto + .createHash("sha256") + .update(adminpass) + .digest("base64"); } function setSessionAdminPass(id, adminpass, list, callback) { - try { - if(id == "empty" || id == undefined) { - callback(); - return; - } - - connected_db.collection(id).update({_id: list}, {$set: {adminpass: hash_pass(decrypt_string(adminpass), true)}}, {upsert: true}, function(e, d){ - callback(); - return; - }); - } catch(e) { - + try { + if (id == "empty" || id == undefined) { + callback(); + return; } + + connected_db + .collection(id) + .update( + { _id: list }, + { $set: { adminpass: hash_pass(decrypt_string(adminpass), true) } }, + { upsert: true }, + function(e, d) { + callback(); + return; + } + ); + } catch (e) {} } function setSessionChatPass(id, name, pass, callback) { - try { - if(id == "empty" || id == undefined) { - callback(); - return; - } - connected_db.collection(id).update({_id: "_chat_"}, {$set: {password: pass, name: name}}, {upsert: true}, function(e) { - callback(); - return; - }) - } catch(e) { - callback(); - return; + try { + if (id == "empty" || id == undefined) { + callback(); + return; } + connected_db + .collection(id) + .update( + { _id: "_chat_" }, + { $set: { password: pass, name: name } }, + { upsert: true }, + function(e) { + callback(); + return; + } + ); + } catch (e) { + callback(); + return; + } } function getSessionChatPass(id, callback) { - try { - if(id == "empty" || id == undefined) { - callback("", "", false); - return; - } - - connected_db.collection(id).find({_id: "_chat_"}, function(e, d) { - if(d.length > 0) { - var name = ""; - var pass = ""; - if(d[0].name != undefined) name = d[0].name; - if(d[0].password != undefined) pass = d[0].password; - callback(name, pass); - return; - } else { - callback("", "", false); - return; - } - }) - } catch(e) { - callback(); - return; + try { + if (id == "empty" || id == undefined) { + callback("", "", false); + return; } + + connected_db.collection(id).find({ _id: "_chat_" }, function(e, d) { + if (d.length > 0) { + var name = ""; + var pass = ""; + if (d[0].name != undefined) name = d[0].name; + if (d[0].password != undefined) pass = d[0].password; + callback(name, pass); + return; + } else { + callback("", "", false); + return; + } + }); + } catch (e) { + callback(); + return; + } } - function setChromecastHost(id, other_id, list, callback) { - try { - if(id == "empty" || id == undefined || other_id == "empty" || other_id == undefined) { - callback(); - return; - } - connected_db.collection(id).update({_id: list}, {"chromecast": true, id: other_id}, {upsert: true}, function(e, docs) { - callback(true); - return; - }); - } catch(e) { - callback(false); + try { + if ( + id == "empty" || + id == undefined || + other_id == "empty" || + other_id == undefined + ) { + callback(); + return; } + connected_db + .collection(id) + .update( + { _id: list }, + { chromecast: true, id: other_id }, + { upsert: true }, + function(e, docs) { + callback(true); + return; + } + ); + } catch (e) { + callback(false); + } } function setSessionUserPass(id, userpass, list, callback) { - try { - if(id == "empty" || id == undefined || userpass == undefined) { - callback(); - return; - } - - connected_db.collection(id).update({_id: list}, {$set: {userpass: userpass}}, {upsert: true}, function(e, d){ - callback(); - return; - }); - } catch(e) { - callback(); + try { + if (id == "empty" || id == undefined || userpass == undefined) { + callback(); + return; } + + connected_db + .collection(id) + .update( + { _id: list }, + { $set: { userpass: userpass } }, + { upsert: true }, + function(e, d) { + callback(); + return; + } + ); + } catch (e) { + callback(); + } } function getSessionAdminUser(id, list, callback) { - try { - if(id == "empty" || id == undefined) { - callback("", "", false); - return; - } - connected_db.collection(id).find({_id: list}, function(e, d) { - var userpass = ""; - var adminpass = ""; - if(d.length > 0) { - if(d[0].hasOwnProperty("chromecast") && d[0].chromecast) { - getSessionAdminUser(d[0].id, list, callback); - } else { - if(d[0].userpass != undefined) userpass = d[0].userpass; - if(d[0].adminpass != undefined) adminpass = d[0].adminpass; - callback(userpass, adminpass, true); - } - } else { - callback(userpass, adminpass, true); - } - }) - } catch(e) { - callback("", "", false); + try { + if (id == "empty" || id == undefined) { + callback("", "", false); + return; } + connected_db.collection(id).find({ _id: list }, function(e, d) { + var userpass = ""; + var adminpass = ""; + if (d.length > 0) { + if (d[0].hasOwnProperty("chromecast") && d[0].chromecast) { + getSessionAdminUser(d[0].id, list, callback); + } else { + if (d[0].userpass != undefined) userpass = d[0].userpass; + if (d[0].adminpass != undefined) adminpass = d[0].adminpass; + callback(userpass, adminpass, true); + } + } else { + callback(userpass, adminpass, true); + } + }); + } catch (e) { + callback("", "", false); + } } function removeSessionChatPass(id, callback) { - if(id == "empty" || id == undefined) { - callback(); - return; - } - connected_db.collection(id).remove({_id: "_chat_"}, function() { - callback(); - return; - }); + if (id == "empty" || id == undefined) { + callback(); + return; + } + connected_db.collection(id).remove({ _id: "_chat_" }, function() { + callback(); + return; + }); } - function removeSessionAdminPass(id, channel, callback) { - if(id == "empty" || id == undefined) { - callback(); - return; - } - connected_db.collection(id).update({_id: channel}, {$set: {"adminpass": ""}}, function() { - callback(); - return; + if (id == "empty" || id == undefined) { + callback(); + return; + } + connected_db + .collection(id) + .update({ _id: channel }, { $set: { adminpass: "" } }, function() { + callback(); + return; }); } function remove_from_chat_channel(coll, guid) { - db.collection("user_names").update({"guid": guid}, {$pull: {channels: coll}}, function(err, docs) { - }); + db.collection("user_names").update( + { guid: guid }, + { $pull: { channels: coll } }, + function(err, docs) {} + ); } function left_channel(coll, guid, short_id, in_list, socket, change, caller) { - if(!coll) { - if(!change) { - remove_name_from_db(guid, coll); - } else { - remove_from_chat_channel(coll, guid); - } - return; + if (!coll) { + if (!change) { + remove_name_from_db(guid, coll); + } else { + remove_from_chat_channel(coll, guid); } - //coll = coll.replace(/ /g,''); - db.collection("connected_users").update({"_id": coll}, {$pull: {users: guid}}, function(err, updated) { - if(updated.nModified > 0) { - db.collection("connected_users").update({"_id": "total_users"}, {$pull: {total_users: guid + coll}}, function(err, updated){}); - db.collection("connected_users").find({"_id": coll}, function(err, new_doc){ - db.collection("frontpage_lists").update({"_id": coll, viewers: {$gt: 0}}, {$inc: {viewers: -1}}, function(err, doc) { - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 1) { - var icon = ""; - if(docs[0].icon != undefined) icon = docs[0].icon; - io.to(coll).emit('chat', {from: docs[0].name, icon: icon, msg: " left"}); - } - }); - io.to(coll).emit("viewers", new_doc[0].users.length); - socket.leave(coll); - if(!change) { - remove_name_from_db(guid, coll); - } else { - remove_from_chat_channel(coll, guid); - } - }); - }); - - } else { - db.collection("connected_users").update({"_id": "offline_users"}, {$pull: {users: guid}}, function(err, updated){ - //if(updated.nModified > 0) { - db.collection("connected_users").update({"_id": "total_users"}, {$pull: {total_users: guid + coll}}, function(err, updated){}); - if(!change) { - remove_name_from_db(guid, coll); - } else { - remove_from_chat_channel(coll, guid); - } - //} - }); - - } - }); - remove_unique_id(short_id); + return; + } + //coll = coll.replace(/ /g,''); + db.collection("connected_users").update( + { _id: coll }, + { $pull: { users: guid } }, + function(err, updated) { + if (updated.nModified > 0) { + db.collection("connected_users").update( + { _id: "total_users" }, + { $pull: { total_users: guid + coll } }, + function(err, updated) {} + ); + db.collection("connected_users").find({ _id: coll }, function( + err, + new_doc + ) { + db.collection("frontpage_lists").update( + { _id: coll, viewers: { $gt: 0 } }, + { $inc: { viewers: -1 } }, + function(err, doc) { + db.collection("user_names").find({ guid: guid }, function( + err, + docs + ) { + if (docs.length == 1) { + var icon = ""; + if (docs[0].icon != undefined) icon = docs[0].icon; + io.to(coll).emit("chat", { + from: docs[0].name, + icon: icon, + msg: " left" + }); + } + }); + io.to(coll).emit("viewers", new_doc[0].users.length); + socket.leave(coll); + if (!change) { + remove_name_from_db(guid, coll); + } else { + remove_from_chat_channel(coll, guid); + } + } + ); + }); + } else { + db.collection("connected_users").update( + { _id: "offline_users" }, + { $pull: { users: guid } }, + function(err, updated) { + //if(updated.nModified > 0) { + db.collection("connected_users").update( + { _id: "total_users" }, + { $pull: { total_users: guid + coll } }, + function(err, updated) {} + ); + if (!change) { + remove_name_from_db(guid, coll); + } else { + remove_from_chat_channel(coll, guid); + } + //} + } + ); + } + } + ); + remove_unique_id(short_id); } +function checkTimeout( + type, + timeout, + channel, + guid, + conf_pass, + this_pass, + socket, + callback, + error_message, + error_callback +) { + if (conf_pass != "" && conf_pass == this_pass) { + callback(); + return; + } + db.collection("timeout_api").find( + { + type: type, + guid: guid + }, + function(err, docs) { + if (docs.length > 0) { + var date = new Date(docs[0].createdAt); + date.setSeconds(date.getSeconds() + timeout); + var now = new Date(); -function checkTimeout(type, timeout, channel, guid, conf_pass, this_pass, socket, callback, error_message, error_callback){ - if(conf_pass != "" && conf_pass == this_pass) { - callback(); - return; - } - db.collection("timeout_api").find({ - type: type, - guid: guid, - }, function(err, docs) { - if(docs.length > 0) { - var date = new Date(docs[0].createdAt); - date.setSeconds(date.getSeconds() + timeout); - var now = new Date(); - - var retry_in = (date.getTime() - now.getTime()) / 1000; - if(retry_in > 0) { - if(typeof(error_callback) == "function") { - error_callback(); - } else if(error_message) { - var sOrNot = Math.ceil(retry_in) > 1 || Math.ceil(retry_in) == 0 ? "s" : ""; - socket.emit("toast", error_message + Math.ceil(retry_in) + " second" + sOrNot + "."); - } else { - socket.emit("toast", "wait_longer"); - } - return; - } + var retry_in = (date.getTime() - now.getTime()) / 1000; + if (retry_in > 0) { + if (typeof error_callback == "function") { + error_callback(); + } else if (error_message) { + var sOrNot = + Math.ceil(retry_in) > 1 || Math.ceil(retry_in) == 0 ? "s" : ""; + socket.emit( + "toast", + error_message + Math.ceil(retry_in) + " second" + sOrNot + "." + ); + } else { + socket.emit("toast", "wait_longer"); + } + return; } - var now_date = new Date(); - db.collection("timeout_api").update({type: type, guid: guid}, { - $set: { - "createdAt": now_date, - type: type, - guid: guid, - }, - }, {upsert: true}, function(err, docs) { - callback(); - return; - }); - }); + } + var now_date = new Date(); + db.collection("timeout_api").update( + { type: type, guid: guid }, + { + $set: { + createdAt: now_date, + type: type, + guid: guid + } + }, + { upsert: true }, + function(err, docs) { + callback(); + return; + } + ); + } + ); } module.exports.checkTimeout = checkTimeout; diff --git a/server/handlers/list_change.js b/server/handlers/list_change.js index f6913bde..31a00817 100644 --- a/server/handlers/list_change.js +++ b/server/handlers/list_change.js @@ -1,814 +1,1396 @@ -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var List = require(pathThumbnails + '/handlers/list.js'); -var Frontpage = require(pathThumbnails + '/handlers/frontpage.js'); -var Search = require(pathThumbnails + '/handlers/search.js'); -var crypto = require('crypto'); -var Filter = require('bad-words'); -var filter = new Filter({ placeHolder: 'x'}); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var List = require(pathThumbnails + "/handlers/list.js"); +var Frontpage = require(pathThumbnails + "/handlers/frontpage.js"); +var Search = require(pathThumbnails + "/handlers/search.js"); +var crypto = require("crypto"); +var Filter = require("bad-words"); +var filter = new Filter({ placeHolder: "x" }); /*var filter = { clean: function(str) { return str; } }*/ -var db = require(pathThumbnails + '/handlers/db.js'); +var db = require(pathThumbnails + "/handlers/db.js"); function addFromOtherList(arr, guid, offline, socket) { - var socketid = socket.zoff_id; - if(typeof(arr) == "object") { - if(!arr.hasOwnProperty("channel") || !arr.hasOwnProperty("new_channel") - || typeof(arr.channel) != "string" || typeof(arr.new_channel) != "string") { - var result = { - channel: { - expected: "string", - got: arr.hasOwnProperty("channel") ? typeof(arr.channel) : undefined - }, - new_channel: { - expected: "string", - got: arr.hasOwnProperty("new_channel") ? typeof(arr.new_channel) : undefined - } - }; - socket.emit('update_required', result); - return; + var socketid = socket.zoff_id; + if (typeof arr == "object") { + if ( + !arr.hasOwnProperty("channel") || + !arr.hasOwnProperty("new_channel") || + typeof arr.channel != "string" || + typeof arr.new_channel != "string" + ) { + var result = { + channel: { + expected: "string", + got: arr.hasOwnProperty("channel") ? typeof arr.channel : undefined + }, + new_channel: { + expected: "string", + got: arr.hasOwnProperty("new_channel") + ? typeof arr.new_channel + : undefined } - var channel = arr.channel;//.replace(/ /g,'').toLowerCase(); - var new_channel = Functions.encodeChannelName(arr.new_channel);//.replace(/ /g, '').toLowerCase(); - db.collection("frontpage_lists").find({_id: new_channel}, function(err, fp) { - if(fp.length == 0 || channel == new_channel) { - socket.emit("toast", "nolist"); - return; - } - Functions.getSessionAdminUser(Functions.getSession(socket), channel, function(userpass, adminpass) { - if(userpass != "" || arr.userpass == undefined) { - arr.userpass = userpass; - } else { - arr.userpass = crypto.createHash('sha256').update(Functions.decrypt_string(arr.userpass)).digest('base64') - } - if(adminpass != "" || arr.adminpass == undefined) { - arr.adminpass = Functions.hash_pass(adminpass); - } else { - arr.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(arr.adminpass), true)); - } - Functions.getSessionAdminUser(Functions.getSession(socket), new_channel, function(userpass) { - var otheruser = ""; - if(userpass != "") { - otheruser = userpass; - } else { - otheruser = crypto.createHash('sha256').update(Functions.decrypt_string(otheruser)).digest("base64"); - } - - db.collection(channel).find({now_playing: true}, function(e, np) { - - var project_object = { - "id": 1, - "added": 1, - "guids": { "$literal": [] }, - "now_playing": 1, - "title": 1, - "votes": { "$literal": 0 }, - "start": 1, - "duration": 1, - "end": 1, - "type": 1, - "source": 1, - "thumbnail": 1, - "tags": 1 - }; - var to_set_np = true; - if(np.length > 0) { - project_object.now_playing = { "$literal": false }; - to_set_np = false; - } - db.collection(new_channel + "_settings").find({id: "config"}, function(e, this_conf) { - if(this_conf.length > 0 && (this_conf[0].userpass == "" || !this_conf[0].userpass || this_conf[0].userpass == otheruser)) { - db.collection(channel + "_settings").find({id: "config"}, function(e, this_conf) { - var hash = arr.adminpass; - if(this_conf.length == 0) { - socket.emit("toast", "nolist"); - return; - } - if((this_conf[0].userpass == "" || !this_conf[0].userpass || this_conf[0].userpass == arr.userpass)) { - var connection_id = Functions.hash_pass(socket.handshake.headers["user-agent"] + socket.handshake.address + socket.handshake.headers["accept-language"]); - Functions.checkTimeout("add_playlist", 60, channel, connection_id, this_conf[0].adminpass, hash, socket, function() { - if(((this_conf[0].addsongs === true && (hash == this_conf[0].adminpass || this_conf[0].adminpass === "")) || - this_conf[0].addsongs === false)) { - db.collection(new_channel).aggregate([ - { - "$match": { type: "video" } - }, - { - "$project": project_object - } - ], function(e, docs) { - var path = require('path'); - var mongo_config = require(path.join(path.join(__dirname, '../config/'), 'mongo_config.js')); - var MongoClient = require('mongodb').MongoClient; - var url = "mongodb://" + mongo_config.host + ":" + mongo_config.port + "/"; - MongoClient.connect(url, function(err, _db) { - var dbo = _db.db(mongo_config.config); - dbo.collection(channel).insertMany(docs, {ordered: false}, function(err, res) { - db.collection(channel).count({type: {$ne: "suggested"}}, function(err, count) { - db.collection(channel + "_settings").update({id: "config"}, {$set: {startTime: Functions.get_time()}}, function(e,d) { - if(to_set_np) { - var to_change = { - _id: channel, - count: count, - frontpage: true, - accessed: Functions.get_time(), - } - db.collection(channel).find({now_playing: true}, function(e, np_docs) { - to_change.id = np_docs[0].id; - to_change.title = np_docs[0].title; - db.collection("frontpage_lists").find({_id: new_channel}, function(e, doc) { - if(doc.length > 0 && ((doc[0].thumbnail != "" && doc[0].thumbnail != undefined && (doc[0].thumbnail.indexOf("https://i1.sndcdn.com") > -1 || doc[0].thumbnail.indexOf("https://w1.sndcdn.com") > -1)) || (doc[0].thumbnail == "" || doc[0].thumbnail == undefined))) { - to_change.thumbnail = np_docs[0].thumbnail; - } - - db.collection("frontpage_lists").update({_id: channel}, {$set: to_change}, function(e, d) { - List.send_list(channel, undefined, false, true, false); - List.send_play(channel, undefined); - socket.emit("toast", "addedplaylist"); - _db.close(); - }); - }); - }); - } else { - db.collection("frontpage_lists").update({_id: channel}, {$set: {count: count}}, function(e, d) { - List.send_list(channel, undefined, false, true, false); - List.send_play(channel, undefined); - socket.emit("toast", "addedplaylist"); - _db.close(); - }) - } - }); - }); - }); - }); - }); - } else { - socket.emit("toast", "listhaspass"); - return; - } - }, "Log in to do that, or please wait "); - } else { - socket.emit("auth_required"); - return; - } - }); - } else { - socket.emit("toast", "other_list_pass"); - return; - } - }) - }); - }); - }); - }); + }; + socket.emit("update_required", result); + return; } + var channel = arr.channel; //.replace(/ /g,'').toLowerCase(); + var new_channel = Functions.encodeChannelName(arr.new_channel); //.replace(/ /g, '').toLowerCase(); + db.collection("frontpage_lists").find({ _id: new_channel }, function( + err, + fp + ) { + if (fp.length == 0 || channel == new_channel) { + socket.emit("toast", "nolist"); + return; + } + Functions.getSessionAdminUser( + Functions.getSession(socket), + channel, + function(userpass, adminpass) { + if (userpass != "" || arr.userpass == undefined) { + arr.userpass = userpass; + } else { + arr.userpass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(arr.userpass)) + .digest("base64"); + } + if (adminpass != "" || arr.adminpass == undefined) { + arr.adminpass = Functions.hash_pass(adminpass); + } else { + arr.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(arr.adminpass), true) + ); + } + Functions.getSessionAdminUser( + Functions.getSession(socket), + new_channel, + function(userpass) { + var otheruser = ""; + if (userpass != "") { + otheruser = userpass; + } else { + otheruser = crypto + .createHash("sha256") + .update(Functions.decrypt_string(otheruser)) + .digest("base64"); + } + + db.collection(channel).find({ now_playing: true }, function( + e, + np + ) { + var project_object = { + id: 1, + added: 1, + guids: { $literal: [] }, + now_playing: 1, + title: 1, + votes: { $literal: 0 }, + start: 1, + duration: 1, + end: 1, + type: 1, + source: 1, + thumbnail: 1, + tags: 1 + }; + var to_set_np = true; + if (np.length > 0) { + project_object.now_playing = { $literal: false }; + to_set_np = false; + } + db.collection(new_channel + "_settings").find( + { id: "config" }, + function(e, this_conf) { + if ( + this_conf.length > 0 && + (this_conf[0].userpass == "" || + !this_conf[0].userpass || + this_conf[0].userpass == otheruser) + ) { + db.collection(channel + "_settings").find( + { id: "config" }, + function(e, this_conf) { + var hash = arr.adminpass; + if (this_conf.length == 0) { + socket.emit("toast", "nolist"); + return; + } + if ( + this_conf[0].userpass == "" || + !this_conf[0].userpass || + this_conf[0].userpass == arr.userpass + ) { + var connection_id = Functions.hash_pass( + socket.handshake.headers["user-agent"] + + socket.handshake.address + + socket.handshake.headers["accept-language"] + ); + Functions.checkTimeout( + "add_playlist", + 60, + channel, + connection_id, + this_conf[0].adminpass, + hash, + socket, + function() { + if ( + (this_conf[0].addsongs === true && + (hash == this_conf[0].adminpass || + this_conf[0].adminpass === "")) || + this_conf[0].addsongs === false + ) { + db.collection(new_channel).aggregate( + [ + { + $match: { type: "video" } + }, + { + $project: project_object + } + ], + function(e, docs) { + var path = require("path"); + var mongo_config = require(path.join( + path.join(__dirname, "../config/"), + "mongo_config.js" + )); + var MongoClient = require("mongodb") + .MongoClient; + var url = + "mongodb://" + + mongo_config.host + + ":" + + mongo_config.port + + "/"; + MongoClient.connect( + url, + function(err, _db) { + var dbo = _db.db(mongo_config.config); + dbo + .collection(channel) + .insertMany( + docs, + { ordered: false }, + function(err, res) { + db.collection(channel).count( + { + type: { $ne: "suggested" } + }, + function(err, count) { + db.collection( + channel + "_settings" + ).update( + { id: "config" }, + { + $set: { + startTime: Functions.get_time() + } + }, + function(e, d) { + if (to_set_np) { + var to_change = { + _id: channel, + count: count, + frontpage: true, + accessed: Functions.get_time() + }; + db.collection( + channel + ).find( + { + now_playing: true + }, + function( + e, + np_docs + ) { + to_change.id = + np_docs[0].id; + to_change.title = + np_docs[0].title; + db.collection( + "frontpage_lists" + ).find( + { + _id: new_channel + }, + function( + e, + doc + ) { + if ( + doc.length > + 0 && + ((doc[0] + .thumbnail != + "" && + doc[0] + .thumbnail != + undefined && + (doc[0].thumbnail.indexOf( + "https://i1.sndcdn.com" + ) > -1 || + doc[0].thumbnail.indexOf( + "https://w1.sndcdn.com" + ) > + -1)) || + (doc[0] + .thumbnail == + "" || + doc[0] + .thumbnail == + undefined)) + ) { + to_change.thumbnail = + np_docs[0].thumbnail; + } + + db.collection( + "frontpage_lists" + ).update( + { + _id: channel + }, + { + $set: to_change + }, + function( + e, + d + ) { + List.send_list( + channel, + undefined, + false, + true, + false + ); + List.send_play( + channel, + undefined + ); + socket.emit( + "toast", + "addedplaylist" + ); + _db.close(); + } + ); + } + ); + } + ); + } else { + db.collection( + "frontpage_lists" + ).update( + { _id: channel }, + { + $set: { + count: count + } + }, + function(e, d) { + List.send_list( + channel, + undefined, + false, + true, + false + ); + List.send_play( + channel, + undefined + ); + socket.emit( + "toast", + "addedplaylist" + ); + _db.close(); + } + ); + } + } + ); + } + ); + } + ); + } + ); + } + ); + } else { + socket.emit("toast", "listhaspass"); + return; + } + }, + "Log in to do that, or please wait " + ); + } else { + socket.emit("auth_required"); + return; + } + } + ); + } else { + socket.emit("toast", "other_list_pass"); + return; + } + } + ); + }); + } + ); + } + ); + }); + } } function addPlaylist(arr, guid, offline, socket) { - var socketid = socket.zoff_id; - if(typeof(arr) == "object") { - if(!arr.hasOwnProperty("channel") || !arr.hasOwnProperty("songs") - || typeof(arr.channel) != "string" || typeof(arr.songs) != "object") { - var result = { - channel: { - expected: "string", - got: arr.hasOwnProperty("channel") ? typeof(arr.channel) : undefined - }, - songs: { - expected: "object", - got: arr.hasOwnProperty("songs") ? typeof(arr.songs) : undefined - } - }; - socket.emit('update_required', result); - return; + var socketid = socket.zoff_id; + if (typeof arr == "object") { + if ( + !arr.hasOwnProperty("channel") || + !arr.hasOwnProperty("songs") || + typeof arr.channel != "string" || + typeof arr.songs != "object" + ) { + var result = { + channel: { + expected: "string", + got: arr.hasOwnProperty("channel") ? typeof arr.channel : undefined + }, + songs: { + expected: "object", + got: arr.hasOwnProperty("songs") ? typeof arr.songs : undefined } - var channel = arr.channel;//.replace(/ /g,'').toLowerCase(); - if(arr.length == 0 || arr.songs.length == 0) { - socket.emit("toast", "Empty list.."); - return; - } - db.collection("frontpage_lists").find({_id: channel}, function(err, fp) { - if(fp.length == 0) { - socket.emit("toast", "nolist"); - return; - } - - Functions.getSessionAdminUser(Functions.getSession(socket), channel, function(userpass, adminpass) { - if(userpass != "" || arr.userpass == undefined) { - arr.userpass = userpass; - } else { - arr.userpass = crypto.createHash('sha256').update(Functions.decrypt_string(arr.userpass)).digest("base64"); - } - if(adminpass != "" || arr.adminpass == undefined) { - arr.adminpass = Functions.hash_pass(adminpass); - } else { - arr.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(arr.adminpass), true)) - } - db.collection(channel).find({now_playing: true}, function(e, np) { - var now_playing = false; - if(np.length == 0) now_playing = true; - db.collection(channel + "_settings").find({id: "config"}, function(e, conf) { - if(arr.length == 0 || arr.songs.length == 0) { - socket.emit("toast", "Empty list.."); - return; - } - if(conf.length > 0) { - var hash = arr.adminpass; - if((conf[0].userpass == "" || !conf[0].userpass || conf[0].userpass == arr.userpass)) { - if(((conf[0].addsongs === true && (hash == conf[0].adminpass || conf[0].adminpass === "")) || - conf[0].addsongs === false)) { - var connection_id = Functions.hash_pass(socket.handshake.headers["user-agent"] + socket.handshake.address + socket.handshake.headers["accept-language"]); - Functions.checkTimeout("add_playlist", 60, channel, connection_id, conf[0].adminpass, hash, socket, function() { - var path = require('path'); - var mongo_config = require(path.join(path.join(__dirname, '../config/'), 'mongo_config.js')); - var MongoClient = require('mongodb').MongoClient; - var url = "mongodb://" + mongo_config.host + ":" + mongo_config.port + "/"; - MongoClient.connect(url, function(err, _db) { - var dbo = _db.db(mongo_config.config); - var number_elements = arr.songs.length + 1; - var time = Functions.get_time() - number_elements; - var to_set_np = now_playing; - var bulk = dbo.collection(channel).initializeUnorderedBulkOp({useLegacyOps: true}); - for(var i = 0; i < arr.songs.length; i++) { - var this_element = arr.songs[i]; - if(!this_element.hasOwnProperty("duration") || !this_element.hasOwnProperty("id") || !this_element.hasOwnProperty("title")) { - continue; - } - this_element.id = this_element.id + ""; - this_element.added = time; - this_element.now_playing = now_playing; - this_element.votes = 0; - this_element.guids = []; - if(!this_element.hasOwnProperty("start")) this_element.start = 0; - if(!this_element.hasOwnProperty("end")) this_element.end = this_element.duration; - this_element.start = parseInt(this_element.start); - this_element.end = parseInt(this_element.end); - this_element.type = "video"; - if(this_element.tags == undefined) this_element.tags = []; - this_element.duration = parseInt(this_element.duration); - if(this_element.start > this_element.end) { - this_element.start = 0; - } - if(this_element.source == "soundcloud") { - if(this_element.thumbnail.indexOf("https://i1.sndcdn.com") > -1 || this_element.thumbnail.indexOf("https://w1.sndcdn.com") > -1) { - this_element.thumbnail = this_element.thumbnail; - } else { - this_element.thumbnail = "https://img.youtube.com/vi/404_notfound/mqdefault.jpg"; - } - } else if(this_element.source == "youtube") this_element.thumbnail = "https://img.youtube.com/vi/" + this_element.id + "/mqdefault.jpg"; - if(now_playing) { - now_playing = false; - } - bulk.insert(this_element); - } - bulk.execute(function(err, results) { - db.collection(channel).count({type: {$ne: "suggested"}}, function(err, count) { - db.collection(channel + "_settings").update({id: "config"}, {$set: {startTime: Functions.get_time()}}, function(e,d) { - if(to_set_np) { - var to_change = { - _id: channel, - count: count, - frontpage: true, - accessed: Functions.get_time(), - } - db.collection(channel).find({now_playing: true}, function(e, np_docs) { - to_change.id = np_docs[0].id; - to_change.title = np_docs[0].title; - db.collection("frontpage_lists").find({_id: channel}, function(e, doc) { - if(doc.length > 0 && ((doc[0].thumbnail != "" && doc[0].thumbnail != undefined && (doc[0].thumbnail.indexOf("https://i1.sndcdn.com") > -1 || doc[0].thumbnail.indexOf("https://w1.sndcdn.com") > -1)) || (doc[0].thumbnail == "" || doc[0].thumbnail == undefined))) { - to_change.thumbnail = np_docs[0].thumbnail; - } - - db.collection("frontpage_lists").update({_id: channel}, {$set: to_change}, function(e, d) { - List.send_list(channel, undefined, false, true, false); - List.send_play(channel, undefined); - socket.emit("toast", "addedplaylist"); - _db.close(); - }); - }); - }); - } else { - db.collection("frontpage_lists").update({_id: channel}, {$set: {count: count}}, function(e, d) { - List.send_list(channel, undefined, false, true, false); - List.send_play(channel, undefined); - socket.emit("toast", "addedplaylist"); - _db.close(); - }) - } - Search.get_genres_list_recursive(arr.songs, channel); - }); - }); - }); - }); - }, "Log in to do that, or please wait "); - } else { - socket.emit("toast", "listhaspass"); - return; - } - } else { - socket.emit("auth_required"); - return; - } - } else { - socket.emit("toast", "nolist"); - return; - } - }) - }); - }); - }); + }; + socket.emit("update_required", result); + return; } + var channel = arr.channel; //.replace(/ /g,'').toLowerCase(); + if (arr.length == 0 || arr.songs.length == 0) { + socket.emit("toast", "Empty list.."); + return; + } + db.collection("frontpage_lists").find({ _id: channel }, function(err, fp) { + if (fp.length == 0) { + socket.emit("toast", "nolist"); + return; + } + + Functions.getSessionAdminUser( + Functions.getSession(socket), + channel, + function(userpass, adminpass) { + if (userpass != "" || arr.userpass == undefined) { + arr.userpass = userpass; + } else { + arr.userpass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(arr.userpass)) + .digest("base64"); + } + if (adminpass != "" || arr.adminpass == undefined) { + arr.adminpass = Functions.hash_pass(adminpass); + } else { + arr.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(arr.adminpass), true) + ); + } + db.collection(channel).find({ now_playing: true }, function(e, np) { + var now_playing = false; + if (np.length == 0) now_playing = true; + db.collection(channel + "_settings").find( + { id: "config" }, + function(e, conf) { + if (arr.length == 0 || arr.songs.length == 0) { + socket.emit("toast", "Empty list.."); + return; + } + if (conf.length > 0) { + var hash = arr.adminpass; + if ( + conf[0].userpass == "" || + !conf[0].userpass || + conf[0].userpass == arr.userpass + ) { + if ( + (conf[0].addsongs === true && + (hash == conf[0].adminpass || + conf[0].adminpass === "")) || + conf[0].addsongs === false + ) { + var connection_id = Functions.hash_pass( + socket.handshake.headers["user-agent"] + + socket.handshake.address + + socket.handshake.headers["accept-language"] + ); + Functions.checkTimeout( + "add_playlist", + 60, + channel, + connection_id, + conf[0].adminpass, + hash, + socket, + function() { + var path = require("path"); + var mongo_config = require(path.join( + path.join(__dirname, "../config/"), + "mongo_config.js" + )); + var MongoClient = require("mongodb").MongoClient; + var url = + "mongodb://" + + mongo_config.host + + ":" + + mongo_config.port + + "/"; + MongoClient.connect( + url, + function(err, _db) { + var dbo = _db.db(mongo_config.config); + var number_elements = arr.songs.length + 1; + var time = Functions.get_time() - number_elements; + var to_set_np = now_playing; + var bulk = dbo + .collection(channel) + .initializeUnorderedBulkOp({ + useLegacyOps: true + }); + for (var i = 0; i < arr.songs.length; i++) { + var this_element = arr.songs[i]; + if ( + !this_element.hasOwnProperty("duration") || + !this_element.hasOwnProperty("id") || + !this_element.hasOwnProperty("title") + ) { + continue; + } + this_element.id = this_element.id + ""; + this_element.added = time; + this_element.now_playing = now_playing; + this_element.votes = 0; + this_element.guids = []; + if (!this_element.hasOwnProperty("start")) + this_element.start = 0; + if (!this_element.hasOwnProperty("end")) + this_element.end = this_element.duration; + this_element.start = parseInt( + this_element.start + ); + this_element.end = parseInt(this_element.end); + this_element.type = "video"; + if (this_element.tags == undefined) + this_element.tags = []; + this_element.duration = parseInt( + this_element.duration + ); + if (this_element.start > this_element.end) { + this_element.start = 0; + } + if (this_element.source == "soundcloud") { + if ( + this_element.thumbnail.indexOf( + "https://i1.sndcdn.com" + ) > -1 || + this_element.thumbnail.indexOf( + "https://w1.sndcdn.com" + ) > -1 + ) { + this_element.thumbnail = + this_element.thumbnail; + } else { + this_element.thumbnail = + "https://img.youtube.com/vi/404_notfound/mqdefault.jpg"; + } + } else if (this_element.source == "youtube") + this_element.thumbnail = + "https://img.youtube.com/vi/" + + this_element.id + + "/mqdefault.jpg"; + if (now_playing) { + now_playing = false; + } + bulk.insert(this_element); + } + bulk.execute(function(err, results) { + db.collection(channel).count( + { type: { $ne: "suggested" } }, + function(err, count) { + db.collection(channel + "_settings").update( + { id: "config" }, + { + $set: { + startTime: Functions.get_time() + } + }, + function(e, d) { + if (to_set_np) { + var to_change = { + _id: channel, + count: count, + frontpage: true, + accessed: Functions.get_time() + }; + db.collection(channel).find( + { now_playing: true }, + function(e, np_docs) { + to_change.id = np_docs[0].id; + to_change.title = + np_docs[0].title; + db.collection( + "frontpage_lists" + ).find({ _id: channel }, function( + e, + doc + ) { + if ( + doc.length > 0 && + ((doc[0].thumbnail != "" && + doc[0].thumbnail != + undefined && + (doc[0].thumbnail.indexOf( + "https://i1.sndcdn.com" + ) > -1 || + doc[0].thumbnail.indexOf( + "https://w1.sndcdn.com" + ) > -1)) || + (doc[0].thumbnail == "" || + doc[0].thumbnail == + undefined)) + ) { + to_change.thumbnail = + np_docs[0].thumbnail; + } + + db.collection( + "frontpage_lists" + ).update( + { _id: channel }, + { $set: to_change }, + function(e, d) { + List.send_list( + channel, + undefined, + false, + true, + false + ); + List.send_play( + channel, + undefined + ); + socket.emit( + "toast", + "addedplaylist" + ); + _db.close(); + } + ); + }); + } + ); + } else { + db.collection( + "frontpage_lists" + ).update( + { _id: channel }, + { $set: { count: count } }, + function(e, d) { + List.send_list( + channel, + undefined, + false, + true, + false + ); + List.send_play( + channel, + undefined + ); + socket.emit( + "toast", + "addedplaylist" + ); + _db.close(); + } + ); + } + Search.get_genres_list_recursive( + arr.songs, + channel + ); + } + ); + } + ); + }); + } + ); + }, + "Log in to do that, or please wait " + ); + } else { + socket.emit("toast", "listhaspass"); + return; + } + } else { + socket.emit("auth_required"); + return; + } + } else { + socket.emit("toast", "nolist"); + return; + } + } + ); + }); + } + ); + }); + } } function add_function(arr, coll, guid, offline, socket) { - var socketid = socket.zoff_id; - if(typeof(arr) === 'object' && arr !== undefined && arr !== null && arr !== "" && !isNaN(parseInt(arr.duration))) - { - if(coll == "" || coll == undefined || coll == null || !arr.hasOwnProperty("duration")) { - var result = { - start: { - expected: "number or string that can be cast to int", - got: arr.hasOwnProperty("start") ? typeof(arr.start) : undefined - }, - end: { - expected: "number or string that can be cast to int", - got: arr.hasOwnProperty("end") ? typeof(arr.end) : undefined - } - }; - socket.emit('update_required', result); - return; + var socketid = socket.zoff_id; + if ( + typeof arr === "object" && + arr !== undefined && + arr !== null && + arr !== "" && + !isNaN(parseInt(arr.duration)) + ) { + if ( + coll == "" || + coll == undefined || + coll == null || + !arr.hasOwnProperty("duration") + ) { + var result = { + start: { + expected: "number or string that can be cast to int", + got: arr.hasOwnProperty("start") ? typeof arr.start : undefined + }, + end: { + expected: "number or string that can be cast to int", + got: arr.hasOwnProperty("end") ? typeof arr.end : undefined } - - try { - if(arr.start == undefined) arr.start = 0; - if(arr.end == undefined) arr.end = parseInt(arr.duration); - var start = parseInt(arr.start); - var end = parseInt(arr.end); - if(start < 0) { - socket.emit("toast", "faulty_start_end"); - return; - } - if(end < 0) { - socket.emit("toast", "faulty_start_end"); - return; - } - if(start >= end) { - start = 0; - arr.duration = end - start; - } - } catch(e) { - return; - } - - if(!arr.hasOwnProperty("source")) { - arr.source = "youtube"; - } - - if(typeof(arr.id) != "string" || typeof(arr.start) != "number" || - typeof(arr.end) != "number" || typeof(arr.title) != "string" || - typeof(arr.list) != "string" || typeof(arr.duration) != "number" || - (arr.source == "soundcloud" && (!arr.hasOwnProperty("thumbnail") || !Functions.isUrl(arr.thumbnail)))) { - var result = { - start: { - expected: "number or string that can be cast to int", - got: arr.hasOwnProperty("start") ? typeof(arr.start) : undefined - }, - end: { - expected: "number or string that can be cast to int", - got: arr.hasOwnProperty("end") ? typeof(arr.end) : undefined - }, - title: { - expected: "string", - got: arr.hasOwnProperty("title") ? typeof(arr.title) : undefined - }, - list: { - expected: "string", - got: arr.hasOwnProperty("list") ? typeof(arr.list) : undefined - }, - duration: { - expected: "number or string that can be cast to int", - got: arr.hasOwnProperty("duration") ? typeof(arr.duration) : undefined - }, - pass: { - expected: "string", - got: arr.hasOwnProperty("pass") ? typeof(arr.pass) : undefined - }, - adminpass: { - expected: "string", - got: arr.hasOwnProperty("adminpass") ? typeof(arr.adminpass) : undefined - }, - source: { - expected: "string (youtube or soundcloud)", - got: arr.hasOwnProperty("source") ? typeof(arr.source) : undefined - }, - thumbnail: { - expected: "url if source == soundcloud", - got: arr.hasOwnProperty("thumbnail") ? typeof(arr.thumbnail) : undefined - } - }; - socket.emit('update_required', result); - return; - } - if(arr.hasOwnProperty("offsiteAdd") && arr.offsiteAdd) { - coll = arr.list; - } - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { - if(adminpass != "" || arr.adminpass == undefined) { - arr.adminpass = Functions.hash_pass(adminpass); - } else { - arr.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(arr.adminpass), true)); - } - if(userpass != "" || arr.pass == undefined) { - arr.pass = userpass; - } else { - arr.pass = crypto.createHash('sha256').update(Functions.decrypt_string(arr.pass)).digest("base64"); - } - db.collection(coll + "_settings").find(function(err, docs){ - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (arr.hasOwnProperty('pass') && docs[0].userpass == arr.pass))) { - if((arr.hasOwnProperty("offsiteAdd") && !arr.offsiteAdd) || !arr.hasOwnProperty("offsiteAdd")) { - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 5"); - } - var id = arr.id + ""; - var title = arr.title; - var hash = arr.adminpass; - var duration = parseInt(arr.duration); - var source = arr.source; - var tags = arr.tags; - conf = docs; - if(docs !== null && docs.length !== 0 && ((docs[0].addsongs === true && (hash == docs[0].adminpass || docs[0].adminpass === "")) || - docs[0].addsongs === false)) { - db.collection(coll).find({id:id, type:{$ne:"suggested"}}, function(err, docs){ - if(docs !== null && docs.length === 0) { - var guids = [guid]; - var added = Functions.get_time(); - var votes = 1; - db.collection(coll).find({now_playing:true}, function(err, docs){ - if((docs !== null && docs.length === 0)){ - np = true; - } else { - np = false; - } - var new_song = {"added": added,"guids":guids,"id":id,"now_playing":np,"title":title,"tags":tags,"votes":votes, "duration":duration, "start": parseInt(start), "end": parseInt(end), "type": "video", "source": source}; - if(source == "soundcloud") { - if(arr.thumbnail.indexOf("https://i1.sndcdn.com") > -1 || arr.thumbnail.indexOf("https://w1.sndcdn.com") > -1) { - new_song.thumbnail = arr.thumbnail; - } else { - new_song.thumbnail = "https://img.youtube.com/vi/404_notfound/mqdefault.jpg"; - } - } else if(source == "youtube") new_song.thumbnail = "https://img.youtube.com/vi/" + new_song.id + "/mqdefault.jpg"; - db.collection(coll).update({id: id}, new_song, {upsert: true}, function(err, docs){ - new_song._id = "asd"; - if(np) { - List.send_list(coll, undefined, false, true, false); - db.collection(coll + "_settings").update({ id: "config" }, {$set:{startTime: Functions.get_time()}}); - List.send_play(coll, undefined); - var thumbnail = arr.thumbnail != undefined ? arr.thumbnail : undefined; - Frontpage.update_frontpage(coll, id, title, thumbnail, arr.source); - if(source != "soundcloud") Search.get_correct_info(new_song, coll, false); - else if(source == "soundcloud") Search.get_genres_soundcloud(new_song, coll); - } else { - io.to(coll).emit("channel", {type: "added", value: new_song}); - if(source != "soundcloud") Search.get_correct_info(new_song, coll, true); - else if(source == "soundcloud") Search.get_genres_soundcloud(new_song, coll); - } - db.collection("frontpage_lists").update({_id:coll}, {$inc:{count:1}, $set:{accessed: Functions.get_time()}}, {upsert:true}, function(err, docs){}); - List.getNextSong(coll, undefined); - }); - socket.emit("toast", "addedsong"); - }); - } else { - vote(coll, id, guid, socket); - } - }); - } else { - db.collection(coll).find({id: id}, function(err, docs) { - if(docs.length === 0) { - var suggestedAdd = { - "added":Functions.get_time(), - "guids": [guid], - "id":id, - "now_playing": false, - "title":title, - "votes":1, - "duration":duration, - "start": start, - "end": end, - "type":"suggested", - "tags":tags - }; - var source = arr.source; - if(source == "soundcloud") { - suggestedAdd.thumbnail = arr.thumbnail; - suggestedAdd.source = source; - } else { - suggestedAdd.source = "youtube"; - } - db.collection(coll).update({id: id}, {$set: suggestedAdd}, {upsert:true}, function(err, docs){ - socket.emit("toast", "suggested"); - var toSend = suggestedAdd; - toSend.guids = []; - if(source == "soundcloud") toSend.thumbnail = arr.thumbnail; - io.to(coll).emit("suggested", toSend); - }); - } else if(docs[0].now_playing === true){ - socket.emit("toast", "alreadyplay"); - } else{ - if(conf[0].vote === false) vote(coll, id, guid, socket); - else socket.emit("toast", "listhaspass"); - } - }); - } - } else { - if((arr.hasOwnProperty("offsiteAdd") && !arr.offsiteAdd) || !arr.hasOwnProperty("offsiteAdd")) { - socket.emit("auth_required"); - } else { - socket.emit("toast", "listhaspass"); - } - } - }); - }); - } else { - var result = { - arr: { - expected: "object", - got: typeof(arr) - }, - duration: { - expected: "number or string that can be cast to int", - got: arr.hasOwnProperty("duration") ? typeof(arr.duration) : undefined, - } - }; - socket.emit('update_required', result); + }; + socket.emit("update_required", result); + return; } + + try { + if (arr.start == undefined) arr.start = 0; + if (arr.end == undefined) arr.end = parseInt(arr.duration); + var start = parseInt(arr.start); + var end = parseInt(arr.end); + if (start < 0) { + socket.emit("toast", "faulty_start_end"); + return; + } + if (end < 0) { + socket.emit("toast", "faulty_start_end"); + return; + } + if (start >= end) { + start = 0; + arr.duration = end - start; + } + } catch (e) { + return; + } + + if (!arr.hasOwnProperty("source")) { + arr.source = "youtube"; + } + + if ( + typeof arr.id != "string" || + typeof arr.start != "number" || + typeof arr.end != "number" || + typeof arr.title != "string" || + typeof arr.list != "string" || + typeof arr.duration != "number" || + (arr.source == "soundcloud" && + (!arr.hasOwnProperty("thumbnail") || !Functions.isUrl(arr.thumbnail))) + ) { + var result = { + start: { + expected: "number or string that can be cast to int", + got: arr.hasOwnProperty("start") ? typeof arr.start : undefined + }, + end: { + expected: "number or string that can be cast to int", + got: arr.hasOwnProperty("end") ? typeof arr.end : undefined + }, + title: { + expected: "string", + got: arr.hasOwnProperty("title") ? typeof arr.title : undefined + }, + list: { + expected: "string", + got: arr.hasOwnProperty("list") ? typeof arr.list : undefined + }, + duration: { + expected: "number or string that can be cast to int", + got: arr.hasOwnProperty("duration") ? typeof arr.duration : undefined + }, + pass: { + expected: "string", + got: arr.hasOwnProperty("pass") ? typeof arr.pass : undefined + }, + adminpass: { + expected: "string", + got: arr.hasOwnProperty("adminpass") + ? typeof arr.adminpass + : undefined + }, + source: { + expected: "string (youtube or soundcloud)", + got: arr.hasOwnProperty("source") ? typeof arr.source : undefined + }, + thumbnail: { + expected: "url if source == soundcloud", + got: arr.hasOwnProperty("thumbnail") + ? typeof arr.thumbnail + : undefined + } + }; + socket.emit("update_required", result); + return; + } + if (arr.hasOwnProperty("offsiteAdd") && arr.offsiteAdd) { + coll = arr.list; + } + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass + ) { + if (adminpass != "" || arr.adminpass == undefined) { + arr.adminpass = Functions.hash_pass(adminpass); + } else { + arr.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(arr.adminpass), true) + ); + } + if (userpass != "" || arr.pass == undefined) { + arr.pass = userpass; + } else { + arr.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(arr.pass)) + .digest("base64"); + } + db.collection(coll + "_settings").find(function(err, docs) { + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (arr.hasOwnProperty("pass") && docs[0].userpass == arr.pass)) + ) { + if ( + (arr.hasOwnProperty("offsiteAdd") && !arr.offsiteAdd) || + !arr.hasOwnProperty("offsiteAdd") + ) { + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 5" + ); + } + var id = arr.id + ""; + var title = arr.title; + var hash = arr.adminpass; + var duration = parseInt(arr.duration); + var source = arr.source; + var tags = arr.tags; + conf = docs; + if ( + docs !== null && + docs.length !== 0 && + ((docs[0].addsongs === true && + (hash == docs[0].adminpass || docs[0].adminpass === "")) || + docs[0].addsongs === false) + ) { + db.collection(coll).find( + { id: id, type: { $ne: "suggested" } }, + function(err, docs) { + if (docs !== null && docs.length === 0) { + var guids = [guid]; + var added = Functions.get_time(); + var votes = 1; + db.collection(coll).find({ now_playing: true }, function( + err, + docs + ) { + if (docs !== null && docs.length === 0) { + np = true; + } else { + np = false; + } + var new_song = { + added: added, + guids: guids, + id: id, + now_playing: np, + title: title, + tags: tags, + votes: votes, + duration: duration, + start: parseInt(start), + end: parseInt(end), + type: "video", + source: source + }; + if (source == "soundcloud") { + if ( + arr.thumbnail.indexOf("https://i1.sndcdn.com") > -1 || + arr.thumbnail.indexOf("https://w1.sndcdn.com") > -1 + ) { + new_song.thumbnail = arr.thumbnail; + } else { + new_song.thumbnail = + "https://img.youtube.com/vi/404_notfound/mqdefault.jpg"; + } + } else if (source == "youtube") + new_song.thumbnail = + "https://img.youtube.com/vi/" + + new_song.id + + "/mqdefault.jpg"; + db.collection(coll).update( + { id: id }, + new_song, + { upsert: true }, + function(err, docs) { + new_song._id = "asd"; + if (np) { + List.send_list(coll, undefined, false, true, false); + db.collection(coll + "_settings").update( + { id: "config" }, + { $set: { startTime: Functions.get_time() } } + ); + List.send_play(coll, undefined); + var thumbnail = + arr.thumbnail != undefined + ? arr.thumbnail + : undefined; + Frontpage.update_frontpage( + coll, + id, + title, + thumbnail, + arr.source + ); + if (source != "soundcloud") + Search.get_correct_info(new_song, coll, false); + else if (source == "soundcloud") + Search.get_genres_soundcloud(new_song, coll); + } else { + io.to(coll).emit("channel", { + type: "added", + value: new_song + }); + if (source != "soundcloud") + Search.get_correct_info(new_song, coll, true); + else if (source == "soundcloud") + Search.get_genres_soundcloud(new_song, coll); + } + db.collection("frontpage_lists").update( + { _id: coll }, + { + $inc: { count: 1 }, + $set: { accessed: Functions.get_time() } + }, + { upsert: true }, + function(err, docs) {} + ); + List.getNextSong(coll, undefined); + } + ); + socket.emit("toast", "addedsong"); + }); + } else { + vote(coll, id, guid, socket); + } + } + ); + } else { + db.collection(coll).find({ id: id }, function(err, docs) { + if (docs.length === 0) { + var suggestedAdd = { + added: Functions.get_time(), + guids: [guid], + id: id, + now_playing: false, + title: title, + votes: 1, + duration: duration, + start: start, + end: end, + type: "suggested", + tags: tags + }; + var source = arr.source; + if (source == "soundcloud") { + suggestedAdd.thumbnail = arr.thumbnail; + suggestedAdd.source = source; + } else { + suggestedAdd.source = "youtube"; + } + db.collection(coll).update( + { id: id }, + { $set: suggestedAdd }, + { upsert: true }, + function(err, docs) { + socket.emit("toast", "suggested"); + var toSend = suggestedAdd; + toSend.guids = []; + if (source == "soundcloud") + toSend.thumbnail = arr.thumbnail; + io.to(coll).emit("suggested", toSend); + } + ); + } else if (docs[0].now_playing === true) { + socket.emit("toast", "alreadyplay"); + } else { + if (conf[0].vote === false) vote(coll, id, guid, socket); + else socket.emit("toast", "listhaspass"); + } + }); + } + } else { + if ( + (arr.hasOwnProperty("offsiteAdd") && !arr.offsiteAdd) || + !arr.hasOwnProperty("offsiteAdd") + ) { + socket.emit("auth_required"); + } else { + socket.emit("toast", "listhaspass"); + } + } + }); + }); + } else { + var result = { + arr: { + expected: "object", + got: typeof arr + }, + duration: { + expected: "number or string that can be cast to int", + got: arr.hasOwnProperty("duration") ? typeof arr.duration : undefined + } + }; + socket.emit("update_required", result); + } } function voteUndecided(msg, coll, guid, offline, socket) { - var socketid = socket.zoff_id; - if(typeof(msg) === 'object' && msg !== undefined && msg !== null){ - if(msg.hasOwnProperty("id")) msg.id = msg.id + ""; - if(!msg.hasOwnProperty("channel") || !msg.hasOwnProperty("id") || - !msg.hasOwnProperty("type") || typeof(msg.channel) != "string" || - typeof(msg.id) != "string" || typeof(msg.type) != "string") { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - id: { - expected: "string", - got: msg.hasOwnProperty("id") ? typeof(msg.id) : undefined, - }, - type: { - expected: "string", - got: msg.hasOwnProperty("type") ? typeof(msg.type) : undefined, - }, - adminpass: { - expected: "adminpass", - got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - }, - }; - socket.emit('update_required', result); - return; + var socketid = socket.zoff_id; + if (typeof msg === "object" && msg !== undefined && msg !== null) { + if (msg.hasOwnProperty("id")) msg.id = msg.id + ""; + if ( + !msg.hasOwnProperty("channel") || + !msg.hasOwnProperty("id") || + !msg.hasOwnProperty("type") || + typeof msg.channel != "string" || + typeof msg.id != "string" || + typeof msg.type != "string" + ) { + var result = { + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + id: { + expected: "string", + got: msg.hasOwnProperty("id") ? typeof msg.id : undefined + }, + type: { + expected: "string", + got: msg.hasOwnProperty("type") ? typeof msg.type : undefined + }, + adminpass: { + expected: "adminpass", + got: msg.hasOwnProperty("adminpass") + ? typeof msg.adminpass + : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined } - coll = msg.channel.toLowerCase();//.replace(/ /g,''); - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { - if(adminpass != "" || msg.adminpass == undefined) { - msg.adminpass = Functions.hash_pass(adminpass); - } else { - msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true)); - } - if(userpass != "" || msg.pass == undefined) { - msg.pass = userpass; - } else if(msg.hasOwnProperty("pass")){ - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - - db.collection(coll + "_settings").find({id: "config"}, function(err, docs){ - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) { - - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 6"); - - if(msg.type == "del") { - del(msg, socket, socketid); - } else { - var id = msg.id; - var hash = msg.adminpass; - if(docs !== null && docs.length !== 0 && ((docs[0].vote === true && (hash == docs[0].adminpass || docs[0].adminpass === "")) || - docs[0].vote === false)) { - vote(coll, id, guid, socket); - } else { - socket.emit("toast", "listhaspass"); - } - } - } else { - socket.emit("auth_required"); - } - }); - }); - } else { - var result = { - msg: { - expected: "object", - got: typeof(msg) - } - }; - socket.emit('update_required', result); + }; + socket.emit("update_required", result); + return; } + coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass + ) { + if (adminpass != "" || msg.adminpass == undefined) { + msg.adminpass = Functions.hash_pass(adminpass); + } else { + msg.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true) + ); + } + if (userpass != "" || msg.pass == undefined) { + msg.pass = userpass; + } else if (msg.hasOwnProperty("pass")) { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + + db.collection(coll + "_settings").find({ id: "config" }, function( + err, + docs + ) { + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass)) + ) { + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 6" + ); + + if (msg.type == "del") { + del(msg, socket, socketid); + } else { + var id = msg.id; + var hash = msg.adminpass; + if ( + docs !== null && + docs.length !== 0 && + ((docs[0].vote === true && + (hash == docs[0].adminpass || docs[0].adminpass === "")) || + docs[0].vote === false) + ) { + vote(coll, id, guid, socket); + } else { + socket.emit("toast", "listhaspass"); + } + } + } else { + socket.emit("auth_required"); + } + }); + }); + } else { + var result = { + msg: { + expected: "object", + got: typeof msg + } + }; + socket.emit("update_required", result); + } } function shuffle(msg, coll, guid, offline, socket) { - var socketid = socket.zoff_id; - if(!msg.hasOwnProperty("channel") || typeof(msg.channel) != "string") { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - adminpass: { - expected: "string", - got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - }, - }; - socket.emit('update_required', result); - return; + var socketid = socket.zoff_id; + if (!msg.hasOwnProperty("channel") || typeof msg.channel != "string") { + var result = { + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + adminpass: { + expected: "string", + got: msg.hasOwnProperty("adminpass") ? typeof msg.adminpass : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined + } + }; + socket.emit("update_required", result); + return; + } + coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass + ) { + if (adminpass != "" || msg.adminpass == undefined) { + msg.adminpass = Functions.hash_pass(adminpass); + } else if (msg.adminpass != "") { + msg.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true) + ); + } else { + msg.adminpass = ""; } - coll = msg.channel.toLowerCase();//.replace(/ /g,''); - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { - if(adminpass != "" || msg.adminpass == undefined) { - msg.adminpass = Functions.hash_pass(adminpass); - } else if(msg.adminpass != ""){ - msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass),true)); - } else { - msg.adminpass = ""; - } - if(userpass != "" || msg.pass == undefined) { - msg.pass = userpass; - } else if(msg.hasOwnProperty("pass")) { - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - Functions.checkTimeout("shuffle", 5, coll, coll, "foo", "bar", socket, function() { - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 7"); - var hash = msg.adminpass; - db.collection(coll + "_settings").find(function(err, docs){ - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) { - if(docs !== null && docs.length !== 0 && ((docs[0].adminpass == hash && docs[0].adminpass != "") || docs[0].shuffle === false)) - { - db.collection(coll).find({now_playing:false}).forEach(function(err, docs){ - if(!docs){ - List.send_list(coll, undefined, false, true, false, true); - socket.emit("toast", "shuffled"); + if (userpass != "" || msg.pass == undefined) { + msg.pass = userpass; + } else if (msg.hasOwnProperty("pass")) { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + Functions.checkTimeout( + "shuffle", + 5, + coll, + coll, + "foo", + "bar", + socket, + function() { + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 7" + ); + var hash = msg.adminpass; + db.collection(coll + "_settings").find(function(err, docs) { + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass)) + ) { + if ( + docs !== null && + docs.length !== 0 && + ((docs[0].adminpass == hash && docs[0].adminpass != "") || + docs[0].shuffle === false) + ) { + db.collection(coll) + .find({ now_playing: false }) + .forEach(function(err, docs) { + if (!docs) { + List.send_list(coll, undefined, false, true, false, true); + socket.emit("toast", "shuffled"); - return; - }else{ - num = Math.floor(Math.random()*1000000); - db.collection(coll).update({id:docs.id}, {$set:{added:num}}); - } - }); - }else - socket.emit("toast", "wrongpass"); - } else { - socket.emit("auth_required"); - } - }); - - var complete = function(tot, curr){ - if(tot == curr) - { - List.send_list(coll, undefined, false, true, false); - List.getNextSong(coll, undefined); - } - }; + return; + } else { + num = Math.floor(Math.random() * 1000000); + db.collection(coll).update( + { id: docs.id }, + { $set: { added: num } } + ); + } + }); + } else socket.emit("toast", "wrongpass"); + } else { + socket.emit("auth_required"); + } }); - }); + var complete = function(tot, curr) { + if (tot == curr) { + List.send_list(coll, undefined, false, true, false); + List.getNextSong(coll, undefined); + } + }; + } + ); + }); } function del(params, socket, socketid) { - if(params.id){ - var coll = Functions.removeEmojis(params.channel).toLowerCase(); - //coll = coll.replace(/_/g, "").replace(/ /g,''); - - //coll = filter.clean(coll); - db.collection(coll + "_settings").find(function(err, docs){ - if(docs !== null && docs.length !== 0 && docs[0].adminpass == params.adminpass) - { - db.collection(coll).find({id:params.id}, function(err, docs){ - var dont_increment = false; - if(docs[0]){ - if(docs[0].type == "suggested"){ - dont_increment = true; - } - db.collection(coll).remove({id:params.id}, function(err, docs){ - socket.emit("toast", "deletesong"); - io.to(coll).emit("channel", {type:"deleted", value: params.id}); - if(!dont_increment) db.collection("frontpage_lists").update({_id: coll, count: {$gt: 0}}, {$inc: {count: -1}, $set:{accessed: Functions.get_time()}}, {upsert: true}, function(err, docs){}); - }); - } - }); + if (params.id) { + var coll = Functions.removeEmojis(params.channel).toLowerCase(); + //coll = coll.replace(/_/g, "").replace(/ /g,''); + //coll = filter.clean(coll); + db.collection(coll + "_settings").find(function(err, docs) { + if ( + docs !== null && + docs.length !== 0 && + docs[0].adminpass == params.adminpass + ) { + db.collection(coll).find({ id: params.id }, function(err, docs) { + var dont_increment = false; + if (docs[0]) { + if (docs[0].type == "suggested") { + dont_increment = true; } + db.collection(coll).remove({ id: params.id }, function(err, docs) { + socket.emit("toast", "deletesong"); + io.to(coll).emit("channel", { + type: "deleted", + value: params.id + }); + if (!dont_increment) + db.collection("frontpage_lists").update( + { _id: coll, count: { $gt: 0 } }, + { + $inc: { count: -1 }, + $set: { accessed: Functions.get_time() } + }, + { upsert: true }, + function(err, docs) {} + ); + }); + } }); - } + } + }); + } } function delete_all(msg, coll, guid, offline, socket) { - var socketid = socket.zoff_id; - if(typeof(msg) == 'object' ) { - if(!msg.hasOwnProperty('channel') || typeof(msg.channel) != "string") { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - adminpass: { - expected: "adminpass", - got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - }, - }; - socket.emit('update_required', result); - return; + var socketid = socket.zoff_id; + if (typeof msg == "object") { + if (!msg.hasOwnProperty("channel") || typeof msg.channel != "string") { + var result = { + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + adminpass: { + expected: "adminpass", + got: msg.hasOwnProperty("adminpass") + ? typeof msg.adminpass + : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined } - if(coll == undefined) { - coll = msg.channel; - } - //coll = coll.replace(/ /g,''); - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) { - if(adminpass != "" || msg.adminpass == undefined) { - msg.adminpass = Functions.hash_pass(adminpass); - } else if(msg.adminpass != "") { - msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass),true)); - } - if(userpass != "" || msg.pass == undefined) { - msg.pass = userpass; - } else { - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - var hash = msg.adminpass; - var hash_userpass = msg.pass; - db.collection(coll + "_settings").find(function(err, conf) { - if(conf.length == 1 && conf) { - conf = conf[0]; - if(conf.adminpass == hash && conf.adminpass != "" && (conf.userpass == "" || conf.userpass == undefined || (conf.userpass != "" && conf.userpass != undefined && conf.pass == hash_userpass))) { - db.collection(coll).remove({views: {$exists: false}, type: "video"}, {multi: true}, function(err, succ) { - List.send_list(coll, false, true, true, true); - db.collection("frontpage_lists").update({_id: coll}, {$set: {count: 0, accessed: Functions.get_time()}}, {upsert: true}, function(err, docs) {}); - socket.emit("toast", "deleted_songs"); - }); - } else { - socket.emit("toast", "listhaspass"); - } - } - }); - }); - } else { - var result = { - msg: { - expected: "object", - got: typeof(msg) - }, - }; - socket.emit('update_required', result); - return; + }; + socket.emit("update_required", result); + return; } + if (coll == undefined) { + coll = msg.channel; + } + //coll = coll.replace(/ /g,''); + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass, + gotten + ) { + if (adminpass != "" || msg.adminpass == undefined) { + msg.adminpass = Functions.hash_pass(adminpass); + } else if (msg.adminpass != "") { + msg.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true) + ); + } + if (userpass != "" || msg.pass == undefined) { + msg.pass = userpass; + } else { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + var hash = msg.adminpass; + var hash_userpass = msg.pass; + db.collection(coll + "_settings").find(function(err, conf) { + if (conf.length == 1 && conf) { + conf = conf[0]; + if ( + conf.adminpass == hash && + conf.adminpass != "" && + (conf.userpass == "" || + conf.userpass == undefined || + (conf.userpass != "" && + conf.userpass != undefined && + conf.pass == hash_userpass)) + ) { + db.collection(coll).remove( + { views: { $exists: false }, type: "video" }, + { multi: true }, + function(err, succ) { + List.send_list(coll, false, true, true, true); + db.collection("frontpage_lists").update( + { _id: coll }, + { $set: { count: 0, accessed: Functions.get_time() } }, + { upsert: true }, + function(err, docs) {} + ); + socket.emit("toast", "deleted_songs"); + } + ); + } else { + socket.emit("toast", "listhaspass"); + } + } + }); + }); + } else { + var result = { + msg: { + expected: "object", + got: typeof msg + } + }; + socket.emit("update_required", result); + return; + } } function vote(coll, id, guid, socket) { - //coll = coll.replace(/ /g,''); - db.collection(coll).find({id:id, now_playing: false, type:"video"}, function(err, docs){ - if(docs !== null && docs.length > 0 && !Functions.contains(docs[0].guids, guid)) - { - db.collection(coll).update({id:id}, {$inc:{votes:1}, $set:{added:Functions.get_time()}, $push :{guids: guid}}, function(err, docs) - { - socket.emit("toast", "voted"); - io.to(coll).emit("channel", {type: "vote", value: id, time: Functions.get_time()}); - - List.getNextSong(coll, undefined); + //coll = coll.replace(/ /g,''); + db.collection(coll).find( + { id: id, now_playing: false, type: "video" }, + function(err, docs) { + if ( + docs !== null && + docs.length > 0 && + !Functions.contains(docs[0].guids, guid) + ) { + db.collection(coll).update( + { id: id }, + { + $inc: { votes: 1 }, + $set: { added: Functions.get_time() }, + $push: { guids: guid } + }, + function(err, docs) { + socket.emit("toast", "voted"); + io.to(coll).emit("channel", { + type: "vote", + value: id, + time: Functions.get_time() }); - }else - { - socket.emit("toast", "alreadyvoted"); - } - }); + + List.getNextSong(coll, undefined); + } + ); + } else { + socket.emit("toast", "alreadyvoted"); + } + } + ); } module.exports.addPlaylist = addPlaylist; diff --git a/server/handlers/list_settings.js b/server/handlers/list_settings.js index 0b06e0e6..1cd67182 100644 --- a/server/handlers/list_settings.js +++ b/server/handlers/list_settings.js @@ -1,282 +1,397 @@ -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var crypto = require('crypto'); -var Filter = require('bad-words'); -var filter = new Filter({ placeHolder: 'x'}); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var crypto = require("crypto"); +var Filter = require("bad-words"); +var filter = new Filter({ placeHolder: "x" }); /*var filter = { clean: function(str) { return str; } }*/ var projects = require(pathThumbnails + "/handlers/aggregates.js"); -var db = require(pathThumbnails + '/handlers/db.js'); +var db = require(pathThumbnails + "/handlers/db.js"); function password(inp, coll, guid, offline, socket) { - var sessionId = Functions.getSession(socket); - if(sessionId == "") sessionId = "empty"; - if(inp !== undefined && inp !== null && inp !== "") - { - if(!inp.hasOwnProperty("password") || !inp.hasOwnProperty("channel") || - typeof(inp.password) != "string" || typeof(inp.channel) != "string") { - var result = { - channel: { - expected: "string", - got: inp.hasOwnProperty("channel") ? typeof(inp.channel) : undefined, - }, - password: { - expected: "password", - got: inp.hasOwnProperty("password") ? typeof(inp.password) : undefined, - }, - }; - socket.emit('update_required', result); - return; + var sessionId = Functions.getSession(socket); + if (sessionId == "") sessionId = "empty"; + if (inp !== undefined && inp !== null && inp !== "") { + if ( + !inp.hasOwnProperty("password") || + !inp.hasOwnProperty("channel") || + typeof inp.password != "string" || + typeof inp.channel != "string" + ) { + var result = { + channel: { + expected: "string", + got: inp.hasOwnProperty("channel") ? typeof inp.channel : undefined + }, + password: { + expected: "password", + got: inp.hasOwnProperty("password") ? typeof inp.password : undefined } - pw = inp.password; - try { - coll = inp.channel; - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - //coll = coll.replace(/ /g,''); - uncrypted = pw; - pw = Functions.hash_pass(Functions.decrypt_string(pw), true); - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 8"); - Functions.getSessionAdminUser(sessionId, coll, function(userpass, adminpass) { - adminpass = Functions.hash_pass(adminpass); - db.collection(coll + "_settings").find(function(err, docs){ - if(docs !== null && docs.length !== 0) - { - if(docs[0].adminpass === "" || docs[0].adminpass == Functions.hash_pass(pw)) - { - Functions.setSessionAdminPass(sessionId, inp.password, coll, function() { - db.collection(coll + "_settings").update({ id: "config" }, {$set:{adminpass:Functions.hash_pass(pw)}}, function(err, docs){ - if(adminpass != pw && adminpass != "") { - socket.emit("toast", "changedpass"); - } else { - socket.emit("toast", "correctpass"); - } - socket.emit("pw", true); - }); - }); - } else if(docs[0].adminpass === "" || docs[0].adminpass == adminpass) { - Functions.setSessionAdminPass(sessionId, inp.password, coll, function() { - db.collection(coll + "_settings").update({ id: "config" }, {$set:{adminpass:Functions.hash_pass(pw)}}, function(err, docs){ - if(adminpass != pw) { - socket.emit("toast", "changedpass"); - } - socket.emit("pw", true); - }); - }); - } else { - Functions.setSessionAdminPass(Functions.getSession(socket), "", coll, function() { - socket.emit("toast", "wrongpass"); - socket.emit("pw", false); - }); - } - } - }); - }); - } else { - var result = { - inp: { - expected: "string", - got: typeof(inpt) - }, - }; - socket.emit('update_required', result); + }; + socket.emit("update_required", result); + return; } + pw = inp.password; + try { + coll = inp.channel; + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + //coll = coll.replace(/ /g,''); + uncrypted = pw; + pw = Functions.hash_pass(Functions.decrypt_string(pw), true); + Functions.check_inlist(coll, guid, socket, offline, undefined, "place 8"); + Functions.getSessionAdminUser(sessionId, coll, function( + userpass, + adminpass + ) { + adminpass = Functions.hash_pass(adminpass); + db.collection(coll + "_settings").find(function(err, docs) { + if (docs !== null && docs.length !== 0) { + if ( + docs[0].adminpass === "" || + docs[0].adminpass == Functions.hash_pass(pw) + ) { + Functions.setSessionAdminPass( + sessionId, + inp.password, + coll, + function() { + db.collection(coll + "_settings").update( + { id: "config" }, + { $set: { adminpass: Functions.hash_pass(pw) } }, + function(err, docs) { + if (adminpass != pw && adminpass != "") { + socket.emit("toast", "changedpass"); + } else { + socket.emit("toast", "correctpass"); + } + socket.emit("pw", true); + } + ); + } + ); + } else if ( + docs[0].adminpass === "" || + docs[0].adminpass == adminpass + ) { + Functions.setSessionAdminPass( + sessionId, + inp.password, + coll, + function() { + db.collection(coll + "_settings").update( + { id: "config" }, + { $set: { adminpass: Functions.hash_pass(pw) } }, + function(err, docs) { + if (adminpass != pw) { + socket.emit("toast", "changedpass"); + } + socket.emit("pw", true); + } + ); + } + ); + } else { + Functions.setSessionAdminPass( + Functions.getSession(socket), + "", + coll, + function() { + socket.emit("toast", "wrongpass"); + socket.emit("pw", false); + } + ); + } + } + }); + }); + } else { + var result = { + inp: { + expected: "string", + got: typeof inpt + } + }; + socket.emit("update_required", result); + } } function conf_function(params, coll, guid, offline, socket) { - if(params !== undefined && params !== null && params !== "") - { - if(coll !== undefined) { - try { - coll = params.channel;//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); + if (params !== undefined && params !== null && params !== "") { + if (coll !== undefined) { + try { + coll = params.channel; //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); - //coll = filter.clean(coll); - } catch(e) { - return; - } - } - - if(coll == "" || coll == undefined || coll == null) { - socket.emit("update_required"); - return; - } - - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 9"); - - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) { - if(gotten) { - params.adminpass = adminpass; - if(!params.userpass_changed) params.userpass = userpass; - } - if(!params.hasOwnProperty('voting') || !params.hasOwnProperty('addsongs') || - !params.hasOwnProperty('longsongs') || !params.hasOwnProperty('frontpage') || - !params.hasOwnProperty('allvideos') || !params.hasOwnProperty('removeplay') || - !params.hasOwnProperty('adminpass') || !params.hasOwnProperty('skipping') || - !params.hasOwnProperty('shuffling') || !params.hasOwnProperty('channel') || - typeof(params.userpass) != "string" || typeof(params.adminpass) != "string" || - typeof(params.voting) != "boolean" || typeof(params.addsongs) != "boolean" || - typeof(params.longsongs) != "boolean" || typeof(params.frontpage) != "boolean" || - typeof(params.allvideos) != "boolean" || typeof(params.removeplay) != "boolean" || - typeof(params.skipping) != "boolean" || typeof(params.shuffling) != "boolean" || - typeof(params.userpass_changed) != "boolean") { - var result = { - adminpass: { - expected: "string", - got: params.hasOwnProperty("adminpass") ? typeof(params.adminpass) : undefined, - }, - userpass: { - expected: "string", - got: params.hasOwnProperty("userpass") ? typeof(params.userpass) : undefined, - }, - vote: { - expected: "boolean", - got: params.hasOwnProperty("vote") ? typeof(params.vote) : undefined, - }, - addsongs: { - expected: "boolean", - got: params.hasOwnProperty("addsongs") ? typeof(params.addsongs) : undefined, - }, - longsongs: { - expected: "boolean", - got: params.hasOwnProperty("longsongs") ? typeof(params.longsongs) : undefined, - }, - frontpage: { - expected: "boolean", - got: params.hasOwnProperty("frontpage") ? typeof(params.frontpage) : undefined, - }, - skipping: { - expected: "boolean", - got: params.hasOwnProperty("skipping") ? typeof(params.skipping) : undefined, - }, - shuffling: { - expected: "boolean", - got: params.hasOwnProperty("shuffling") ? typeof(params.shuffling) : undefined, - }, - userpass_changed: { - expected: "boolean", - got: params.hasOwnProperty("userpass_changed") ? typeof(params.userpass_changed) : undefined, - } - }; - socket.emit("update_required", result); - return; - } - var voting = params.voting; - var addsongs = params.addsongs; - var longsongs = params.longsongs; - var frontpage = params.frontpage; - var allvideos = params.allvideos; - var removeplay = params.removeplay; - var adminpass = params.adminpass; - var skipping = params.skipping; - var shuffling = params.shuffling; - - var userpass = Functions.decrypt_string(params.userpass); - - if((!params.userpass_changed && frontpage) || (params.userpass_changed && userpass == "")) { - userpass = ""; - } else if(params.userpass_changed && userpass != "") { - frontpage = false; - } - var description = ""; - var hash; - if(params.description) description = params.description; - if(adminpass !== "" && !gotten) { - hash = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(adminpass), true)); - } else if(adminpass !== "" && gotten) { - hash = Functions.hash_pass(adminpass); - } else { - hash = adminpass; - } - if(userpass != "") { - if(!params.userpass_changed && gotten) { - - } else { - userpass = crypto.createHash('sha256').update(userpass).digest("base64"); - } - } - db.collection(coll + "_settings").find({id: "config"}, function(err, docs){ - if(docs !== null && docs.length !== 0 && (docs[0].adminpass === "" || docs[0].adminpass == hash)) { - var obj = { - addsongs:addsongs, - allvideos:allvideos, - frontpage:frontpage, - skip:skipping, - vote:voting, - removeplay:removeplay, - shuffle:shuffling, - longsongs:longsongs, - adminpass:hash, - desc: description, - }; - if(params.hasOwnProperty("toggleChat") && docs[0].adminpass != "" && docs[0].adminpass != undefined && docs[0].adminpass == hash) { - obj.toggleChat = params.toggleChat; - } - if(params.hasOwnProperty("strictSkip") && docs[0].adminpass != "" && docs[0].adminpass != undefined && docs[0].adminpass == hash) { - obj.strictSkip = params.strictSkip; - } - if(params.hasOwnProperty("strictSkipNumber") && docs[0].adminpass != "" && docs[0].adminpass != undefined && docs[0].adminpass == hash) { - try { - obj.strictSkipNumber = parseInt(params.strictSkipNumber); - } catch(e) {} - } - if(params.userpass_changed) { - obj["userpass"] = userpass; - } else if (frontpage) { - obj["userpass"] = ""; - } - db.collection(coll + "_settings").update({ id: "config" }, { - $set:obj - }, function(err, docs){ - Functions.setSessionUserPass(Functions.getSession(socket), obj["userpass"], coll, function() { - db.collection(coll + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs){ - if(docs[0].adminpass !== "") docs[0].adminpass = true; - if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true; - else docs[0].userpass = false; - io.to(coll).emit("conf", docs); - socket.emit("toast", "savedsettings"); - - db.collection("frontpage_lists").update({_id: coll}, {$set:{ - frontpage:frontpage, accessed: Functions.get_time()} - }, - {upsert:true}, function(err, docs){}); - }); - }); - }); - } else { - socket.emit("toast", "wrongpass"); - } - }); - }); - } else { - var result = { - params: { - expected: "object", - got: typeof(params), - } - } - socket.emit('update_required', result); + //coll = filter.clean(coll); + } catch (e) { + return; + } } + if (coll == "" || coll == undefined || coll == null) { + socket.emit("update_required"); + return; + } + + Functions.check_inlist(coll, guid, socket, offline, undefined, "place 9"); + + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass, + gotten + ) { + if (gotten) { + params.adminpass = adminpass; + if (!params.userpass_changed) params.userpass = userpass; + } + if ( + !params.hasOwnProperty("voting") || + !params.hasOwnProperty("addsongs") || + !params.hasOwnProperty("longsongs") || + !params.hasOwnProperty("frontpage") || + !params.hasOwnProperty("allvideos") || + !params.hasOwnProperty("removeplay") || + !params.hasOwnProperty("adminpass") || + !params.hasOwnProperty("skipping") || + !params.hasOwnProperty("shuffling") || + !params.hasOwnProperty("channel") || + typeof params.userpass != "string" || + typeof params.adminpass != "string" || + typeof params.voting != "boolean" || + typeof params.addsongs != "boolean" || + typeof params.longsongs != "boolean" || + typeof params.frontpage != "boolean" || + typeof params.allvideos != "boolean" || + typeof params.removeplay != "boolean" || + typeof params.skipping != "boolean" || + typeof params.shuffling != "boolean" || + typeof params.userpass_changed != "boolean" + ) { + var result = { + adminpass: { + expected: "string", + got: params.hasOwnProperty("adminpass") + ? typeof params.adminpass + : undefined + }, + userpass: { + expected: "string", + got: params.hasOwnProperty("userpass") + ? typeof params.userpass + : undefined + }, + vote: { + expected: "boolean", + got: params.hasOwnProperty("vote") ? typeof params.vote : undefined + }, + addsongs: { + expected: "boolean", + got: params.hasOwnProperty("addsongs") + ? typeof params.addsongs + : undefined + }, + longsongs: { + expected: "boolean", + got: params.hasOwnProperty("longsongs") + ? typeof params.longsongs + : undefined + }, + frontpage: { + expected: "boolean", + got: params.hasOwnProperty("frontpage") + ? typeof params.frontpage + : undefined + }, + skipping: { + expected: "boolean", + got: params.hasOwnProperty("skipping") + ? typeof params.skipping + : undefined + }, + shuffling: { + expected: "boolean", + got: params.hasOwnProperty("shuffling") + ? typeof params.shuffling + : undefined + }, + userpass_changed: { + expected: "boolean", + got: params.hasOwnProperty("userpass_changed") + ? typeof params.userpass_changed + : undefined + } + }; + socket.emit("update_required", result); + return; + } + var voting = params.voting; + var addsongs = params.addsongs; + var longsongs = params.longsongs; + var frontpage = params.frontpage; + var allvideos = params.allvideos; + var removeplay = params.removeplay; + var adminpass = params.adminpass; + var skipping = params.skipping; + var shuffling = params.shuffling; + + var userpass = Functions.decrypt_string(params.userpass); + + if ( + (!params.userpass_changed && frontpage) || + (params.userpass_changed && userpass == "") + ) { + userpass = ""; + } else if (params.userpass_changed && userpass != "") { + frontpage = false; + } + var description = ""; + var hash; + if (params.description) description = params.description; + if (adminpass !== "" && !gotten) { + hash = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(adminpass), true) + ); + } else if (adminpass !== "" && gotten) { + hash = Functions.hash_pass(adminpass); + } else { + hash = adminpass; + } + if (userpass != "") { + if (!params.userpass_changed && gotten) { + } else { + userpass = crypto + .createHash("sha256") + .update(userpass) + .digest("base64"); + } + } + db.collection(coll + "_settings").find({ id: "config" }, function( + err, + docs + ) { + if ( + docs !== null && + docs.length !== 0 && + (docs[0].adminpass === "" || docs[0].adminpass == hash) + ) { + var obj = { + addsongs: addsongs, + allvideos: allvideos, + frontpage: frontpage, + skip: skipping, + vote: voting, + removeplay: removeplay, + shuffle: shuffling, + longsongs: longsongs, + adminpass: hash, + desc: description + }; + if ( + params.hasOwnProperty("toggleChat") && + docs[0].adminpass != "" && + docs[0].adminpass != undefined && + docs[0].adminpass == hash + ) { + obj.toggleChat = params.toggleChat; + } + if ( + params.hasOwnProperty("strictSkip") && + docs[0].adminpass != "" && + docs[0].adminpass != undefined && + docs[0].adminpass == hash + ) { + obj.strictSkip = params.strictSkip; + } + if ( + params.hasOwnProperty("strictSkipNumber") && + docs[0].adminpass != "" && + docs[0].adminpass != undefined && + docs[0].adminpass == hash + ) { + try { + obj.strictSkipNumber = parseInt(params.strictSkipNumber); + } catch (e) {} + } + if (params.userpass_changed) { + obj["userpass"] = userpass; + } else if (frontpage) { + obj["userpass"] = ""; + } + db.collection(coll + "_settings").update( + { id: "config" }, + { + $set: obj + }, + function(err, docs) { + Functions.setSessionUserPass( + Functions.getSession(socket), + obj["userpass"], + coll, + function() { + db.collection(coll + "_settings").aggregate( + [ + { + $match: { + id: "config" + } + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if (docs[0].adminpass !== "") docs[0].adminpass = true; + if ( + docs[0].hasOwnProperty("userpass") && + docs[0].userpass != "" + ) + docs[0].userpass = true; + else docs[0].userpass = false; + io.to(coll).emit("conf", docs); + socket.emit("toast", "savedsettings"); + + db.collection("frontpage_lists").update( + { _id: coll }, + { + $set: { + frontpage: frontpage, + accessed: Functions.get_time() + } + }, + { upsert: true }, + function(err, docs) {} + ); + } + ); + } + ); + } + ); + } else { + socket.emit("toast", "wrongpass"); + } + }); + }); + } else { + var result = { + params: { + expected: "object", + got: typeof params + } + }; + socket.emit("update_required", result); + } } module.exports.password = password; diff --git a/server/handlers/notifications.js b/server/handlers/notifications.js index 31f687ef..26f60e4e 100644 --- a/server/handlers/notifications.js +++ b/server/handlers/notifications.js @@ -1,39 +1,48 @@ -var path = require('path'); +var path = require("path"); function requested_change(type, string, channel) { - try { - //channel = channel.replace(/ /g,''); - var nodemailer = require('nodemailer'); - var mailconfig = require(path.join(__dirname, '../config/mailconfig.js')); + try { + //channel = channel.replace(/ /g,''); + var nodemailer = require("nodemailer"); + var mailconfig = require(path.join(__dirname, "../config/mailconfig.js")); - let transporter = nodemailer.createTransport(mailconfig); + let transporter = nodemailer.createTransport(mailconfig); - transporter.verify(function(error, success) { - if (error) { - return; - } else { - var message = "A " + type + " change was requested on " + channel + "

New supposed value is:

" + string + "


\ + transporter.verify(function(error, success) { + if (error) { + return; + } else { + var message = + "A " + + type + + " change was requested on " + + channel + + "

New supposed value is:

" + + string + + "


\ Go to https://admin.zoff.me/ to accept or decline the request."; - var msg = { - from: mailconfig.from, - to: mailconfig.notify_mail, - subject: 'ZOFF: Requested new ' + type, - text: message, - html: message, - } - transporter.sendMail(msg, (error, info) => { - if (error) { - transporter.close(); - return; - } - transporter.close(); - }); - } + var msg = { + from: mailconfig.from, + to: mailconfig.notify_mail, + subject: "ZOFF: Requested new " + type, + text: message, + html: message + }; + transporter.sendMail(msg, (error, info) => { + if (error) { + transporter.close(); + return; + } + transporter.close(); }); - } catch(e) { - console.log("Mail is not configured and wont work"); - console.log("Seems you forgot to create a mailconfig.js in /server/config/. Have a look at the mailconfig.example.js."); - } + } + }); + } catch (e) { + console.log("Mail is not configured and wont work"); + console.log( + "Seems you forgot to create a mailconfig.js in /server/config/. Have a look at the mailconfig.example.js." + ); + } } module.exports.requested_change = requested_change; diff --git a/server/handlers/search.js b/server/handlers/search.js index cf057533..27958f95 100644 --- a/server/handlers/search.js +++ b/server/handlers/search.js @@ -1,512 +1,668 @@ -var path = require('path'); +var path = require("path"); var time_regex = /P((([0-9]*\.?[0-9]*)Y)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)W)?(([0-9]*\.?[0-9]*)D)?)?(T(([0-9]*\.?[0-9]*)H)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)S)?)?/; try { - var keys = require(path.join(__dirname, '../config/api_key.js')); - var key = keys.youtube; - var soundcloudKey = keys.soundcloud; -} catch(e) { - console.log("Error - missing file"); - console.log("Seems you forgot to create the file api_key.js in /server/config/. Have a look at api_key.example.js."); - process.exit(1); + var keys = require(path.join(__dirname, "../config/api_key.js")); + var key = keys.youtube; + var soundcloudKey = keys.soundcloud; +} catch (e) { + console.log( + "(!) Missing file - /config/api_key.js Have a look at /config/api_key.example.js. The server won't run without this existing." + ); + process.exit(1); } -var request = require('request'); -var db = require(pathThumbnails + '/handlers/db.js'); +var request = require("request"); +var db = require(pathThumbnails + "/handlers/db.js"); var countryCodes = ["US", "NO", "SE", "DK", "CA", "EU", "UK"]; function check_if_error_or_blocked(id, channel, errored, callback) { - if(!errored) { - callback(false); - return; + if (!errored) { + callback(false); + return; + } + db.collection(channel).find({ id: id, now_playing: true }, function( + err, + song + ) { + if (song.length == 0) { + callback(false); + return; } - db.collection(channel).find({id: id, now_playing: true}, function(err, song) { - if(song.length == 0) { + var song_info = song[0]; + if (song_info.source != "soundcloud") { + request( + { + type: "GET", + url: + "https://www.googleapis.com/youtube/v3/videos?part=id,status,contentDetails&key=" + + key + + "&id=" + + song_info.id + }, + function(error, response, body) { + try { + var resp = JSON.parse(body); + if (resp.pageInfo.totalResults == 0) { + callback(true); + return; + } else if (!resp.items[0].status.embeddable) { + callback(true); + return; + } else if ( + resp.items[0].contentDetails.hasOwnProperty("licensedContent") && + resp.items[0].contentDetails.licensedContent + ) { + callback(true); + return; + } else if ( + resp.items[0].contentDetails.hasOwnProperty( + "regionRestriction" + ) && + resp.items[0].contentDetails.regionRestriction.hasOwnProperty( + "blocked" + ) && + resp.items[0].contentDetails.regionRestriction.blocked.length > 0 + ) { + var any = resp.items[0].contentDetails.blocked.some(function( + element + ) { + return countryCodes.indexOf(element) > -1; + }); + if (any) { + callback(true); + return; + } + } callback(false); return; + } catch (e) { + callback(true); + return; + } } - var song_info = song[0]; - if(song_info.source != "soundcloud") { - request({ - type: "GET", - url: "https://www.googleapis.com/youtube/v3/videos?part=id,status,contentDetails&key="+key+"&id=" + song_info.id, - }, function(error, response, body) { - try { - var resp = JSON.parse(body); - if(resp.pageInfo.totalResults == 0) { - callback(true); - return; - } else if(!resp.items[0].status.embeddable) { - callback(true); - return; - } else if(resp.items[0].contentDetails.hasOwnProperty("licensedContent") && - resp.items[0].contentDetails.licensedContent) { - callback(true); - return; - } else if(resp.items[0].contentDetails.hasOwnProperty("regionRestriction") && - resp.items[0].contentDetails.regionRestriction.hasOwnProperty("blocked") && - resp.items[0].contentDetails.regionRestriction.blocked.length > 0) { - var any = resp.items[0].contentDetails.blocked.some(function(element) { - return countryCodes.indexOf(element) > -1; - }); - if(any) { - callback(true); - return; - } - } - callback(false); - return; - } catch(e){ - callback(true); - return; - } - }); - } else { - request({ - type: "GET", - url: "http://api.soundcloud.com/tracks/" + song_info.id + "?client_id=" + soundcloudKey, - }, function(error, response, body) { - try { - var resp = JSON.parse(body); - if(resp.sharing != "public" || resp.embeddable_by != "all") { - callback(true); - return; - } - callback(false); - return; - } catch(e){ - callback(true); - return; - } - }); + ); + } else { + request( + { + type: "GET", + url: + "http://api.soundcloud.com/tracks/" + + song_info.id + + "?client_id=" + + soundcloudKey + }, + function(error, response, body) { + try { + var resp = JSON.parse(body); + if (resp.sharing != "public" || resp.embeddable_by != "all") { + callback(true); + return; + } + callback(false); + return; + } catch (e) { + callback(true); + return; + } } - }); + ); + } + }); } function filterFunction(el) { - return el != null && - el != "" && - el != undefined && - el.trim() != '' + return el != null && el != "" && el != undefined && el.trim() != ""; } function get_genres_soundcloud(song, channel) { - request("http://api.soundcloud.com/tracks/" + song.id + "?client_id=" + soundcloudKey, function(err, response, body) { - if(err) { - console.log("error start", err, song, "error end"); - return; - } - try { - var object = JSON.parse(body); - if(!object.hasOwnProperty("genre") || !object.hasOwnProperty("tag_list")) return; - var genre = object.genre + ","; - genre = genre.toLowerCase().split(",").concat(object.tag_list.toLowerCase().split('"')); - genre = genre.filter(filterFunction); + request( + "http://api.soundcloud.com/tracks/" + + song.id + + "?client_id=" + + soundcloudKey, + function(err, response, body) { + if (err) { + console.log("error start", err, song, "error end"); + return; + } + try { + var object = JSON.parse(body); + if ( + !object.hasOwnProperty("genre") || + !object.hasOwnProperty("tag_list") + ) + return; + var genre = object.genre + ","; + genre = genre + .toLowerCase() + .split(",") + .concat(object.tag_list.toLowerCase().split('"')); + genre = genre.filter(filterFunction); - db.collection(channel).update({"id": song.id}, { - $set: { - "tags": genre - } - }, function(e,d) { - - }); - } catch(e) { - console.log("errored 2", e); - } - }); + db.collection(channel).update( + { id: song.id }, + { + $set: { + tags: genre + } + }, + function(e, d) {} + ); + } catch (e) { + console.log("errored 2", e); + } + } + ); } function get_genres_list(list, channel) { - var youtube_array = ""; - var i = 0; - try { - for(var i = 0; i < list.length; i++) { - - if(!list[i].hasOwnProperty("id")) continue; - if(list[i].source == undefined || list[i].source == "youtube") { - youtube_array += list[i].id + ","; - } - else if(list[i].source != undefined && list[i].source == "soundcloud") { - get_genres_soundcloud(list[i], channel); - } - } - if(youtube_array.length > 0) { - if(youtube_array > 49) { - var subList = []; - for(var i = 0; i < youtube_array.length; i++) { - subList.push(youtube_array[i]); - if(subList.length > 49) { - get_genres_youtube(subList.join(","), channel); - subList = []; - } - } - get_genres_youtube(subList.join(","), channel); - subList = []; - } else { - get_genres_youtube(youtube_array, channel); - } - } - } catch(e) { - console.log("errored", e); - return; + var youtube_array = ""; + var i = 0; + try { + for (var i = 0; i < list.length; i++) { + if (!list[i].hasOwnProperty("id")) continue; + if (list[i].source == undefined || list[i].source == "youtube") { + youtube_array += list[i].id + ","; + } else if ( + list[i].source != undefined && + list[i].source == "soundcloud" + ) { + get_genres_soundcloud(list[i], channel); + } } + if (youtube_array.length > 0) { + if (youtube_array > 49) { + var subList = []; + for (var i = 0; i < youtube_array.length; i++) { + subList.push(youtube_array[i]); + if (subList.length > 49) { + get_genres_youtube(subList.join(","), channel); + subList = []; + } + } + get_genres_youtube(subList.join(","), channel); + subList = []; + } else { + get_genres_youtube(youtube_array, channel); + } + } + } catch (e) { + console.log("errored", e); + return; + } } - function start_soundcloud_get(arr, channel, callback) { - get_genres_soundcloud_recursive(arr, channel, 0, callback); + get_genres_soundcloud_recursive(arr, channel, 0, callback); } function get_genres_soundcloud_recursive(arr, channel, i, callback) { - if(i >= arr.length) { - if(typeof(callback) == "function") callback(); + if (i >= arr.length) { + if (typeof callback == "function") callback(); + return; + } + var song = arr[i]; + request( + "http://api.soundcloud.com/tracks/" + + song.id + + "?client_id=" + + soundcloudKey, + function(err, response, body) { + if (err) { + console.log("error start", err, song, "error end"); + get_genres_soundcloud_recursive(arr, channel, i + 1, callback); return; - } - var song = arr[i]; - request("http://api.soundcloud.com/tracks/" + song.id + "?client_id=" + soundcloudKey, function(err, response, body) { - if(err) { - console.log("error start", err, song, "error end"); - get_genres_soundcloud_recursive(arr, channel, i + 1, callback); - return; + } + try { + var object = JSON.parse(body); + if ( + !object.hasOwnProperty("genre") || + !object.hasOwnProperty("tag_list") + ) { + get_genres_soundcloud_recursive(arr, channel, i + 1, callback); + return; } - try { - var object = JSON.parse(body); - if(!object.hasOwnProperty("genre") || !object.hasOwnProperty("tag_list")) { - get_genres_soundcloud_recursive(arr, channel, i + 1, callback); - return; - } - var genre = object.genre + ","; - genre = genre.toLowerCase().split(",").concat(object.tag_list.toLowerCase().split('"')); - genre = genre.filter(filterFunction); + var genre = object.genre + ","; + genre = genre + .toLowerCase() + .split(",") + .concat(object.tag_list.toLowerCase().split('"')); + genre = genre.filter(filterFunction); - db.collection(channel).update({"id": song.id}, { - $set: { - "tags": genre - } - }, function(e,d) { - get_genres_soundcloud_recursive(arr, channel, i + 1, callback); - }); - } catch(e) { - console.log("errored 2", e); + db.collection(channel).update( + { id: song.id }, + { + $set: { + tags: genre + } + }, + function(e, d) { get_genres_soundcloud_recursive(arr, channel, i + 1, callback); - } - }); + } + ); + } catch (e) { + console.log("errored 2", e); + get_genres_soundcloud_recursive(arr, channel, i + 1, callback); + } + } + ); } function get_genres_list_recursive(list, channel, callback) { - var youtube_array = []; - var soundcloud_array = []; - for(var i = 0; i < list.length; i++) { - if(!list[i].hasOwnProperty("id")) continue; - if(list[i].source == undefined || list[i].source == "youtube") { - youtube_array.push(list[i]); - } - else if(list[i].source != undefined && list[i].source == "soundcloud") { - soundcloud_array.push(list[i]); - } + var youtube_array = []; + var soundcloud_array = []; + for (var i = 0; i < list.length; i++) { + if (!list[i].hasOwnProperty("id")) continue; + if (list[i].source == undefined || list[i].source == "youtube") { + youtube_array.push(list[i]); + } else if (list[i].source != undefined && list[i].source == "soundcloud") { + soundcloud_array.push(list[i]); } - start_youtube_get(youtube_array, channel, function() { - start_soundcloud_get(soundcloud_array, channel, function() { - if(typeof(callback) == "function") callback(); - }) - }) + } + start_youtube_get(youtube_array, channel, function() { + start_soundcloud_get(soundcloud_array, channel, function() { + if (typeof callback == "function") callback(); + }); + }); } function start_youtube_get(arr, channel, callback) { - get_genres_youtube_recursive(arr, channel, 0, callback) + get_genres_youtube_recursive(arr, channel, 0, callback); } function get_genres_youtube_recursive(arr, channel, i, callback) { - if(i >= arr.length) { - if(typeof(callback) == "function") callback(); + if (i >= arr.length) { + if (typeof callback == "function") callback(); + return; + } + var ids = []; + for (var y = i; y < arr.length; y++) { + if (ids.length >= 48) { + break; + } + ids.push(arr[y].id); + } + request( + { + type: "GET", + url: + "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id,topicDetails&key=" + + key + + "&id=" + + ids.join(",") + }, + function(error, response, body) { + if (error) { + get_genres_youtube_recursive(arr, channel, i + ids.length, callback); return; + } + var resp = JSON.parse(body); + if (!resp.hasOwnProperty("items")) { + get_genres_youtube_recursive(arr, channel, i + ids.length, callback); + return; + } + if (resp.items.length > 0) { + for (var z = 0; z < resp.items.length; z++) { + if (!resp.items[z].hasOwnProperty("topicDetails")) continue; + var genre = resp.items[z].topicDetails.topicCategories; + genre = genre.join(","); + genre = genre.replace( + new RegExp("https://en.wikipedia.org/wiki/", "g"), + "" + ); + genre = genre + .replace(/_/g, " ") + .toLowerCase() + .split(","); + genre = genre.filter(filterFunction); + //console.log(resp.items[i].id + " - ", genre); + db.collection(channel).update( + { id: resp.items[z].id }, + { + $set: { + tags: genre + } + }, + function(e, d) {} + ); + } + get_genres_youtube_recursive(arr, channel, i + ids.length, callback); + } else { + get_genres_youtube_recursive(arr, channel, i + ids.length, callback); + } } - var ids = []; - for(var y = i; y < arr.length; y++) { - if(ids.length >= 48) { - break; - } - ids.push(arr[y].id); - } - request({ - type: "GET", - url: "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id,topicDetails&key="+key+"&id=" + ids.join(","), - }, function(error, response, body) { - if(error) { - get_genres_youtube_recursive(arr, channel, i + ids.length, callback); - return; - } - var resp = JSON.parse(body); - if(!resp.hasOwnProperty("items")) { - get_genres_youtube_recursive(arr, channel, i + ids.length, callback); - return; - } - if(resp.items.length > 0) { - for(var z = 0; z < resp.items.length; z++) { - if(!resp.items[z].hasOwnProperty("topicDetails")) continue; - var genre = resp.items[z].topicDetails.topicCategories; - genre = genre.join(","); - genre = genre.replace(new RegExp("https://en.wikipedia.org/wiki/", "g"), ""); - genre = genre.replace(/_/g, " ").toLowerCase().split(","); - genre = genre.filter(filterFunction); - //console.log(resp.items[i].id + " - ", genre); - db.collection(channel).update({"id": resp.items[z].id}, { - $set: { - "tags": genre - } - }, function(e, d) { - }); - } - get_genres_youtube_recursive(arr, channel, i + ids.length, callback); - } else { - get_genres_youtube_recursive(arr, channel, i + ids.length, callback); - } - }); + ); } - function get_genres_youtube(ids, channel) { - request({ - type: "GET", - url: "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id,topicDetails&key="+key+"&id=" + ids, - }, function(error, response, body) { - if(error) { - return; + request( + { + type: "GET", + url: + "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id,topicDetails&key=" + + key + + "&id=" + + ids + }, + function(error, response, body) { + if (error) { + return; + } + var resp = JSON.parse(body); + if (!resp.hasOwnProperty("items")) { + return; + } + if (resp.items.length > 0) { + for (var i = 0; i < resp.items.length; i++) { + if (!resp.items[i].hasOwnProperty("topicDetails")) continue; + var genre = resp.items[i].topicDetails.topicCategories; + genre = genre.join(","); + genre = genre.replace( + new RegExp("https://en.wikipedia.org/wiki/", "g"), + "" + ); + genre = genre + .replace(/_/g, " ") + .toLowerCase() + .split(","); + genre = genre.filter(filterFunction); + //console.log(resp.items[i].id + " - ", genre); + db.collection(channel).update( + { id: resp.items[i].id }, + { + $set: { + tags: genre + } + }, + function(e, d) {} + ); } - var resp = JSON.parse(body); - if(!resp.hasOwnProperty("items")) { - return; - } - if(resp.items.length > 0) { - for(var i = 0; i < resp.items.length; i++) { - if(!resp.items[i].hasOwnProperty("topicDetails")) continue; - var genre = resp.items[i].topicDetails.topicCategories; - genre = genre.join(","); - genre = genre.replace(new RegExp("https://en.wikipedia.org/wiki/", "g"), ""); - genre = genre.replace(/_/g, " ").toLowerCase().split(","); - genre = genre.filter(filterFunction); - //console.log(resp.items[i].id + " - ", genre); - db.collection(channel).update({"id": resp.items[i].id}, { - $set: { - "tags": genre - } - }, function(e, d) {}); - } - } - }); + } + } + ); } function get_correct_info(song_generated, channel, broadcast, callback) { - //channel = channel.replace(/ /g,''); - request({ - type: "GET", - url: "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id,topicDetails&key="+key+"&id=" + song_generated.id, - - }, function(error, response, body) { - try { - var resp = JSON.parse(body); - if(resp.items.length == 1) { - var duration = parseInt(durationToSeconds(resp.items[0].contentDetails.duration)); - var title = resp.items[0].snippet.localized.title; - var genre = resp.items[0].topicDetails.topicCategories; - genre = genre.join(","); - genre = genre.replace(new RegExp("https://en.wikipedia.org/wiki/", "g"), ""); - genre = genre.replace(/_/g, " ").toLowerCase().split(","); - genre = genre.filter(filterFunction); - //console.log(genre + " - ", song_generated.id); - if(title != song_generated.title || duration < parseInt(song_generated.duration)) { - if(title != song_generated.title) { - song_generated.title = title; - } - if(duration < parseInt(song_generated.duration)) { - song_generated.duration = duration; - song_generated.start = 0; - song_generated.end = duration; - } - db.collection(channel).update({"id": song_generated.id}, { - $set: { - "duration": song_generated.duration, - "start": song_generated.start, - "end": song_generated.end, - "title": song_generated.title, - "tags": genre - } - }, function(err, docs) { - if(broadcast && docs.nModified == 1) { - song_generated.new_id = song_generated.id; - //if(song_generated.type == "video") - if(typeof(callback) == "function") { - callback(song_generated, true); - } else { - io.to(channel).emit("channel", {type: "changed_values", value: song_generated}); - } - } else { - if(typeof(callback) == "function") { - callback(song_generated, true); - } - } - }); - } else { - db.collection(channel).update({"id": song_generated.id}, { - $set: { - "tags": genre - } - }, function(e,d) { - if(typeof(callback) == "function") { - callback(song_generated, true); - } - }); + //channel = channel.replace(/ /g,''); + request( + { + type: "GET", + url: + "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id,topicDetails&key=" + + key + + "&id=" + + song_generated.id + }, + function(error, response, body) { + try { + var resp = JSON.parse(body); + if (resp.items.length == 1) { + var duration = parseInt( + durationToSeconds(resp.items[0].contentDetails.duration) + ); + var title = resp.items[0].snippet.localized.title; + var genre = resp.items[0].topicDetails.topicCategories; + genre = genre.join(","); + genre = genre.replace( + new RegExp("https://en.wikipedia.org/wiki/", "g"), + "" + ); + genre = genre + .replace(/_/g, " ") + .toLowerCase() + .split(","); + genre = genre.filter(filterFunction); + //console.log(genre + " - ", song_generated.id); + if ( + title != song_generated.title || + duration < parseInt(song_generated.duration) + ) { + if (title != song_generated.title) { + song_generated.title = title; + } + if (duration < parseInt(song_generated.duration)) { + song_generated.duration = duration; + song_generated.start = 0; + song_generated.end = duration; + } + db.collection(channel).update( + { id: song_generated.id }, + { + $set: { + duration: song_generated.duration, + start: song_generated.start, + end: song_generated.end, + title: song_generated.title, + tags: genre } - } else { - findSimilar(song_generated, channel, broadcast, callback) - } - } catch(e){ - if(typeof(callback) == "function") { - callback({}, false); - } + }, + function(err, docs) { + if (broadcast && docs.nModified == 1) { + song_generated.new_id = song_generated.id; + //if(song_generated.type == "video") + if (typeof callback == "function") { + callback(song_generated, true); + } else { + io.to(channel).emit("channel", { + type: "changed_values", + value: song_generated + }); + } + } else { + if (typeof callback == "function") { + callback(song_generated, true); + } + } + } + ); + } else { + db.collection(channel).update( + { id: song_generated.id }, + { + $set: { + tags: genre + } + }, + function(e, d) { + if (typeof callback == "function") { + callback(song_generated, true); + } + } + ); + } + } else { + findSimilar(song_generated, channel, broadcast, callback); } - }); + } catch (e) { + if (typeof callback == "function") { + callback({}, false); + } + } + } + ); } function check_error_video(msg, channel) { - if(!msg.hasOwnProperty("id") || !msg.hasOwnProperty("title") || - typeof(msg.id) != "string" || typeof(msg.title) != "string") { - var result = { - id: { - expected: "string", - got: msg.hasOwnProperty("id") ? typeof(msg.id) : undefined, - }, - title: { - expected: "string", - got: msg.hasOwnProperty("title") ? typeof(msg.title) : undefined, - }, - }; - return; - } - if(msg.source == "soundcloud") return; - //channel = channel.replace(/ /g,''); - request({ - type: "GET", - url: "https://www.googleapis.com/youtube/v3/videos?part=id&key="+key+"&id=" + msg.id, - - }, function(error, response, body) { - try { - var resp = JSON.parse(body); - if(resp.pageInfo.totalResults == 0) { - findSimilar(msg, channel, true, undefined); - } - } catch(e){ - console.log(msg.id, key, e, body); + if ( + !msg.hasOwnProperty("id") || + !msg.hasOwnProperty("title") || + typeof msg.id != "string" || + typeof msg.title != "string" + ) { + var result = { + id: { + expected: "string", + got: msg.hasOwnProperty("id") ? typeof msg.id : undefined + }, + title: { + expected: "string", + got: msg.hasOwnProperty("title") ? typeof msg.title : undefined + } + }; + return; + } + if (msg.source == "soundcloud") return; + //channel = channel.replace(/ /g,''); + request( + { + type: "GET", + url: + "https://www.googleapis.com/youtube/v3/videos?part=id&key=" + + key + + "&id=" + + msg.id + }, + function(error, response, body) { + try { + var resp = JSON.parse(body); + if (resp.pageInfo.totalResults == 0) { + findSimilar(msg, channel, true, undefined); } - }); + } catch (e) { + console.log(msg.id, key, e, body); + } + } + ); } function findSimilar(msg, channel, broadcast, callback) { - //channel = channel.replace(/ /g,''); - var yt_url = "https://www.googleapis.com/youtube/v3/search?key="+key+"&videoEmbeddable=true&part=id&type=video&order=viewCount&safeSearch=none&maxResults=5&q=" + encodeURIComponent(msg.title); - request({ - method: "GET", - url: yt_url, - }, function(error, response, body){ - var resp = JSON.parse(body); - if(resp.items.length > 0) { - var vid_url = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id&key="+key+"&id="; - for(var i = 0; i < resp.items.length; i++) { - vid_url += resp.items[i].id.videoId + ","; - } - request({ - type: "GET", - url: vid_url - }, function(error, response, body) { - var resp = JSON.parse(body); - var found = false; - var element = {}; - for(var i = 0; i < resp.items.length; i++) { - if(similarity(resp.items[i].snippet.localized.title, msg.title) > 0.75) { - found = true; - element = { - title: resp.items[i].snippet.localized.title, - duration: parseInt(durationToSeconds(resp.items[i].contentDetails.duration)), - id: resp.items[i].id, - start: 0, - end: parseInt(durationToSeconds(resp.items[i].contentDetails.duration)), - } - break; - } - } - if(found) { - db.collection(channel).update({"id": msg.id}, { - $set: element - }, function(err, docs) { - if(docs && docs.hasOwnProperty("nModified") && docs.nModified == 1 && broadcast) { - element.new_id = element.id; - element.id = msg.id; - if(!callback) { - io.to(channel).emit("channel", {type: "changed_values", value: element}); - } - } - if(typeof(callback) == "function") { - msg.title = element.title; - msg.id = element.id; - msg.duration = element.duration; - msg.start = element.start; - msg.end = element.end; - callback(msg, true); - } - }); - } else if(typeof(callback) == "function") { - callback({}, false); - } - }); + //channel = channel.replace(/ /g,''); + var yt_url = + "https://www.googleapis.com/youtube/v3/search?key=" + + key + + "&videoEmbeddable=true&part=id&type=video&order=viewCount&safeSearch=none&maxResults=5&q=" + + encodeURIComponent(msg.title); + request( + { + method: "GET", + url: yt_url + }, + function(error, response, body) { + var resp = JSON.parse(body); + if (resp.items.length > 0) { + var vid_url = + "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id&key=" + + key + + "&id="; + for (var i = 0; i < resp.items.length; i++) { + vid_url += resp.items[i].id.videoId + ","; } - }); + request( + { + type: "GET", + url: vid_url + }, + function(error, response, body) { + var resp = JSON.parse(body); + var found = false; + var element = {}; + for (var i = 0; i < resp.items.length; i++) { + if ( + similarity(resp.items[i].snippet.localized.title, msg.title) > + 0.75 + ) { + found = true; + element = { + title: resp.items[i].snippet.localized.title, + duration: parseInt( + durationToSeconds(resp.items[i].contentDetails.duration) + ), + id: resp.items[i].id, + start: 0, + end: parseInt( + durationToSeconds(resp.items[i].contentDetails.duration) + ) + }; + break; + } + } + if (found) { + db.collection(channel).update( + { id: msg.id }, + { + $set: element + }, + function(err, docs) { + if ( + docs && + docs.hasOwnProperty("nModified") && + docs.nModified == 1 && + broadcast + ) { + element.new_id = element.id; + element.id = msg.id; + if (!callback) { + io.to(channel).emit("channel", { + type: "changed_values", + value: element + }); + } + } + if (typeof callback == "function") { + msg.title = element.title; + msg.id = element.id; + msg.duration = element.duration; + msg.start = element.start; + msg.end = element.end; + callback(msg, true); + } + } + ); + } else if (typeof callback == "function") { + callback({}, false); + } + } + ); + } + } + ); } function similarity(s1, s2) { - var longer = s1; - var shorter = s2; - if (s1.length < s2.length) { - longer = s2; - shorter = s1; - } - var longerLength = longer.length; - if (longerLength == 0) { - return 1.0; - } - return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength); + var longer = s1; + var shorter = s2; + if (s1.length < s2.length) { + longer = s2; + shorter = s1; + } + var longerLength = longer.length; + if (longerLength == 0) { + return 1.0; + } + return ( + (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength) + ); } function editDistance(s1, s2) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); + s1 = s1.toLowerCase(); + s2 = s2.toLowerCase(); - var costs = new Array(); - for (var i = 0; i <= s1.length; i++) { - var lastValue = i; - for (var j = 0; j <= s2.length; j++) { - if (i == 0) - costs[j] = j; - else { - if (j > 0) { - var newValue = costs[j - 1]; - if (s1.charAt(i - 1) != s2.charAt(j - 1)) - newValue = Math.min(Math.min(newValue, lastValue), - costs[j]) + 1; - costs[j - 1] = lastValue; - lastValue = newValue; - } - } + var costs = new Array(); + for (var i = 0; i <= s1.length; i++) { + var lastValue = i; + for (var j = 0; j <= s2.length; j++) { + if (i == 0) costs[j] = j; + else { + if (j > 0) { + var newValue = costs[j - 1]; + if (s1.charAt(i - 1) != s2.charAt(j - 1)) + newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; + costs[j - 1] = lastValue; + lastValue = newValue; } - if (i > 0) - costs[s2.length] = lastValue; + } } - return costs[s2.length]; + if (i > 0) costs[s2.length] = lastValue; + } + return costs[s2.length]; } function durationToSeconds(duration) { - var matches = duration.match(time_regex); - hours= parseInt(matches[12])||0; - minutes= parseInt(matches[14])||0; - seconds= parseInt(matches[16])||0; - return hours*60*60+minutes*60+seconds; + var matches = duration.match(time_regex); + hours = parseInt(matches[12]) || 0; + minutes = parseInt(matches[14]) || 0; + seconds = parseInt(matches[16]) || 0; + return hours * 60 * 60 + minutes * 60 + seconds; } module.exports.check_if_error_or_blocked = check_if_error_or_blocked; diff --git a/server/handlers/suggestions.js b/server/handlers/suggestions.js index 180165f3..7896e88e 100644 --- a/server/handlers/suggestions.js +++ b/server/handlers/suggestions.js @@ -1,183 +1,284 @@ -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var Notifications = require(pathThumbnails + '/handlers/notifications.js'); -var crypto = require('crypto'); -var db = require(pathThumbnails + '/handlers/db.js'); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var Notifications = require(pathThumbnails + "/handlers/notifications.js"); +var crypto = require("crypto"); +var db = require(pathThumbnails + "/handlers/db.js"); function thumbnail(msg, coll, guid, offline, socket) { - if(msg.thumbnail != undefined && msg.channel && msg.channel != undefined && Functions.isUrl(msg.thumbnail)){ - if(typeof(msg.channel) != "string" || typeof(msg.thumbnail) != "string") - { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - }, - thumbnail: { - expected: "string", - got: msg.hasOwnProperty("thumbnail") ? typeof(msg.thumbnail) : undefined, - }, - adminpass: { - expected: "string", - got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, - }, - }; - socket.emit("update_required", result); - return; - } - //coll = coll.replace(/ /g,''); - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { - if(userpass != "" || msg.pass == undefined) { - msg.pass = userpass; - } else if(msg.hasOwnProperty("pass")){ - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - if(adminpass != "" || msg.adminpass == undefined) { - msg.adminpass = Functions.hash_pass(adminpass); - } else { - msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass),true)); - } - if(msg.thumbnail != "") { - msg.thumbnail = msg.thumbnail.replace(/^https?\:\/\//i, ""); - if(msg.thumbnail.substring(0,2) != "//") msg.thumbnail = "//" + msg.thumbnail; - } - var channel = msg.channel.toLowerCase(); - var hash = msg.adminpass; - db.collection(channel + "_settings").find({id: "config"}, function(err, docs){ - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) { - if(docs !== null && docs.length !== 0 && docs[0].adminpass !== "" && docs[0].adminpass == hash){ - db.collection("suggested_thumbnails").update({channel: channel}, {$set:{thumbnail: msg.thumbnail}}, {upsert:true}, function(err, docs){ - Notifications.requested_change("thumbnail", msg.thumbnail, channel); - socket.emit("toast", "suggested_thumbnail"); - }); - } - } else { - socket.emit("auth_required"); - } - }); - }); - } else { - socket.emit("toast", "thumbnail_denied"); + if ( + msg.thumbnail != undefined && + msg.channel && + msg.channel != undefined && + Functions.isUrl(msg.thumbnail) + ) { + if (typeof msg.channel != "string" || typeof msg.thumbnail != "string") { + var result = { + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined + }, + thumbnail: { + expected: "string", + got: msg.hasOwnProperty("thumbnail") + ? typeof msg.thumbnail + : undefined + }, + adminpass: { + expected: "string", + got: msg.hasOwnProperty("adminpass") + ? typeof msg.adminpass + : undefined + } + }; + socket.emit("update_required", result); + return; } + //coll = coll.replace(/ /g,''); + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass + ) { + if (userpass != "" || msg.pass == undefined) { + msg.pass = userpass; + } else if (msg.hasOwnProperty("pass")) { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + if (adminpass != "" || msg.adminpass == undefined) { + msg.adminpass = Functions.hash_pass(adminpass); + } else { + msg.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true) + ); + } + if (msg.thumbnail != "") { + msg.thumbnail = msg.thumbnail.replace(/^https?\:\/\//i, ""); + if (msg.thumbnail.substring(0, 2) != "//") + msg.thumbnail = "//" + msg.thumbnail; + } + var channel = msg.channel.toLowerCase(); + var hash = msg.adminpass; + db.collection(channel + "_settings").find({ id: "config" }, function( + err, + docs + ) { + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass)) + ) { + if ( + docs !== null && + docs.length !== 0 && + docs[0].adminpass !== "" && + docs[0].adminpass == hash + ) { + db.collection("suggested_thumbnails").update( + { channel: channel }, + { $set: { thumbnail: msg.thumbnail } }, + { upsert: true }, + function(err, docs) { + Notifications.requested_change( + "thumbnail", + msg.thumbnail, + channel + ); + socket.emit("toast", "suggested_thumbnail"); + } + ); + } + } else { + socket.emit("auth_required"); + } + }); + }); + } else { + socket.emit("toast", "thumbnail_denied"); + } } function description(msg, coll, guid, offline, socket) { - if(msg.description && msg.channel && msg.description.length < 100){ - if(typeof(msg.channel) != "string" || typeof(msg.description) != "string") { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - }, - description: { - expected: "string", - got: msg.hasOwnProperty("description") ? typeof(msg.description) : undefined, - }, - adminpass: { - expected: "string", - got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, - }, - }; - socket.emit("update_required", result); - return; - } - //coll = coll.replace(/ /g,''); - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) { - if(userpass != "" || msg.pass == undefined) { - msg.pass = userpass; - } else if(msg.hasOwnProperty("pass")) { - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - if(adminpass != "" || msg.adminpass == undefined) { - msg.adminpass = Functions.hash_pass(adminpass); - } else { - msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true)); - } - var channel = msg.channel.toLowerCase(); - var hash = msg.adminpass; - db.collection(channel + "_settings").find({id: "config"}, function(err, docs){ - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) { - if(docs !== null && docs.length !== 0 && docs[0].adminpass !== "" && docs[0].adminpass == hash){ - db.collection("suggested_descriptions").update({channel: channel}, {$set:{description: msg.description}}, {upsert:true}, function(err, docs){ - Notifications.requested_change("description", msg.description, channel); - socket.emit("toast", "suggested_description"); - }); - } - } else { - socket.emit("auth_required"); - } - }); - }); - } else { - socket.emit("toast", "description_denied"); + if (msg.description && msg.channel && msg.description.length < 100) { + if (typeof msg.channel != "string" || typeof msg.description != "string") { + var result = { + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined + }, + description: { + expected: "string", + got: msg.hasOwnProperty("description") + ? typeof msg.description + : undefined + }, + adminpass: { + expected: "string", + got: msg.hasOwnProperty("adminpass") + ? typeof msg.adminpass + : undefined + } + }; + socket.emit("update_required", result); + return; } + //coll = coll.replace(/ /g,''); + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass, + gotten + ) { + if (userpass != "" || msg.pass == undefined) { + msg.pass = userpass; + } else if (msg.hasOwnProperty("pass")) { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + if (adminpass != "" || msg.adminpass == undefined) { + msg.adminpass = Functions.hash_pass(adminpass); + } else { + msg.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true) + ); + } + var channel = msg.channel.toLowerCase(); + var hash = msg.adminpass; + db.collection(channel + "_settings").find({ id: "config" }, function( + err, + docs + ) { + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass)) + ) { + if ( + docs !== null && + docs.length !== 0 && + docs[0].adminpass !== "" && + docs[0].adminpass == hash + ) { + db.collection("suggested_descriptions").update( + { channel: channel }, + { $set: { description: msg.description } }, + { upsert: true }, + function(err, docs) { + Notifications.requested_change( + "description", + msg.description, + channel + ); + socket.emit("toast", "suggested_description"); + } + ); + } + } else { + socket.emit("auth_required"); + } + }); + }); + } else { + socket.emit("toast", "description_denied"); + } } - function rules(msg, coll, guid, offline, socket) { - if(msg.rules && msg.channel && msg.rules.length < 250){ - if(typeof(msg.channel) != "string" || typeof(msg.rules) != "string") { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - }, - rules: { - expected: "string", - got: msg.hasOwnProperty("rules") ? typeof(msg.rules) : undefined, - }, - adminpass: { - expected: "string", - got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, - }, - }; - socket.emit("update_required", result); - return; - } - //coll = coll.replace(/ /g,''); - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) { - if(userpass != "" || msg.pass == undefined) { - msg.pass = userpass; - } else if(msg.hasOwnProperty("pass")) { - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - if(adminpass != "" || msg.adminpass == undefined) { - msg.adminpass = Functions.hash_pass(adminpass); - } else { - msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true)); - } - var channel = msg.channel.toLowerCase(); - var hash = msg.adminpass; - db.collection(channel + "_settings").find({id: "config"}, function(err, docs){ - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) { - if(docs !== null && docs.length !== 0 && docs[0].adminpass !== "" && docs[0].adminpass == hash){ - db.collection("suggested_rules").update({channel: channel}, {$set:{rules: msg.rules}}, {upsert:true}, function(err, docs){ - Notifications.requested_change("rules", msg.rules, channel); - socket.emit("toast", "suggested_rules"); - }); - } - } else { - socket.emit("auth_required"); - } - }); - }); - } else { - socket.emit("toast", "rules_denied"); + if (msg.rules && msg.channel && msg.rules.length < 250) { + if (typeof msg.channel != "string" || typeof msg.rules != "string") { + var result = { + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined + }, + rules: { + expected: "string", + got: msg.hasOwnProperty("rules") ? typeof msg.rules : undefined + }, + adminpass: { + expected: "string", + got: msg.hasOwnProperty("adminpass") + ? typeof msg.adminpass + : undefined + } + }; + socket.emit("update_required", result); + return; } + //coll = coll.replace(/ /g,''); + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass, + gotten + ) { + if (userpass != "" || msg.pass == undefined) { + msg.pass = userpass; + } else if (msg.hasOwnProperty("pass")) { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + if (adminpass != "" || msg.adminpass == undefined) { + msg.adminpass = Functions.hash_pass(adminpass); + } else { + msg.adminpass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true) + ); + } + var channel = msg.channel.toLowerCase(); + var hash = msg.adminpass; + db.collection(channel + "_settings").find({ id: "config" }, function( + err, + docs + ) { + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass)) + ) { + if ( + docs !== null && + docs.length !== 0 && + docs[0].adminpass !== "" && + docs[0].adminpass == hash + ) { + db.collection("suggested_rules").update( + { channel: channel }, + { $set: { rules: msg.rules } }, + { upsert: true }, + function(err, docs) { + Notifications.requested_change("rules", msg.rules, channel); + socket.emit("toast", "suggested_rules"); + } + ); + } + } else { + socket.emit("auth_required"); + } + }); + }); + } else { + socket.emit("toast", "rules_denied"); + } } - module.exports.thumbnail = thumbnail; module.exports.description = description; module.exports.rules = rules; diff --git a/server/routing/admin/api.js b/server/routing/admin/api.js index c393134e..5b27ac0c 100644 --- a/server/routing/admin/api.js +++ b/server/routing/admin/api.js @@ -1,456 +1,625 @@ -var express = require('express'); +var express = require("express"); var router = express.Router(); -var path = require('path'); -var mongo_db_cred = require(path.join(__dirname, '../../config/mongo_config.js')); -var mongojs = require('mongojs'); +var path = require("path"); +try { + var mongo_db_cred = require(path.join( + __dirname, + "../../config/mongo_config.js" + )); +} catch (e) { + console.log( + "(!) Missing file - /config/mongo_config.js. Have a look at /config/mongo_config.example.js. The server won't run without this existing." + ); + process.exit(1); +} +var mongojs = require("mongojs"); var db = mongojs(mongo_db_cred.config); var token_db = mongojs("tokens"); -var uniqid = require('uniqid'); -var crypto = require('crypto'); +var uniqid = require("uniqid"); +var crypto = require("crypto"); var ObjectId = mongojs.ObjectId; -var sIO = require(path.join(__dirname, '../../apps/client.js')).socketIO; +var sIO = require(path.join(__dirname, "../../apps/client.js")).socketIO; var projects = require(pathThumbnails + "/handlers/aggregates.js"); router.use(function(req, res, next) { - next(); // make sure we go to the next routes and don't stop here + next(); // make sure we go to the next routes and don't stop here }); -router.route('/api/lists').get(function(req, res){ - if(req.isAuthenticated()){ - db.collection("frontpage_lists").find().sort({count: -1},function(err, docs){ - res.json(docs); +router.route("/api/lists").get(function(req, res) { + if (req.isAuthenticated()) { + db.collection("frontpage_lists") + .find() + .sort({ count: -1 }, function(err, docs) { + res.json(docs); }); - } else { - res.send(false); - } + } else { + res.send(false); + } }); -router.route('/api/thumbnails').get(function(req, res){ - if(req.isAuthenticated()){ - db.collection("suggested_thumbnails").find(function(err, docs){ - res.json(docs); - }); - } else { - res.send(false); - } +router.route("/api/thumbnails").get(function(req, res) { + if (req.isAuthenticated()) { + db.collection("suggested_thumbnails").find(function(err, docs) { + res.json(docs); + }); + } else { + res.send(false); + } }); -router.route('/api/descriptions').get(function(req, res){ - if(req.isAuthenticated()){ - db.collection("suggested_descriptions").find(function(err, docs){ - res.json(docs); - }); - } else { - res.send(false); - } +router.route("/api/descriptions").get(function(req, res) { + if (req.isAuthenticated()) { + db.collection("suggested_descriptions").find(function(err, docs) { + res.json(docs); + }); + } else { + res.send(false); + } }); -router.route('/api/rules').get(function(req, res){ - if(req.isAuthenticated()){ - db.collection("suggested_rules").find(function(err, docs){ - res.json(docs); - }); - } else { - res.send(false); - } +router.route("/api/rules").get(function(req, res) { + if (req.isAuthenticated()) { + db.collection("suggested_rules").find(function(err, docs) { + res.json(docs); + }); + } else { + res.send(false); + } }); -router.route('/api/approve_thumbnail').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("suggested_thumbnails").find({channel: channel}, function(err, docs){ - var thumbnail = docs[0].thumbnail; - db.collection("frontpage_lists").update({_id: channel}, {$set:{thumbnail: thumbnail}}, {upsert: true}, function(err, docs){ - db.collection(channel + "_settings").update({views:{$exists:true}}, {$set:{thumbnail: thumbnail}}, {upsert: true}, function(err, docs){ - db.collection("suggested_thumbnails").remove({channel: channel}, function(err, docs){ - db.collection(channel + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs[0].adminpass !== "") docs[0].adminpass = true; - if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true; - else docs[0].userpass = false; - sIO.to(channel).emit("conf", docs); - res.send(true); - }); - }); - }); - }); - }); - } else { - res.send(false); - } +router.route("/api/approve_thumbnail").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("suggested_thumbnails").find({ channel: channel }, function( + err, + docs + ) { + var thumbnail = docs[0].thumbnail; + db.collection("frontpage_lists").update( + { _id: channel }, + { $set: { thumbnail: thumbnail } }, + { upsert: true }, + function(err, docs) { + db.collection(channel + "_settings").update( + { views: { $exists: true } }, + { $set: { thumbnail: thumbnail } }, + { upsert: true }, + function(err, docs) { + db.collection("suggested_thumbnails").remove( + { channel: channel }, + function(err, docs) { + db.collection(channel + "_settings").aggregate( + [ + { + $match: { + id: "config" + } + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if (docs[0].adminpass !== "") docs[0].adminpass = true; + if ( + docs[0].hasOwnProperty("userpass") && + docs[0].userpass != "" + ) + docs[0].userpass = true; + else docs[0].userpass = false; + sIO.to(channel).emit("conf", docs); + res.send(true); + } + ); + } + ); + } + ); + } + ); + }); + } else { + res.send(false); + } }); -router.route('/api/deny_thumbnail').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("suggested_thumbnails").remove({channel: channel},function(err, docs){ - res.send(true); - }); - } else { - res.send(false); - } +router.route("/api/deny_thumbnail").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("suggested_thumbnails").remove({ channel: channel }, function( + err, + docs + ) { + res.send(true); + }); + } else { + res.send(false); + } }); - -router.route('/api/approve_rules').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("suggested_rules").find({channel: channel}, function(err, docs){ - var rules = docs[0].rules; - db.collection(channel + "_settings").update({views:{$exists:true}}, {$set:{rules: rules}}, {upsert: true}, function(err, docs){ - db.collection("suggested_rules").remove({channel: channel}, function(err, docs){ - db.collection(channel + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs[0].adminpass !== "") docs[0].adminpass = true; - if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true; - else docs[0].userpass = false; - sIO.to(channel).emit("conf", docs); - res.send(true); - }); - }); - }); - }); - } else { - res.send(false); - } -}); - -router.route('/api/deny_rules').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("suggested_rules").remove({channel: channel},function(err, docs){ - res.send(true); - }); - } else { - res.send(false); - } -}); - -router.route('/api/remove_rules').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection(channel + "_settings").update({views:{$exists:true}}, {$set:{rules: ""}}, function(err, docs){ - db.collection(channel + "_settings").aggregate([ - { - "$match": { +router.route("/api/approve_rules").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("suggested_rules").find({ channel: channel }, function( + err, + docs + ) { + var rules = docs[0].rules; + db.collection(channel + "_settings").update( + { views: { $exists: true } }, + { $set: { rules: rules } }, + { upsert: true }, + function(err, docs) { + db.collection("suggested_rules").remove( + { channel: channel }, + function(err, docs) { + db.collection(channel + "_settings").aggregate( + [ + { + $match: { id: "config" + } + }, + { + $project: projects.toShowConfig } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs[0].adminpass !== "") docs[0].adminpass = true; - if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true; + ], + function(err, docs) { + if (docs[0].adminpass !== "") docs[0].adminpass = true; + if ( + docs[0].hasOwnProperty("userpass") && + docs[0].userpass != "" + ) + docs[0].userpass = true; + else docs[0].userpass = false; + sIO.to(channel).emit("conf", docs); + res.send(true); + } + ); + } + ); + } + ); + }); + } else { + res.send(false); + } +}); + +router.route("/api/deny_rules").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("suggested_rules").remove({ channel: channel }, function( + err, + docs + ) { + res.send(true); + }); + } else { + res.send(false); + } +}); + +router.route("/api/remove_rules").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection(channel + "_settings").update( + { views: { $exists: true } }, + { $set: { rules: "" } }, + function(err, docs) { + db.collection(channel + "_settings").aggregate( + [ + { + $match: { + id: "config" + } + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if (docs[0].adminpass !== "") docs[0].adminpass = true; + if (docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") + docs[0].userpass = true; else docs[0].userpass = false; sIO.to(channel).emit("conf", docs); res.send(true); - }); - }); - } else { - res.send(false); - } -}); - -router.route('/api/approve_description').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("suggested_descriptions").find({channel: channel}, function(err, docs){ - var description = docs[0].description; - db.collection("frontpage_lists").update({_id: channel}, {$set:{description: description}}, {upsert: true}, function(err, docs){ - db.collection(channel + "_settings").update({views:{$exists:true}}, {$set:{description: description}}, function(err, docs){ - db.collection("suggested_descriptions").remove({channel: channel}, function(err, docs){ - db.collection(channel + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs[0].adminpass !== "") docs[0].adminpass = true; - if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true; - else docs[0].userpass = false; - sIO.to(channel).emit("conf", docs); - res.send(true); - }); - }); - }); - }); - }); - } else { - res.send(false); - } -}); - -router.route('/api/deny_description').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("suggested_descriptions").remove({channel: channel}, 1,function(err, docs){ - res.send(true); - }); - } else { - res.send(false); - } -}); - -router.route('/api/remove_thumbnail').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("frontpage_lists").update({_id: channel}, {$set:{thumbnail: ""}}, function(err, docs){ - db.collection(channel + "_settings").update({views:{$exists:true}}, {$set:{thumbnail: ""}}, function(err, docs){ - db.collection(channel + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs[0].adminpass !== "") docs[0].adminpass = true; - if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true; - else docs[0].userpass = false; - sIO.to(channel).emit("conf", docs); - res.send(true); - }); - }); - }); - } else { - res.send(false); - } -}); - -router.route('/api/remove_description').post(function(req, res){ - if(req.isAuthenticated()){ - var channel = req.body.channel; - db.collection("frontpage_lists").update({_id: channel}, {$set:{description: ""}}, function(err, docs){ - db.collection(channel + "_settings").update({views:{$exists:true}}, {$set:{description: ""}}, function(err, docs){ - db.collection(channel + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs[0].adminpass !== "") docs[0].adminpass = true; - if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true; - else docs[0].userpass = false; - sIO.to(channel).emit("conf", docs); - res.send(true); - }); - }); - }); - } else { - res.send(false); - } -}); - -router.route('/api/names').get(function(req, res) { - if(req.isAuthenticated()){ - db.collection("registered_users").find({_id: {$exists: true}}, {_id: 1, icon: 1}, function(err, docs) { - res.json(docs); - }) - } else { - res.send(false); - } -}); - -router.route('/api/names').post(function(req, res) { - if(req.isAuthenticated()) { - var icon = req.body.icon; - var name = req.body.name; - db.collection("registered_users").update({_id: name}, {$set: {icon: icon}}, function(err, docs) { - if(err) res.send(false); - else res.send(true); - }); - } else { - res.send(false); - } -}); - -router.route('/api/names').delete(function(req, res) { - if(req.isAuthenticated()) { - var name = req.body.name; - db.collection("registered_users").remove({_id: name}, function(err, docs) { - if(err) res.send(false); - else res.send(true); - }); - } else { - res.send(false); - } -}); - -router.route('/api/token').get(function(req, res){ - if(req.isAuthenticated()){ - token_db.collection("tokens").find(function(err, docs){ - if(docs.length == 1){ - res.json({token: docs[0].token}); - } else { - var id = new Buffer(makeid()).toString('base64'); - token_db.collection("tokens").insert({token: id}, function(err, docs){ - res.json({token: id}); - }); - } - }) - } else { - res.send(false); - } -}); - -router.route('/api/api_token').get(function(req, res) { - if(req.isAuthenticated()) { - token_db.collection("api_token").find({token: {$exists: true}}, function(err, all) { - res.json(all); - }); - } else { - res.sendStatus(403); - } -}); - -router.route('/api/api_token').delete(function(req, res){ - if(req.isAuthenticated()){ - var id = req.body.id; - token_db.collection("api_token").remove({_id: ObjectId(id)}, function(err, success) { - if(err) { - res.send("failed"); - return; - } - res.send("success"); - }) - } -}); - -router.route('/api/api_token').put(function(req, res){ - if(req.isAuthenticated()){ - var id = req.body.id; - var limit = req.body.limit; - if(limit < 0) { - res.sendStatus(500); - return; + } + ); } - token_db.collection("api_token").update({_id: ObjectId(id)}, {$set: {limit: limit}}, function(err, success) { - if(err) { - res.sendStatus(500); - return; - } - res.sendStatus(200); - }) - } + ); + } else { + res.send(false); + } }); -router.route('/api/api_token').post(function(req, res){ - if(req.isAuthenticated()){ - var name = req.body.name; - var id = crypto.createHash('sha256').update(uniqid()).digest('base64'); - token_db.collection("api_token").insert({name: name, token: id, usage: 0}, function(err, docs){ - token_db.collection("api_token").find({token: id}, function(err, d) { - res.json({token: id, _id: d[0]._id}); - }); +router.route("/api/approve_description").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("suggested_descriptions").find({ channel: channel }, function( + err, + docs + ) { + var description = docs[0].description; + db.collection("frontpage_lists").update( + { _id: channel }, + { $set: { description: description } }, + { upsert: true }, + function(err, docs) { + db.collection(channel + "_settings").update( + { views: { $exists: true } }, + { $set: { description: description } }, + function(err, docs) { + db.collection("suggested_descriptions").remove( + { channel: channel }, + function(err, docs) { + db.collection(channel + "_settings").aggregate( + [ + { + $match: { + id: "config" + } + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if (docs[0].adminpass !== "") docs[0].adminpass = true; + if ( + docs[0].hasOwnProperty("userpass") && + docs[0].userpass != "" + ) + docs[0].userpass = true; + else docs[0].userpass = false; + sIO.to(channel).emit("conf", docs); + res.send(true); + } + ); + } + ); + } + ); + } + ); + }); + } else { + res.send(false); + } +}); + +router.route("/api/deny_description").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("suggested_descriptions").remove( + { channel: channel }, + 1, + function(err, docs) { + res.send(true); + } + ); + } else { + res.send(false); + } +}); + +router.route("/api/remove_thumbnail").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("frontpage_lists").update( + { _id: channel }, + { $set: { thumbnail: "" } }, + function(err, docs) { + db.collection(channel + "_settings").update( + { views: { $exists: true } }, + { $set: { thumbnail: "" } }, + function(err, docs) { + db.collection(channel + "_settings").aggregate( + [ + { + $match: { + id: "config" + } + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if (docs[0].adminpass !== "") docs[0].adminpass = true; + if ( + docs[0].hasOwnProperty("userpass") && + docs[0].userpass != "" + ) + docs[0].userpass = true; + else docs[0].userpass = false; + sIO.to(channel).emit("conf", docs); + res.send(true); + } + ); + } + ); + } + ); + } else { + res.send(false); + } +}); + +router.route("/api/remove_description").post(function(req, res) { + if (req.isAuthenticated()) { + var channel = req.body.channel; + db.collection("frontpage_lists").update( + { _id: channel }, + { $set: { description: "" } }, + function(err, docs) { + db.collection(channel + "_settings").update( + { views: { $exists: true } }, + { $set: { description: "" } }, + function(err, docs) { + db.collection(channel + "_settings").aggregate( + [ + { + $match: { + id: "config" + } + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if (docs[0].adminpass !== "") docs[0].adminpass = true; + if ( + docs[0].hasOwnProperty("userpass") && + docs[0].userpass != "" + ) + docs[0].userpass = true; + else docs[0].userpass = false; + sIO.to(channel).emit("conf", docs); + res.send(true); + } + ); + } + ); + } + ); + } else { + res.send(false); + } +}); + +router.route("/api/names").get(function(req, res) { + if (req.isAuthenticated()) { + db.collection("registered_users").find( + { _id: { $exists: true } }, + { _id: 1, icon: 1 }, + function(err, docs) { + res.json(docs); + } + ); + } else { + res.send(false); + } +}); + +router.route("/api/names").post(function(req, res) { + if (req.isAuthenticated()) { + var icon = req.body.icon; + var name = req.body.name; + db.collection("registered_users").update( + { _id: name }, + { $set: { icon: icon } }, + function(err, docs) { + if (err) res.send(false); + else res.send(true); + } + ); + } else { + res.send(false); + } +}); + +router.route("/api/names").delete(function(req, res) { + if (req.isAuthenticated()) { + var name = req.body.name; + db.collection("registered_users").remove({ _id: name }, function( + err, + docs + ) { + if (err) res.send(false); + else res.send(true); + }); + } else { + res.send(false); + } +}); + +router.route("/api/token").get(function(req, res) { + if (req.isAuthenticated()) { + token_db.collection("tokens").find(function(err, docs) { + if (docs.length == 1) { + res.json({ token: docs[0].token }); + } else { + var id = new Buffer(makeid()).toString("base64"); + token_db + .collection("tokens") + .insert({ token: id }, function(err, docs) { + res.json({ token: id }); + }); + } + }); + } else { + res.send(false); + } +}); + +router.route("/api/api_token").get(function(req, res) { + if (req.isAuthenticated()) { + token_db + .collection("api_token") + .find({ token: { $exists: true } }, function(err, all) { + res.json(all); }); - } else { - res.send(false); - } + } else { + res.sendStatus(403); + } }); -router.route('/api/delete').post(function(req, res){ - if(req.isAuthenticated()){ - var list = req.body._id; - db.collection(list).drop(function(err, docs){ - db.collection(list + "_settings").drop(function(err, docs){ - db.collection("frontpage_lists").remove({_id: list}, function(err, docs){ - res.send(true); - }) - }); +router.route("/api/api_token").delete(function(req, res) { + if (req.isAuthenticated()) { + var id = req.body.id; + token_db + .collection("api_token") + .remove({ _id: ObjectId(id) }, function(err, success) { + if (err) { + res.send("failed"); + return; + } + res.send("success"); }); - } else { - res.send(false); - } + } }); -router.route('/api/remove_token').get(function(req, res){ - if(req.isAuthenticated()){ - token_db.collection("tokens").find(function(err, docs){ - if(docs.length == 1){ - token_db.collection("tokens").remove({token: docs[0].token}, function(err, docs){ - res.send(true); - }) - } else { - res.send(false); - } - }) - } else { - res.send(false); - } +router.route("/api/api_token").put(function(req, res) { + if (req.isAuthenticated()) { + var id = req.body.id; + var limit = req.body.limit; + if (limit < 0) { + res.sendStatus(500); + return; + } + token_db + .collection("api_token") + .update({ _id: ObjectId(id) }, { $set: { limit: limit } }, function( + err, + success + ) { + if (err) { + res.sendStatus(500); + return; + } + res.sendStatus(200); + }); + } }); -router.route('/api/pinned').post(function(req, res){ - if(req.isAuthenticated()){ - var to_pin = req.body._id; - db.collection("frontpage_lists").update({pinned:1}, {$set:{pinned:0}}, function(err, resp){ - db.collection("frontpage_lists").update({_id:to_pin}, {$set:{pinned:1}}, function(err, resp){ - res.send(true); - }); +router.route("/api/api_token").post(function(req, res) { + if (req.isAuthenticated()) { + var name = req.body.name; + var id = crypto + .createHash("sha256") + .update(uniqid()) + .digest("base64"); + token_db + .collection("api_token") + .insert({ name: name, token: id, usage: 0 }, function(err, docs) { + token_db.collection("api_token").find({ token: id }, function(err, d) { + res.json({ token: id, _id: d[0]._id }); }); - } else { - res.send(false); - } -}); - -router.route('/api/admin').post(function(req, res){ - if(req.isAuthenticated()){ - var to_remove = req.body._id; - db.collection(to_remove + "_settings").update({views: {$exists: true}}, {$set:{adminpass: ""}}, function(err, docs){ - res.send(true); }); - } else { - res.send(false); - } + } else { + res.send(false); + } }); -router.route('/api/userpass').post(function(req, res){ - if(req.isAuthenticated()){ - var to_remove = req.body._id; - db.collection(to_remove + "_settings").update({views: {$exists: true}}, {$set:{userpass: ""}}, function(err, docs){ - res.send(true); +router.route("/api/delete").post(function(req, res) { + if (req.isAuthenticated()) { + var list = req.body._id; + db.collection(list).drop(function(err, docs) { + db.collection(list + "_settings").drop(function(err, docs) { + db.collection("frontpage_lists").remove({ _id: list }, function( + err, + docs + ) { + res.send(true); + }); }); - } else { - res.send(false); - } + }); + } else { + res.send(false); + } }); -function makeid() -{ - var text = ""; - var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; +router.route("/api/remove_token").get(function(req, res) { + if (req.isAuthenticated()) { + token_db.collection("tokens").find(function(err, docs) { + if (docs.length == 1) { + token_db + .collection("tokens") + .remove({ token: docs[0].token }, function(err, docs) { + res.send(true); + }); + } else { + res.send(false); + } + }); + } else { + res.send(false); + } +}); - for( var i=0; i < 20; i++ ) - text += possible.charAt(Math.floor(Math.random() * possible.length)); +router.route("/api/pinned").post(function(req, res) { + if (req.isAuthenticated()) { + var to_pin = req.body._id; + db.collection("frontpage_lists").update( + { pinned: 1 }, + { $set: { pinned: 0 } }, + function(err, resp) { + db.collection("frontpage_lists").update( + { _id: to_pin }, + { $set: { pinned: 1 } }, + function(err, resp) { + res.send(true); + } + ); + } + ); + } else { + res.send(false); + } +}); - return text; +router.route("/api/admin").post(function(req, res) { + if (req.isAuthenticated()) { + var to_remove = req.body._id; + db.collection(to_remove + "_settings").update( + { views: { $exists: true } }, + { $set: { adminpass: "" } }, + function(err, docs) { + res.send(true); + } + ); + } else { + res.send(false); + } +}); + +router.route("/api/userpass").post(function(req, res) { + if (req.isAuthenticated()) { + var to_remove = req.body._id; + db.collection(to_remove + "_settings").update( + { views: { $exists: true } }, + { $set: { userpass: "" } }, + function(err, docs) { + res.send(true); + } + ); + } else { + res.send(false); + } +}); + +function makeid() { + var text = ""; + var possible = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + for (var i = 0; i < 20; i++) + text += possible.charAt(Math.floor(Math.random() * possible.length)); + + return text; } - module.exports = router; diff --git a/server/routing/client/api.js b/server/routing/client/api.js index ceb8d0da..5a59d129 100644 --- a/server/routing/client/api.js +++ b/server/routing/client/api.js @@ -13,7 +13,7 @@ try { } catch (e) { allowed_key = ["***"]; console.log( - "Allowed API-key for skipping songs from API has not been configured, so all keys are allowed by default (!). Have a look at config/allowed_api.example.js" + "(!) Missing file - /config/allowed_api.js Have a look at /config/allowed_api.example.js." ); } var crypto = require("crypto"); diff --git a/server/routing/client/icons_routing.js b/server/routing/client/icons_routing.js index 113f12a5..f2e1e1b9 100644 --- a/server/routing/client/icons_routing.js +++ b/server/routing/client/icons_routing.js @@ -1,24 +1,33 @@ -var express = require('express'); -const path = require('path'); +var express = require("express"); +const path = require("path"); var router = express.Router(); router.use(function(req, res, next) { - next(); // make sure we go to the next routes and don't stop here + next(); // make sure we go to the next routes and don't stop here }); -router.route('/favicon.ico').get(function(req, res, next) { - res.sendFile(path.join(pathThumbnails, '/public/assets/images/favicon.ico')); +router.route("/favicon.ico").get(function(req, res, next) { + res.sendFile(path.join(pathThumbnails, "/public/assets/images/favicon.ico")); }); -router.route('/browserconfig.xml').get(function(req, res, next) { - res.sendFile(path.join(pathThumbnails, '/public/assets/images/browserconfig.xml')); +router.route("/browserconfig.xml").get(function(req, res, next) { + res.sendFile( + path.join(pathThumbnails, "/public/assets/images/browserconfig.xml") + ); }); -router.route('/apple-touch-icon.png').get(function(req, res, next) { - res.sendFile(path.join(pathThumbnails, '/public/assets/images/apple-touch-icon.png')); +router.route("/apple-touch-icon.png").get(function(req, res, next) { + res.sendFile( + path.join(pathThumbnails, "/public/assets/images/apple-touch-icon.png") + ); }); -router.route('/apple-touch-icon-precomposed.png').get(function(req, res, next) { - res.sendFile(path.join(pathThumbnails, '/public/assets/images/apple-touch-icon-precomposed.png')); +router.route("/apple-touch-icon-precomposed.png").get(function(req, res, next) { + res.sendFile( + path.join( + pathThumbnails, + "/public/assets/images/apple-touch-icon-precomposed.png" + ) + ); }); module.exports = router; diff --git a/server/routing/client/router.js b/server/routing/client/router.js index 45a563e0..75bc3ad3 100644 --- a/server/routing/client/router.js +++ b/server/routing/client/router.js @@ -1,248 +1,270 @@ -var express = require('express'); +var express = require("express"); var router = express.Router(); -var path = require('path'); -var year = new Date().getYear()+1900; -var path = require('path'); +var path = require("path"); +var year = new Date().getYear() + 1900; +var path = require("path"); var analytics = "xx"; var google = {}; var adsense = "xx"; var adds = false; -var mongojs = require('mongojs'); +var mongojs = require("mongojs"); var token_db = mongojs("tokens"); -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var Frontpage = require(pathThumbnails + '/handlers/frontpage.js'); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var Frontpage = require(pathThumbnails + "/handlers/frontpage.js"); -var db = require(pathThumbnails + '/handlers/db.js'); +var db = require(pathThumbnails + "/handlers/db.js"); //var db = require(pathThumbnails + '/handlers/db.js'); try { - google = require(path.join(path.join(__dirname, '../../config/'), 'google.js')); - analytics = google.analytics; - adsense = google.adsense; -} catch(e) { - console.log("No analytics-id found"); + google = require(path.join( + path.join(__dirname, "../../config/"), + "google.js" + )); + analytics = google.analytics; + adsense = google.adsense; +} catch (e) { + console.log("No analytics-id found"); } try { - var Recaptcha = require('express-recaptcha'); - var recaptcha_config = require(path.join(path.join(__dirname, '../../config/'), 'recaptcha.js')); - var RECAPTCHA_SITE_KEY = recaptcha_config.site; - var RECAPTCHA_SECRET_KEY = recaptcha_config.key; - var recaptcha = new Recaptcha(RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY); -} catch(e) { - console.log("Error - missing file"); - console.log("Seems you forgot to create the file recaptcha.js in /server/config/. Have a look at recaptcha.example.js."); - var recaptcha = { - middleware: { - render: (req, res, next) => { - res.recaptcha = "" - next() - } - } + var Recaptcha = require("express-recaptcha"); + var recaptcha_config = require(path.join( + path.join(__dirname, "../../config/"), + "recaptcha.js" + )); + var RECAPTCHA_SITE_KEY = recaptcha_config.site; + var RECAPTCHA_SECRET_KEY = recaptcha_config.key; + var recaptcha = new Recaptcha(RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY); +} catch (e) { + console.log( + "(!) Missing file - /config/recaptcha.js Have a look at /config/recaptcha.example.js." + ); + var recaptcha = { + middleware: { + render: (req, res, next) => { + res.recaptcha = ""; + next(); + } } + }; } router.use(recaptcha.middleware.render, function(req, res, next) { - next(); // make sure we go to the next routes and don't stop here + next(); // make sure we go to the next routes and don't stop here }); -router.route('/:channel_name').get(function(req, res, next){ - channel(req, res, next); +router.route("/:channel_name").get(function(req, res, next) { + channel(req, res, next); }); -router.route('/r/:base64data').get(function(req, res, next){ - var channelToRedirect = Buffer.from(req.params.base64data, 'base64'); - res.redirect('/' + channelToRedirect); +router.route("/r/:base64data").get(function(req, res, next) { + var channelToRedirect = Buffer.from(req.params.base64data, "base64"); + res.redirect("/" + channelToRedirect); }); -router.route('/').get(function(req, res, next){ - root(req, res, next); +router.route("/").get(function(req, res, next) { + root(req, res, next); }); -router.route('/').post(function(req, res, next){ - root(req, res, next); +router.route("/").post(function(req, res, next) { + root(req, res, next); }); -router.route('/api/embed').get(function(req, res, next) { - var data = { - year: year, - type: "video", - javascript_file: "embed.min.js", - captcha: res.recaptcha, - analytics: analytics, - stylesheet: "embed.css", - embed: true, - og_image: "https://zoff.me/assets/images/small-square.jpg", - } - res.render('layouts/client/embed', data); +router.route("/api/embed").get(function(req, res, next) { + var data = { + year: year, + type: "video", + javascript_file: "embed.min.js", + captcha: res.recaptcha, + analytics: analytics, + stylesheet: "embed.css", + embed: true, + og_image: "https://zoff.me/assets/images/small-square.jpg" + }; + res.render("layouts/client/embed", data); }); -router.route('/api/oauth').get(function(req, res, next) { - res.sendFile(path.join(pathThumbnails, '/public/assets/html/callback.html')); +router.route("/api/oauth").get(function(req, res, next) { + res.sendFile(path.join(pathThumbnails, "/public/assets/html/callback.html")); }); -router.route('/api/apply').get(function(req, res, next) { - var data = { - year: year, - javascript_file: "token.min.js", - captcha: res.recaptcha, - analytics: analytics, - adsense: adsense, - adds: adds, - type: "website", - activated: false, - id: "", - correct: false, - stylesheet: "style.css", - embed: false, - og_image: "https://zoff.me/assets/images/small-square.jpg", - } - res.render('layouts/client/token', data); +router.route("/api/apply").get(function(req, res, next) { + var data = { + year: year, + javascript_file: "token.min.js", + captcha: res.recaptcha, + analytics: analytics, + adsense: adsense, + adds: adds, + type: "website", + activated: false, + id: "", + correct: false, + stylesheet: "style.css", + embed: false, + og_image: "https://zoff.me/assets/images/small-square.jpg" + }; + res.render("layouts/client/token", data); }); -router.route('/api/apply/:id').get(function(req, res) { - var id = req.params.id; - token_db.collection('api_links').find({id: id}, function(err, result) { - if(result.length == 1) { - token_db.collection('api_links').remove({id: id}, function(e,d) { - token_db.collection('api_token').update({token: result[0].token}, {$set: {active: true}}, function(e,d) { - var data = { - year: year, - javascript_file: "token.min.js", - captcha: res.recaptcha, - analytics: analytics, - adsense: adsense, - adds: adds, - activated: true, - type: "website", - token: result[0].token, - correct: true, - stylesheet: "style.css", - embed: false, - og_image: "https://zoff.me/assets/images/small-square.jpg", - } - res.render('layouts/client/token', data); - }); - }); - } else { - var data = { +router.route("/api/apply/:id").get(function(req, res) { + var id = req.params.id; + token_db.collection("api_links").find({ id: id }, function(err, result) { + if (result.length == 1) { + token_db.collection("api_links").remove({ id: id }, function(e, d) { + token_db + .collection("api_token") + .update( + { token: result[0].token }, + { $set: { active: true } }, + function(e, d) { + var data = { year: year, javascript_file: "token.min.js", captcha: res.recaptcha, analytics: analytics, adsense: adsense, adds: adds, - activated: false, - token:"", + activated: true, type: "website", - correct: false, + token: result[0].token, + correct: true, stylesheet: "style.css", embed: false, - og_image: "https://zoff.me/assets/images/small-square.jpg", + og_image: "https://zoff.me/assets/images/small-square.jpg" + }; + res.render("layouts/client/token", data); } - res.render('layouts/client/token', data); - } - }); + ); + }); + } else { + var data = { + year: year, + javascript_file: "token.min.js", + captcha: res.recaptcha, + analytics: analytics, + adsense: adsense, + adds: adds, + activated: false, + token: "", + type: "website", + correct: false, + stylesheet: "style.css", + embed: false, + og_image: "https://zoff.me/assets/images/small-square.jpg" + }; + res.render("layouts/client/token", data); + } + }); }); - function root(req, res, next) { - try{ - var url = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : req.headers.host.split(":")[0]; - var subdomain = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'].split(".") : req.headers.host.split(":")[0].split("."); - /*if(url != "zoff.me" && url != "admin.localhost" && url != "admin.zoff.me" && url != "remote.zoff.me" && url != "fb.zoff.me" && url != "remote.localhost" && url != "localhost") { + try { + var url = req.headers["x-forwarded-host"] + ? req.headers["x-forwarded-host"] + : req.headers.host.split(":")[0]; + var subdomain = req.headers["x-forwarded-host"] + ? req.headers["x-forwarded-host"].split(".") + : req.headers.host.split(":")[0].split("."); + /*if(url != "zoff.me" && url != "admin.localhost" && url != "admin.zoff.me" && url != "remote.zoff.me" && url != "fb.zoff.me" && url != "remote.localhost" && url != "localhost") { res.redirect("https://zoff.me"); return; }*/ - if(subdomain[0] == "remote") { - var data = { - year: year, - javascript_file: "remote.min.js", - captcha: res.recaptcha, - adsense: adsense, - adds: adds, - analytics: analytics, - type: "website", - stylesheet: "style.css", - embed: false, - client: false, - og_image: "https://zoff.me/assets/images/small-square.jpg", - } - res.render('layouts/client/remote', data); - } else if(subdomain[0] == "www") { - res.redirect("https://zoff.me"); - } else { - var data = { - year: year, - javascript_file: "main.min.js", - captcha: res.recaptcha, - adsense: adsense, - adds: adds, - analytics: analytics, - stylesheet: "style.css", - type: "website", - embed: false, - client: false, - og_image: "https://zoff.me/assets/images/small-square.jpg", - channels: [], - } - if(subdomain[0] == "client") { - data.client = true; - } - Frontpage.get_frontpage_lists(function(err, docs){ - db.collection("connected_users").find({"_id": "total_users"}, function(err, tot) { - if(docs.length > 0) { - data.channels_exist = true; - data.channels = docs.slice(0, 12); - data.channel_list = JSON.stringify(docs); - } else { - data.channels_exist = false; - data.channels = []; - data.channel_list = []; - } - data.viewers = tot[0].total_users.length; - res.render('layouts/client/frontpage', data); - }); - }); - - } - } catch(e) { - console.log(e); - //res.redirect("https://zoff.me"); + if (subdomain[0] == "remote") { + var data = { + year: year, + javascript_file: "remote.min.js", + captcha: res.recaptcha, + adsense: adsense, + adds: adds, + analytics: analytics, + type: "website", + stylesheet: "style.css", + embed: false, + client: false, + og_image: "https://zoff.me/assets/images/small-square.jpg" + }; + res.render("layouts/client/remote", data); + } else if (subdomain[0] == "www") { + res.redirect("https://zoff.me"); + } else { + var data = { + year: year, + javascript_file: "main.min.js", + captcha: res.recaptcha, + adsense: adsense, + adds: adds, + analytics: analytics, + stylesheet: "style.css", + type: "website", + embed: false, + client: false, + og_image: "https://zoff.me/assets/images/small-square.jpg", + channels: [] + }; + if (subdomain[0] == "client") { + data.client = true; + } + Frontpage.get_frontpage_lists(function(err, docs) { + db.collection("connected_users").find({ _id: "total_users" }, function( + err, + tot + ) { + if (docs.length > 0) { + data.channels_exist = true; + data.channels = docs.slice(0, 12); + data.channel_list = JSON.stringify(docs); + } else { + data.channels_exist = false; + data.channels = []; + data.channel_list = []; + } + data.viewers = tot[0].total_users.length; + res.render("layouts/client/frontpage", data); + }); + }); } + } catch (e) { + console.log(e); + //res.redirect("https://zoff.me"); + } } function channel(req, res, next) { - try{ - var url = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : req.headers.host.split(":")[0]; - var subdomain = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'].split(".") : req.headers.host.split(":")[0].split("."); - /*if(url != "zoff.me" && url != "admin.localhost" && url != "admin.zoff.me" && url != "remote.zoff.me" && url != "fb.zoff.me" && url != "remote.localhost" && url != "localhost") { + try { + var url = req.headers["x-forwarded-host"] + ? req.headers["x-forwarded-host"] + : req.headers.host.split(":")[0]; + var subdomain = req.headers["x-forwarded-host"] + ? req.headers["x-forwarded-host"].split(".") + : req.headers.host.split(":")[0].split("."); + /*if(url != "zoff.me" && url != "admin.localhost" && url != "admin.zoff.me" && url != "remote.zoff.me" && url != "fb.zoff.me" && url != "remote.localhost" && url != "localhost") { res.redirect("https://zoff.me"); return; }*/ - if(subdomain[0] == "remote") { - var data = { - year: year, - javascript_file: "remote.min.js", - captcha: res.recaptcha, - adsense: adsense, - adds: adds, - analytics: analytics, - type: "website", - stylesheet: "style.css", - embed: false, - client: false, - og_image: "https://zoff.me/assets/images/small-square.jpg", - } - res.render('layouts/client/remote', data); - } else if(subdomain.length >= 2 && subdomain[0] == "www") { - res.redirect("https://zoff.me"); - } else { - if(req.params.channel_name == "o_callback") { - res.redirect("/api/oauth"); - //res.sendFile(path.join(pathThumbnails, '/public/assets/html/callback.html')); - } else { - /*db.collection("frontpage_lists").find({"_id": Functions.encodeChannelName(req.params.channel_name)}, function(err, docs) { + if (subdomain[0] == "remote") { + var data = { + year: year, + javascript_file: "remote.min.js", + captcha: res.recaptcha, + adsense: adsense, + adds: adds, + analytics: analytics, + type: "website", + stylesheet: "style.css", + embed: false, + client: false, + og_image: "https://zoff.me/assets/images/small-square.jpg" + }; + res.render("layouts/client/remote", data); + } else if (subdomain.length >= 2 && subdomain[0] == "www") { + res.redirect("https://zoff.me"); + } else { + if (req.params.channel_name == "o_callback") { + res.redirect("/api/oauth"); + //res.sendFile(path.join(pathThumbnails, '/public/assets/html/callback.html')); + } else { + /*db.collection("frontpage_lists").find({"_id": Functions.encodeChannelName(req.params.channel_name)}, function(err, docs) { console.log(docs); var og_image = "https://zoff.me/assets/images/small-square.jpg"; if(docs.length == 1) { @@ -253,39 +275,39 @@ function channel(req, res, next) { og_image = "https://img.youtube.com/vi/" + docs[0].id + "/hqdefault.jpg"; } }*/ - var data = { - title: "404: File Not Found", - //list_name: capitalizeFirstLetter(Functions.decodeChannelName(req.params.channel_name)), - list_name: capitalizeFirstLetter(req.params.channel_name), - year: year, - javascript_file: "main.min.js", - captcha: res.recaptcha, - adsense: adsense, - adds: adds, - analytics: analytics, - type: "video", - stylesheet: "style.css", - embed: false, - client:false, - og_image: "https://zoff.me/assets/images/small-square.jpg" - } - if(subdomain[0] == "client") { - data.client = true; - } - if(req.params.channel_name == "404") { - res.status(404); - } - res.render('layouts/client/channel', data); - //}); - } + var data = { + title: "404: File Not Found", + //list_name: capitalizeFirstLetter(Functions.decodeChannelName(req.params.channel_name)), + list_name: capitalizeFirstLetter(req.params.channel_name), + year: year, + javascript_file: "main.min.js", + captcha: res.recaptcha, + adsense: adsense, + adds: adds, + analytics: analytics, + type: "video", + stylesheet: "style.css", + embed: false, + client: false, + og_image: "https://zoff.me/assets/images/small-square.jpg" + }; + if (subdomain[0] == "client") { + data.client = true; } - } catch(e) { - res.redirect("https://zoff.me"); + if (req.params.channel_name == "404") { + res.status(404); + } + res.render("layouts/client/channel", data); + //}); + } } + } catch (e) { + res.redirect("https://zoff.me"); + } } function capitalizeFirstLetter(string) { - return string.charAt(0).toUpperCase() + string.slice(1); + return string.charAt(0).toUpperCase() + string.slice(1); } module.exports = router;