Prettified som more files and fixed some logging of missing files so they are more similar in fashion

This commit is contained in:
Kasper Rynning-Tønnesen
2019-07-26 08:46:03 +02:00
parent 6369c55252
commit 6ed67ffee6
18 changed files with 5629 additions and 3697 deletions

View File

@@ -1,146 +1,155 @@
var cluster = require('cluster'), var cluster = require("cluster"),
net = require('net'), net = require("net"),
path = require('path'), path = require("path"),
//publicPath = path.join(__dirname, 'public'), //publicPath = path.join(__dirname, 'public'),
http = require('http'), http = require("http"),
port = 8080, port = 8080,
//farmhash = require('farmhash'), //farmhash = require('farmhash'),
uniqid = require('uniqid'), uniqid = require("uniqid"),
num_processes = require('os').cpus().length; num_processes = require("os").cpus().length;
publicPath = path.join(__dirname, 'public'); publicPath = path.join(__dirname, "public");
pathThumbnails = __dirname; pathThumbnails = __dirname;
try { try {
var redis = require("redis"); var redis = require("redis");
var client = redis.createClient({host: "localhost", port: 6379}); var client = redis.createClient({ host: "localhost", port: 6379 });
client.on("error", function (err) { 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"); console.log("Couldn't connect to redis-server, assuming non-clustered run");
num_processes = 1; num_processes = 1;
startSingle(false, false); 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) { function startClustered(redis_enabled) {
//Found https://stackoverflow.com/questions/40885592/use-node-js-cluster-with-socket-io-chat-application //Found https://stackoverflow.com/questions/40885592/use-node-js-cluster-with-socket-io-chat-application
if (cluster.isMaster) { if (cluster.isMaster) {
var workers = []; var workers = [];
var spawn = function(i) { var spawn = function(i) {
workers[i] = cluster.fork(); workers[i] = cluster.fork();
workers[i].on('exit', function(code, signal) { workers[i].on("exit", function(code, signal) {
if(code == 1) { if (code == 1) {
process.exit(1); process.exit(1);
return; return;
}
console.log('respawning worker', i);
spawn(i);
});
};
for (var i = 0; i < num_processes; i++) {
spawn(i);
} }
console.log("respawning worker", i);
spawn(i);
});
};
var worker_index = function(ip, len) { for (var i = 0; i < num_processes; i++) {
//console.log(ip); spawn(i);
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);
} }
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) { function startSingle(clustered, redis_enabled) {
var server; var server;
var client = require('./apps/client.js'); 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 { try {
var cert_config = require(path.join(path.join(__dirname, 'config'), 'cert_config.js')); socketIO.adapter(redis({ host: "localhost", port: 6379 }));
var fs = require('fs'); } catch (e) {
var privateKey = fs.readFileSync(cert_config.privateKey).toString(); console.log("No redis-server to connect to..");
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.listen(server);
if(clustered) { process.on("message", function(message, connection) {
server.listen(onListen); if (message !== "sticky-session:connection") {
} else { return;
server.listen(port, onListen);
} }
server.emit("connection", connection);
var socketIO = client.socketIO; connection.resume();
});
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();
});
} }
function onListen() { function onListen() {
console.log("Started with pid [" + process.pid + "]"); console.log("Started with pid [" + process.pid + "]");
} }
function routingFunction(req, res, next) { function routingFunction(req, res, next) {
var client = require('./apps/client.js'); var client = require("./apps/client.js");
var admin = require('./apps/admin.js'); var admin = require("./apps/admin.js");
try { try {
var url = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : req.headers.host.split(":")[0]; var url = req.headers["x-forwarded-host"]
var subdomain = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'].split(".") : req.headers.host.split(":")[0].split("."); ? 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") { if (subdomain.length > 1 && subdomain[0] == "admin") {
admin(req, res, next); admin(req, res, next);
} else { } else {
client(req, res, next); 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
} }
} 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
}
} }

View File

@@ -1,252 +1,268 @@
var express = require('express'); var express = require("express");
var app = express(); var app = express();
const path = require('path'); const path = require("path");
const publicPath = path.join(__dirname + "", '../public'); const publicPath = path.join(__dirname + "", "../public");
var exphbs = require('express-handlebars'); var exphbs = require("express-handlebars");
var hbs = exphbs.create({ var hbs = exphbs.create({
defaultLayout: publicPath + '/layouts/admin/main', defaultLayout: publicPath + "/layouts/admin/main",
layoutsDir: publicPath + '/layouts', layoutsDir: publicPath + "/layouts",
partialsDir: publicPath + '/partials' partialsDir: publicPath + "/partials"
}); });
var passport = require('passport'); var passport = require("passport");
var mpromise = require('mpromise'); var mpromise = require("mpromise");
var LocalStrategy = require('passport-local').Strategy; var LocalStrategy = require("passport-local").Strategy;
var mongoose = require('mongoose'); var mongoose = require("mongoose");
var mongo_db_cred = require(pathThumbnails + '/config/mongo_config.js'); var mongo_db_cred = require(pathThumbnails + "/config/mongo_config.js");
var mongojs = require('mongojs'); var mongojs = require("mongojs");
var db = mongojs(mongo_db_cred.config); var db = mongojs(mongo_db_cred.config);
var token_db = mongojs("tokens"); var token_db = mongojs("tokens");
var bodyParser = require('body-parser'); var bodyParser = require("body-parser");
var session = require('express-session'); var session = require("express-session");
var MongoStore = require('connect-mongo')(session); var MongoStore = require("connect-mongo")(session);
var api = require(pathThumbnails + '/routing/admin/api.js'); var api = require(pathThumbnails + "/routing/admin/api.js");
var compression = require('compression'); var compression = require("compression");
var User = require(pathThumbnails + '/models/user.js'); var User = require(pathThumbnails + "/models/user.js");
var url = 'mongodb://' + mongo_db_cred.host + '/' + mongo_db_cred.users; var url = "mongodb://" + mongo_db_cred.host + "/" + mongo_db_cred.users;
mongoose.connect(url); mongoose.connect(url);
app.engine("handlebars", hbs.engine);
app.set("view engine", "handlebars");
app.use(compression({ filter: shouldCompress }));
app.engine('handlebars', hbs.engine); function shouldCompress(req, res) {
app.set('view engine', 'handlebars'); if (req.headers["x-no-compression"]) {
app.use(compression({filter: shouldCompress})) // don't compress responses with this request header
return false;
}
function shouldCompress (req, res) { // fallback to standard filter function
if (req.headers['x-no-compression']) { return compression.filter(req, res);
// don't compress responses with this request header
return false;
}
// 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 cookieParser = require("cookie-parser");
var referrerPolicy = require('referrer-policy'); var referrerPolicy = require("referrer-policy");
var helmet = require('helmet'); var helmet = require("helmet");
var featurePolicy = require('feature-policy'); var featurePolicy = require("feature-policy");
app.use(featurePolicy({ app.use(
featurePolicy({
features: { features: {
fullscreen: ["*"], fullscreen: ["*"],
//vibrate: ["'none'"], //vibrate: ["'none'"],
payment: ["'none'"], payment: ["'none'"],
microphone: ["'none'"], microphone: ["'none'"],
camera: ["'none'"], camera: ["'none'"],
speaker: ["*"], speaker: ["*"],
syncXhr: ["'self'"], syncXhr: ["'self'"]
//notifications: ["'self'"] //notifications: ["'self'"]
} }
})); })
app.use(helmet({ );
frameguard: false, app.use(
})); helmet({
app.use(referrerPolicy({ policy: 'origin-when-cross-origin' })); frameguard: false
app.enable('view cache'); })
app.set('views', publicPath); );
app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(referrerPolicy({ policy: "origin-when-cross-origin" }));
app.use(bodyParser.urlencoded({ app.enable("view cache");
app.set("views", publicPath);
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
extended: true extended: true
})); })
app.use(session({ );
app.use(
session({
secret: mongo_db_cred.secret, secret: mongo_db_cred.secret,
resave: true, resave: true,
saveUninitialized: true, saveUninitialized: true,
store: new MongoStore({ store: new MongoStore({
url: url, url: url,
useNewUrlParser: true, useNewUrlParser: true,
collection: 'sessions', collection: "sessions",
ttl: mongo_db_cred.expire ttl: mongo_db_cred.expire
}) })
})); // session secret })
); // session secret
app.use(passport.initialize()); app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions app.use(passport.session()); // persistent login sessions
//app.use('/assets', express.static(publicPath + '/assets')); //app.use('/assets', express.static(publicPath + '/assets'));
passport.serializeUser(function(user, done) { passport.serializeUser(function(user, done) {
done(null, user.id); done(null, user.id);
}); });
// used to deserialize the user // used to deserialize the user
passport.deserializeUser(function(id, done) { passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) { User.findById(id, function(err, user) {
done(err, user); done(err, user);
}); });
}); });
passport.use('local-signup', new LocalStrategy({ passport.use(
// by default, local strategy uses username and password, we will override with username "local-signup",
usernameField : 'username', new LocalStrategy(
passwordField : 'password', {
passReqToCallback : true // allows us to pass back the entire request to the callback // by default, local strategy uses username and password, we will override with username
}, usernameField: "username",
function(req, username, password, done) { passwordField: "password",
// asynchronous passReqToCallback: true // allows us to pass back the entire request to the callback
// User.findOne wont fire unless data is sent back },
process.nextTick(function() { 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 // 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 // we are checking to see if the user trying to login already exists
var token = req.body.token; var token = req.body.token;
token_db.collection("tokens").find({token: token}, function(err, docs){ token_db
if(docs.length == 1){ .collection("tokens")
token_db.collection("tokens").remove({token: token}, function(err, docs){ .find({ token: token }, function(err, docs) {
User.findOne({ 'username' : username }, function(err, user) { if (docs.length == 1) {
// if there are any errors, return the error token_db
if (err) .collection("tokens")
return done(err); .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 // check to see if theres already a user with that username
if (user) { if (user) {
return done(null, false); return done(null, false);
} else { } else {
// if there is no user with that username
// create the user
var newUser = new User();
// if there is no user with that username // set the user's local credentials
// create the user newUser.username = username;
var newUser = new User(); newUser.password = newUser.generateHash(password);
// set the user's local credentials // save the user
newUser.username = username; newUser.save(function(err) {
newUser.password = newUser.generateHash(password); if (err) throw err;
return done(null, newUser);
// save the user });
newUser.save(function(err) { }
if (err) });
throw err;
return done(null, newUser);
});
}
});
}); });
} else { } 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({ // find a user whose email is the same as the forms email
// by default, local strategy uses username and password, we will override with email // we are checking to see if the user trying to login already exists
usernameField : 'username', User.findOne({ username: username }, function(err, user) {
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) {
// if there are any errors, return the error before anything else // if there are any errors, return the error before anything else
if (err) if (err) return done(err);
return done(err);
// if no user is found, return the message // if no user is found, return the message
if (!user) if (!user) return done(null, false); // req.flash is the way to set flashdata using connect-flash
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 the user is found but the password is wrong
if (!user.validPassword(password)) if (!user.validPassword(password)) return done(null, false); // create the loginMessage and save it to session as flashdata
return done(null, false); // create the loginMessage and save it to session as flashdata
// all is well, return successful user // all is well, return successful user
return done(null, 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(); return next();
}); }
res.redirect("/");
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("/");
} }
function isLoggedIn(req, res, next) { function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) if (req.isAuthenticated()) return next();
return next(); res.redirect("/login");
res.redirect('/login');
} }
//app.listen(default_port); //app.listen(default_port);

View File

@@ -1,185 +1,207 @@
VERSION = require(pathThumbnails + '/VERSION.js'); VERSION = require(pathThumbnails + "/VERSION.js");
var secure = false; var secure = false;
var path = require('path'); var path = require("path");
try { try {
var cert_config = require(path.join(path.join(__dirname, '../config/'), 'cert_config.js')); var cert_config = require(path.join(
var fs = require('fs'); path.join(__dirname, "../config/"),
var privateKey = fs.readFileSync(cert_config.privateKey).toString(); "cert_config.js"
var certificate = fs.readFileSync(cert_config.certificate).toString(); ));
var ca = fs.readFileSync(cert_config.ca).toString(); var fs = require("fs");
var credentials = { var privateKey = fs.readFileSync(cert_config.privateKey).toString();
key: privateKey, var certificate = fs.readFileSync(cert_config.certificate).toString();
cert: certificate, var ca = fs.readFileSync(cert_config.ca).toString();
ca: ca var credentials = {
}; key: privateKey,
secure = true; cert: certificate,
} catch(err){} ca: ca
};
secure = true;
} catch (err) {}
var add = ""; var add = "";
var express = require('express'); var express = require("express");
var app = express(); var app = express();
var compression = require('compression'); var compression = require("compression");
var exphbs = require('express-handlebars'); var exphbs = require("express-handlebars");
var cors = require('cors'); var cors = require("cors");
var Functions = require(pathThumbnails + '/handlers/functions.js'); var Functions = require(pathThumbnails + "/handlers/functions.js");
var hbs = exphbs.create({ var hbs = exphbs.create({
defaultLayout: publicPath + '/layouts/client/main', defaultLayout: publicPath + "/layouts/client/main",
layoutsDir: publicPath + '/layouts/client', layoutsDir: publicPath + "/layouts/client",
partialsDir: publicPath + '/partials', partialsDir: publicPath + "/partials",
helpers: { helpers: {
if_equal: function(a, b, opts) { if_equal: function(a, b, opts) {
if (a == b) { if (a == b) {
return opts.fn(this) return opts.fn(this);
} else { } else {
return opts.inverse(this) return opts.inverse(this);
} }
}, },
decodeString: function(s) { decodeString: function(s) {
if(s == undefined) return s; if (s == undefined) return s;
return Functions.decodeChannelName(s); return Functions.decodeChannelName(s);
}
} }
}
}); });
var uniqid = require('uniqid'); var uniqid = require("uniqid");
app.use(compression({filter: shouldCompress})) app.use(compression({ filter: shouldCompress }));
function shouldCompress (req, res) { function shouldCompress(req, res) {
if (req.headers['x-no-compression']) { if (req.headers["x-no-compression"]) {
// don't compress responses with this request header // don't compress responses with this request header
return false; return false;
} }
// fallback to standard filter function // fallback to standard filter function
return compression.filter(req, res); return compression.filter(req, res);
} }
app.engine('handlebars', hbs.engine); app.engine("handlebars", hbs.engine);
app.set('view engine', 'handlebars'); app.set("view engine", "handlebars");
app.enable('view cache'); app.enable("view cache");
app.set('views', publicPath); app.set("views", publicPath);
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 cookieParser = require("cookie-parser");
var referrerPolicy = require('referrer-policy'); var referrerPolicy = require("referrer-policy");
var helmet = require('helmet'); var helmet = require("helmet");
var featurePolicy = require('feature-policy'); var featurePolicy = require("feature-policy");
app.use(featurePolicy({ app.use(
featurePolicy({
features: { features: {
fullscreen: ["*"], fullscreen: ["*"],
//vibrate: ["'none'"], //vibrate: ["'none'"],
payment: ["'none'"], payment: ["'none'"],
microphone: ["'none'"], microphone: ["'none'"],
camera: ["'none'"], camera: ["'none'"],
speaker: ["*"], speaker: ["*"],
syncXhr: ["'self'"], syncXhr: ["'self'"]
//notifications: ["'self'"] //notifications: ["'self'"]
} }
})); })
app.use(helmet({ );
frameguard: false, app.use(
})); helmet({
app.use(referrerPolicy({ policy: 'origin-when-cross-origin' })); frameguard: false
app.use( bodyParser.json() ); // to support JSON-encoded bodies })
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies );
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 extended: true
})); })
);
app.use(cookieParser()); app.use(cookieParser());
//app.set('json spaces', 2); //app.set('json spaces', 2);
io = require('socket.io')({ io = require("socket.io")({
pingTimeout: 25000, pingTimeout: 25000
//path: '/zoff', //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*")}); //"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(); socketIO();
app.socketIO = io; app.socketIO = io;
/* Globally needed "libraries" and files */ /* Globally needed "libraries" and files */
var router = require(pathThumbnails + '/routing/client/router.js'); var router = require(pathThumbnails + "/routing/client/router.js");
var api_file = require(pathThumbnails + '/routing/client/api.js'); var api_file = require(pathThumbnails + "/routing/client/api.js");
var api = api_file.router; var api = api_file.router;
api_file.sIO = app.socketIO; 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) { app.get("/robots.txt", function(req, res) {
res.type('text/plain'); res.type("text/plain");
res.send("User-agent: *\nAllow: /$\nDisallow: /"); res.send("User-agent: *\nAllow: /$\nDisallow: /");
}); });
app.use(function (req, res, next) { app.use(function(req, res, next) {
var cookie = req.cookies._uI; var cookie = req.cookies._uI;
var skipElements = ["/_embed", "/assets/manifest.json", "/apple-touch-icon.png"]; var skipElements = [
if(skipElements.indexOf(req.originalUrl) > -1) { "/_embed",
res.header("Access-Control-Allow-Origin", "*"); "/assets/manifest.json",
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); "/apple-touch-icon.png"
next(); ];
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 { } else {
if(req.originalUrl.split("/").length > 3) { if (cookie === undefined) {
res.header("Access-Control-Allow-Origin", "*"); try {
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); //console.error((new Date), "originalUrl", req.originalUrl);
next(); //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?");
} else { } catch (e) {
if (cookie === undefined) { //console.error((new Date), "couldn't fetch origin");
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();
} }
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) { app.use("/service-worker.js", function(req, res) {
res.sendFile(publicPath + '/service-worker.js'); res.sendFile(publicPath + "/service-worker.js");
}); });
app.use('/', ico_router); app.use("/", ico_router);
app.use('/', api); app.use("/", api);
app.use('/', cors(), router); app.use("/", cors(), router);
app.use('/assets/js', function(req, res, next) { app.use("/assets/js", function(req, res, next) {
res.sendStatus(403); res.sendStatus(403);
return; return;
}); });
app.use('/assets/admin', function(req, res, next) { app.use("/assets/admin", function(req, res, next) {
res.sendStatus(403); res.sendStatus(403);
return; return;
}); });
app.use('/assets', express.static(publicPath + '/assets')); app.use("/assets", express.static(publicPath + "/assets"));
app.use(function (req, res, next) { app.use(function(req, res, next) {
res.status(404); res.status(404);
res.redirect("/404"); res.redirect("/404");
}) });
module.exports = app; module.exports = app;

View File

@@ -1,8 +1,8 @@
var api_key = { var api_key = {
"youtube": "xxxx", youtube: "xxxx",
"soundcloud": "xx", soundcloud: "xx" // This can be excluded if you don't have a soundcloud key
}; };
try { try {
module.exports = api_key; module.exports = api_key;
} catch(e) {} } catch (e) {}

View File

@@ -1,59 +1,62 @@
var toShowConfig = { var toShowConfig = {
"addsongs": true, addsongs: true,
"adminpass": 1, adminpass: 1,
"allvideos": 1, allvideos: 1,
"frontpage": 1, frontpage: 1,
"longsongs": 1, longsongs: 1,
"removeplay": 1, removeplay: 1,
"shuffle": 1, shuffle: 1,
"skip": 1, skip: 1,
"startTime": 1, startTime: 1,
"userpass": 1, userpass: 1,
"vote": 1, vote: 1,
"toggleChat": { $ifNull: [ "$toggleChat", true ] }, toggleChat: { $ifNull: ["$toggleChat", true] },
"strictSkip": { $ifNull: [ "$strictSkip", false ] }, strictSkip: { $ifNull: ["$strictSkip", false] },
"strictSkipNumber": { $ifNull: [ "$strictSkipNumber", 10 ] }, strictSkipNumber: { $ifNull: ["$strictSkipNumber", 10] },
"description": { $ifNull: [ "$description", "" ] }, description: { $ifNull: ["$description", ""] },
"thumbnail": { $ifNull: [ "$thumbnail", "" ] }, thumbnail: { $ifNull: ["$thumbnail", ""] },
"rules": { $ifNull: [ "$rules", "" ] }, rules: { $ifNull: ["$rules", ""] },
"_id": 0 _id: 0
}; };
var project_object = { var project_object = {
"_id": 0, _id: 0,
"id": 1, id: 1,
"added": 1, added: 1,
"now_playing": 1, now_playing: 1,
"title": 1, title: 1,
"votes": 1, votes: 1,
"start": 1, start: 1,
"duration": 1, duration: 1,
"end": 1, end: 1,
"type": 1, type: 1,
"source": { $ifNull: [ "$source", "youtube" ] }, source: { $ifNull: ["$source", "youtube"] },
"thumbnail": { thumbnail: {
$ifNull: [ "$thumbnail", { $ifNull: [
$concat : [ "https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"] "$thumbnail",
} ] {
}, $concat: ["https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"]
"tags": { $ifNull: [ "$tags", [] ] }, }
]
},
tags: { $ifNull: ["$tags", []] }
}; };
var toShowChannel = { var toShowChannel = {
start: 1, start: 1,
end: 1, end: 1,
added: 1, added: 1,
id: 1, id: 1,
title: 1, title: 1,
votes: 1, votes: 1,
duration: 1, duration: 1,
type: 1, type: 1,
_id: 0, _id: 0,
tags: 1, tags: 1,
now_playing: 1, now_playing: 1,
type: 1, type: 1,
source: 1, source: 1,
thumbnail: 1, thumbnail: 1
}; };
module.exports.project_object = project_object; module.exports.project_object = project_object;

File diff suppressed because it is too large Load Diff

View File

@@ -1,39 +1,84 @@
var path = require('path'); var path = require("path");
try { try {
var mongo_config = require(path.join(path.join(__dirname, '../config/'), 'mongo_config.js')); var mongo_config = require(path.join(
} catch(e) { path.join(__dirname, "../config/"),
console.log("Error - missing file"); "mongo_config.js"
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); } 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 mongojs = require("mongojs");
var db = mongojs('mongodb://' + mongo_config.host + '/' + mongo_config.config); var db = mongojs("mongodb://" + mongo_config.host + "/" + mongo_config.config);
var connected_db = mongojs('mongodb://' + mongo_config.host + '/user_credentials'); var connected_db = mongojs(
"mongodb://" + mongo_config.host + "/user_credentials"
);
var ObjectId = mongojs.ObjectId; var ObjectId = mongojs.ObjectId;
db.collection("chat_logs").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 600 }, function(){}); db.collection("chat_logs").createIndex(
db.collection("timeout_api").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 120 }, function(){}); { createdAt: 1 },
db.collection("api_links").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 86400 }, function(){}); { expireAfterSeconds: 600 },
db.on('connected', function(err) { function() {}
console.log("connected"); );
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) { db.on("error", function(err) {
console.log("\n" + new Date().toString() + "\n Database error: ", err); console.log("\n" + new Date().toString() + "\n Database error: ", err);
}); });
db.on("error", function(err) {
db.on('error',function(err) { console.log("\n" + new Date().toString() + "\n Database error: ", err);
console.log("\n" + new Date().toString() + "\n Database error: ", err);
}); });
/* Resetting usernames, and connected users */ /* 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("unique_ids").update(
db.collection("user_names").remove({"guid": {$exists: true}}, {multi: true, upsert: true}, function(err, docs){}); { _id: "unique_ids" },
db.collection("user_names").update({"_id": "all_names"}, {$set: {names: []}}, {multi: true, upsert: true}, function(err, docs){}); { $set: { unique_ids: [] } },
db.collection("connected_users").update({users: {$exists: true}}, {$set: {users: []}}, {multi: true, upsert: true}, function(err, docs){}); { multi: true, upsert: true },
db.collection("connected_users").update({"_id": "total_users"}, {$set: {total_users: []}}, {multi: true, upsert: true}, function(err, docs) {}); function(err, docs) {}
db.collection("frontpage_lists").update({viewers: {$ne: 0}}, {$set: {"viewers": 0}}, {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; module.exports = db;

View File

@@ -1,104 +1,143 @@
var Functions = require(pathThumbnails + '/handlers/functions.js'); var Functions = require(pathThumbnails + "/handlers/functions.js");
var db = require(pathThumbnails + '/handlers/db.js'); var db = require(pathThumbnails + "/handlers/db.js");
function frontpage_lists(msg, socket) { function frontpage_lists(msg, socket) {
if(msg == undefined || !msg.hasOwnProperty('version') || msg.version != VERSION || msg.version == undefined) { if (
var result = { msg == undefined ||
version: { !msg.hasOwnProperty("version") ||
expected: VERSION, msg.version != VERSION ||
got: msg.hasOwnProperty("version") ? msg.version : undefined, msg.version == undefined
} ) {
}; var result = {
socket.emit('update_required', result); version: {
return; 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("frontpage_lists").find({ frontpage: true }, function(
db.collection("connected_users").find({"_id": "total_users"}, function(err, tot){ err,
socket.compress(true).emit("playlists", {channels: docs, viewers: tot[0].total_users.length}); 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) { function get_frontpage_lists(callback) {
var project_object = { var project_object = {
"_id": 1, _id: 1,
"count": 1, count: 1,
"frontpage": 1, frontpage: 1,
"id": 1, id: 1,
"title": 1, title: 1,
"viewers": 1, viewers: 1,
"accessed": 1, accessed: 1,
"pinned": { $ifNull: [ "$pinned", 0 ] }, pinned: { $ifNull: ["$pinned", 0] },
"description": { description: {
$ifNull: [ {$cond: { $ifNull: [
"if": { {
"$or": [ $cond: {
{ "$eq": [ "$description", ""] }, if: {
{ "$eq": [ "$description", null] }, $or: [
{ "$eq": [ "$description", undefined] } { $eq: ["$description", ""] },
] { $eq: ["$description", null] },
}, { $eq: ["$description", undefined] }
then: "This list has no description", ]
else: "$description" },
}}, "This list has no description"] then: "This list has no description",
else: "$description"
}
}, },
"thumbnail": { "This list has no description"
$ifNull: [ {$cond: { ]
"if": { },
"$or": [ thumbnail: {
{ "$eq": [ "$thumbnail", ""] }, $ifNull: [
{ "$eq": [ "$thumbnail", null] }, {
{ "$eq": [ "$thumbnail", undefined] } $cond: {
] if: {
}, $or: [
then: { { $eq: ["$thumbnail", ""] },
$concat : [ "https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"] { $eq: ["$thumbnail", null] },
}, { $eq: ["$thumbnail", undefined] }
else: "$thumbnail" ]
}}, { $concat : [ "https://img.youtube.com/vi/", "$id", "/mqdefault.jpg"]}] },
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([ {
{ $project: project_object
"$match": { },
frontpage: true, {
count: {$gt: 3}, $sort: {
} pinned: -1,
}, viewers: -1,
{ accessed: -1,
"$project": project_object count: -1,
}, title: 1
{ }
"$sort" : { }
"pinned": -1, ],
"viewers": -1, callback
"accessed": -1, );
"count": -1,
"title": 1
}
},
], callback);
} }
function update_frontpage(coll, id, title, thumbnail, source, callback) { function update_frontpage(coll, id, title, thumbnail, source, callback) {
//coll = coll.replace(/ /g,''); //coll = coll.replace(/ /g,'');
db.collection("frontpage_lists").find({_id: coll}, function(e, doc) { db.collection("frontpage_lists").find({ _id: coll }, function(e, doc) {
var updateObject = { var updateObject = {
id: id, id: id,
title: title, title: title,
accessed: Functions.get_time() 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))) { if (
updateObject.thumbnail = thumbnail; doc.length > 0 &&
if(thumbnail == undefined) updateObject.thumbnail = ""; ((doc[0].thumbnail != "" &&
} doc[0].thumbnail != undefined &&
db.collection("frontpage_lists").update({_id: coll}, {$set: updateObject (doc[0].thumbnail.indexOf("https://i1.sndcdn.com") > -1 ||
},{upsert: true}, function(err, returnDocs){ doc[0].thumbnail.indexOf("https://w1.sndcdn.com") > -1 ||
if(typeof(callback) == "function") callback(); 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; module.exports.get_frontpage_lists = get_frontpage_lists;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,282 +1,397 @@
var Functions = require(pathThumbnails + '/handlers/functions.js'); var Functions = require(pathThumbnails + "/handlers/functions.js");
var crypto = require('crypto'); var crypto = require("crypto");
var Filter = require('bad-words'); var Filter = require("bad-words");
var filter = new Filter({ placeHolder: 'x'}); var filter = new Filter({ placeHolder: "x" });
/*var filter = { /*var filter = {
clean: function(str) { clean: function(str) {
return str; return str;
} }
}*/ }*/
var projects = require(pathThumbnails + "/handlers/aggregates.js"); 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) { function password(inp, coll, guid, offline, socket) {
var sessionId = Functions.getSession(socket); var sessionId = Functions.getSession(socket);
if(sessionId == "") sessionId = "empty"; if (sessionId == "") sessionId = "empty";
if(inp !== undefined && inp !== null && inp !== "") if (inp !== undefined && inp !== null && inp !== "") {
{ if (
if(!inp.hasOwnProperty("password") || !inp.hasOwnProperty("channel") || !inp.hasOwnProperty("password") ||
typeof(inp.password) != "string" || typeof(inp.channel) != "string") { !inp.hasOwnProperty("channel") ||
var result = { typeof inp.password != "string" ||
channel: { typeof inp.channel != "string"
expected: "string", ) {
got: inp.hasOwnProperty("channel") ? typeof(inp.channel) : undefined, var result = {
}, channel: {
password: { expected: "string",
expected: "password", got: inp.hasOwnProperty("channel") ? typeof inp.channel : undefined
got: inp.hasOwnProperty("password") ? typeof(inp.password) : undefined, },
}, password: {
}; expected: "password",
socket.emit('update_required', result); got: inp.hasOwnProperty("password") ? typeof inp.password : undefined
return;
} }
pw = inp.password; };
try { socket.emit("update_required", result);
coll = inp.channel; return;
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);
} }
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) { function conf_function(params, coll, guid, offline, socket) {
if(params !== undefined && params !== null && params !== "") if (params !== undefined && params !== null && params !== "") {
{ if (coll !== undefined) {
if(coll !== undefined) { try {
try { coll = params.channel; //.replace(/ /g,'');
coll = params.channel;//.replace(/ /g,''); if (coll.length == 0) return;
if(coll.length == 0) return; coll = Functions.removeEmojis(coll).toLowerCase();
coll = Functions.removeEmojis(coll).toLowerCase(); //coll = coll.replace(/_/g, "");
//coll = coll.replace(/_/g, "");
//coll = filter.clean(coll); //coll = filter.clean(coll);
} catch(e) { } catch (e) {
return; 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);
} }
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; module.exports.password = password;

View File

@@ -1,39 +1,48 @@
var path = require('path'); var path = require("path");
function requested_change(type, string, channel) { function requested_change(type, string, channel) {
try { try {
//channel = channel.replace(/ /g,''); //channel = channel.replace(/ /g,'');
var nodemailer = require('nodemailer'); var nodemailer = require("nodemailer");
var mailconfig = require(path.join(__dirname, '../config/mailconfig.js')); var mailconfig = require(path.join(__dirname, "../config/mailconfig.js"));
let transporter = nodemailer.createTransport(mailconfig); let transporter = nodemailer.createTransport(mailconfig);
transporter.verify(function(error, success) { transporter.verify(function(error, success) {
if (error) { if (error) {
return; return;
} else { } else {
var message = "A " + type + " change was requested on <b>" + channel + "</b><br><br>New supposed value is: <br><br><b>" + string + "</b><br><br><br> \ var message =
"A " +
type +
" change was requested on <b>" +
channel +
"</b><br><br>New supposed value is: <br><br><b>" +
string +
"</b><br><br><br> \
Go to <a href='https://admin.zoff.me/'>https://admin.zoff.me/</a> to accept or decline the request."; Go to <a href='https://admin.zoff.me/'>https://admin.zoff.me/</a> to accept or decline the request.";
var msg = { var msg = {
from: mailconfig.from, from: mailconfig.from,
to: mailconfig.notify_mail, to: mailconfig.notify_mail,
subject: 'ZOFF: Requested new ' + type, subject: "ZOFF: Requested new " + type,
text: message, text: message,
html: message, html: message
} };
transporter.sendMail(msg, (error, info) => { transporter.sendMail(msg, (error, info) => {
if (error) { if (error) {
transporter.close(); transporter.close();
return; return;
} }
transporter.close(); 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; module.exports.requested_change = requested_change;

File diff suppressed because it is too large Load Diff

View File

@@ -1,183 +1,284 @@
var Functions = require(pathThumbnails + '/handlers/functions.js'); var Functions = require(pathThumbnails + "/handlers/functions.js");
var Notifications = require(pathThumbnails + '/handlers/notifications.js'); var Notifications = require(pathThumbnails + "/handlers/notifications.js");
var crypto = require('crypto'); var crypto = require("crypto");
var db = require(pathThumbnails + '/handlers/db.js'); var db = require(pathThumbnails + "/handlers/db.js");
function thumbnail(msg, coll, guid, offline, socket) { function thumbnail(msg, coll, guid, offline, socket) {
if(msg.thumbnail != undefined && msg.channel && msg.channel != undefined && Functions.isUrl(msg.thumbnail)){ if (
if(typeof(msg.channel) != "string" || typeof(msg.thumbnail) != "string") msg.thumbnail != undefined &&
{ msg.channel &&
var result = { msg.channel != undefined &&
channel: { Functions.isUrl(msg.thumbnail)
expected: "string", ) {
got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, if (typeof msg.channel != "string" || typeof msg.thumbnail != "string") {
}, var result = {
pass: { channel: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined
}, },
thumbnail: { pass: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("thumbnail") ? typeof(msg.thumbnail) : undefined, got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined
}, },
adminpass: { thumbnail: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, got: msg.hasOwnProperty("thumbnail")
}, ? typeof msg.thumbnail
}; : undefined
socket.emit("update_required", result); },
return; adminpass: {
} expected: "string",
//coll = coll.replace(/ /g,''); got: msg.hasOwnProperty("adminpass")
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { ? typeof msg.adminpass
if(userpass != "" || msg.pass == undefined) { : undefined
msg.pass = userpass; }
} else if(msg.hasOwnProperty("pass")){ };
msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); socket.emit("update_required", result);
} return;
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");
} }
//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) { function description(msg, coll, guid, offline, socket) {
if(msg.description && msg.channel && msg.description.length < 100){ if (msg.description && msg.channel && msg.description.length < 100) {
if(typeof(msg.channel) != "string" || typeof(msg.description) != "string") { if (typeof msg.channel != "string" || typeof msg.description != "string") {
var result = { var result = {
channel: { channel: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined
}, },
pass: { pass: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined
}, },
description: { description: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("description") ? typeof(msg.description) : undefined, got: msg.hasOwnProperty("description")
}, ? typeof msg.description
adminpass: { : undefined
expected: "string", },
got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, adminpass: {
}, expected: "string",
}; got: msg.hasOwnProperty("adminpass")
socket.emit("update_required", result); ? typeof msg.adminpass
return; : undefined
} }
//coll = coll.replace(/ /g,''); };
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) { socket.emit("update_required", result);
if(userpass != "" || msg.pass == undefined) { return;
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");
} }
//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) { function rules(msg, coll, guid, offline, socket) {
if(msg.rules && msg.channel && msg.rules.length < 250){ if (msg.rules && msg.channel && msg.rules.length < 250) {
if(typeof(msg.channel) != "string" || typeof(msg.rules) != "string") { if (typeof msg.channel != "string" || typeof msg.rules != "string") {
var result = { var result = {
channel: { channel: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined
}, },
pass: { pass: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined
}, },
rules: { rules: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("rules") ? typeof(msg.rules) : undefined, got: msg.hasOwnProperty("rules") ? typeof msg.rules : undefined
}, },
adminpass: { adminpass: {
expected: "string", expected: "string",
got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined, got: msg.hasOwnProperty("adminpass")
}, ? typeof msg.adminpass
}; : undefined
socket.emit("update_required", result); }
return; };
} socket.emit("update_required", result);
//coll = coll.replace(/ /g,''); return;
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");
} }
//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.thumbnail = thumbnail;
module.exports.description = description; module.exports.description = description;
module.exports.rules = rules; module.exports.rules = rules;

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,7 @@ try {
} catch (e) { } catch (e) {
allowed_key = ["***"]; allowed_key = ["***"];
console.log( 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"); var crypto = require("crypto");

View File

@@ -1,24 +1,33 @@
var express = require('express'); var express = require("express");
const path = require('path'); const path = require("path");
var router = express.Router(); var router = express.Router();
router.use(function(req, res, next) { 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) { router.route("/favicon.ico").get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/images/favicon.ico')); res.sendFile(path.join(pathThumbnails, "/public/assets/images/favicon.ico"));
}); });
router.route('/browserconfig.xml').get(function(req, res, next) { router.route("/browserconfig.xml").get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/images/browserconfig.xml')); res.sendFile(
path.join(pathThumbnails, "/public/assets/images/browserconfig.xml")
);
}); });
router.route('/apple-touch-icon.png').get(function(req, res, next) { router.route("/apple-touch-icon.png").get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/images/apple-touch-icon.png')); res.sendFile(
path.join(pathThumbnails, "/public/assets/images/apple-touch-icon.png")
);
}); });
router.route('/apple-touch-icon-precomposed.png').get(function(req, res, next) { 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')); res.sendFile(
path.join(
pathThumbnails,
"/public/assets/images/apple-touch-icon-precomposed.png"
)
);
}); });
module.exports = router; module.exports = router;

View File

@@ -1,248 +1,270 @@
var express = require('express'); var express = require("express");
var router = express.Router(); var router = express.Router();
var path = require('path'); var path = require("path");
var year = new Date().getYear()+1900; var year = new Date().getYear() + 1900;
var path = require('path'); var path = require("path");
var analytics = "xx"; var analytics = "xx";
var google = {}; var google = {};
var adsense = "xx"; var adsense = "xx";
var adds = false; var adds = false;
var mongojs = require('mongojs'); var mongojs = require("mongojs");
var token_db = mongojs("tokens"); var token_db = mongojs("tokens");
var Functions = require(pathThumbnails + '/handlers/functions.js'); var Functions = require(pathThumbnails + "/handlers/functions.js");
var Frontpage = require(pathThumbnails + '/handlers/frontpage.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'); //var db = require(pathThumbnails + '/handlers/db.js');
try { try {
google = require(path.join(path.join(__dirname, '../../config/'), 'google.js')); google = require(path.join(
analytics = google.analytics; path.join(__dirname, "../../config/"),
adsense = google.adsense; "google.js"
} catch(e) { ));
console.log("No analytics-id found"); analytics = google.analytics;
adsense = google.adsense;
} catch (e) {
console.log("No analytics-id found");
} }
try { try {
var Recaptcha = require('express-recaptcha'); var Recaptcha = require("express-recaptcha");
var recaptcha_config = require(path.join(path.join(__dirname, '../../config/'), 'recaptcha.js')); var recaptcha_config = require(path.join(
var RECAPTCHA_SITE_KEY = recaptcha_config.site; path.join(__dirname, "../../config/"),
var RECAPTCHA_SECRET_KEY = recaptcha_config.key; "recaptcha.js"
var recaptcha = new Recaptcha(RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY); ));
} catch(e) { var RECAPTCHA_SITE_KEY = recaptcha_config.site;
console.log("Error - missing file"); var RECAPTCHA_SECRET_KEY = recaptcha_config.key;
console.log("Seems you forgot to create the file recaptcha.js in /server/config/. Have a look at recaptcha.example.js."); var recaptcha = new Recaptcha(RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY);
var recaptcha = { } catch (e) {
middleware: { console.log(
render: (req, res, next) => { "(!) Missing file - /config/recaptcha.js Have a look at /config/recaptcha.example.js."
res.recaptcha = "" );
next() var recaptcha = {
} middleware: {
} render: (req, res, next) => {
res.recaptcha = "";
next();
}
} }
};
} }
router.use(recaptcha.middleware.render, function(req, res, 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){ router.route("/:channel_name").get(function(req, res, next) {
channel(req, res, next); channel(req, res, next);
}); });
router.route('/r/:base64data').get(function(req, res, next){ router.route("/r/:base64data").get(function(req, res, next) {
var channelToRedirect = Buffer.from(req.params.base64data, 'base64'); var channelToRedirect = Buffer.from(req.params.base64data, "base64");
res.redirect('/' + channelToRedirect); res.redirect("/" + channelToRedirect);
}); });
router.route('/').get(function(req, res, next){ router.route("/").get(function(req, res, next) {
root(req, res, next); root(req, res, next);
}); });
router.route('/').post(function(req, res, next){ router.route("/").post(function(req, res, next) {
root(req, res, next); root(req, res, next);
}); });
router.route('/api/embed').get(function(req, res, next) { router.route("/api/embed").get(function(req, res, next) {
var data = { var data = {
year: year, year: year,
type: "video", type: "video",
javascript_file: "embed.min.js", javascript_file: "embed.min.js",
captcha: res.recaptcha, captcha: res.recaptcha,
analytics: analytics, analytics: analytics,
stylesheet: "embed.css", stylesheet: "embed.css",
embed: true, embed: true,
og_image: "https://zoff.me/assets/images/small-square.jpg", og_image: "https://zoff.me/assets/images/small-square.jpg"
} };
res.render('layouts/client/embed', data); res.render("layouts/client/embed", data);
}); });
router.route('/api/oauth').get(function(req, res, next) { router.route("/api/oauth").get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/html/callback.html')); res.sendFile(path.join(pathThumbnails, "/public/assets/html/callback.html"));
}); });
router.route('/api/apply').get(function(req, res, next) { router.route("/api/apply").get(function(req, res, next) {
var data = { var data = {
year: year, year: year,
javascript_file: "token.min.js", javascript_file: "token.min.js",
captcha: res.recaptcha, captcha: res.recaptcha,
analytics: analytics, analytics: analytics,
adsense: adsense, adsense: adsense,
adds: adds, adds: adds,
type: "website", type: "website",
activated: false, activated: false,
id: "", id: "",
correct: false, correct: false,
stylesheet: "style.css", stylesheet: "style.css",
embed: false, 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);
}); });
router.route('/api/apply/:id').get(function(req, res) { router.route("/api/apply/:id").get(function(req, res) {
var id = req.params.id; var id = req.params.id;
token_db.collection('api_links').find({id: id}, function(err, result) { token_db.collection("api_links").find({ id: id }, function(err, result) {
if(result.length == 1) { if (result.length == 1) {
token_db.collection('api_links').remove({id: id}, function(e,d) { 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) { token_db
var data = { .collection("api_token")
year: year, .update(
javascript_file: "token.min.js", { token: result[0].token },
captcha: res.recaptcha, { $set: { active: true } },
analytics: analytics, function(e, d) {
adsense: adsense, var data = {
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 = {
year: year, year: year,
javascript_file: "token.min.js", javascript_file: "token.min.js",
captcha: res.recaptcha, captcha: res.recaptcha,
analytics: analytics, analytics: analytics,
adsense: adsense, adsense: adsense,
adds: adds, adds: adds,
activated: false, activated: true,
token:"",
type: "website", type: "website",
correct: false, token: result[0].token,
correct: true,
stylesheet: "style.css", stylesheet: "style.css",
embed: false, 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) { function root(req, res, next) {
try{ try {
var url = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : req.headers.host.split(":")[0]; var url = req.headers["x-forwarded-host"]
var subdomain = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'].split(".") : req.headers.host.split(":")[0].split("."); ? req.headers["x-forwarded-host"]
/*if(url != "zoff.me" && url != "admin.localhost" && url != "admin.zoff.me" && url != "remote.zoff.me" && url != "fb.zoff.me" && url != "remote.localhost" && url != "localhost") { : 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"); res.redirect("https://zoff.me");
return; return;
}*/ }*/
if(subdomain[0] == "remote") { if (subdomain[0] == "remote") {
var data = { var data = {
year: year, year: year,
javascript_file: "remote.min.js", javascript_file: "remote.min.js",
captcha: res.recaptcha, captcha: res.recaptcha,
adsense: adsense, adsense: adsense,
adds: adds, adds: adds,
analytics: analytics, analytics: analytics,
type: "website", type: "website",
stylesheet: "style.css", stylesheet: "style.css",
embed: false, embed: false,
client: false, client: 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/remote', data); res.render("layouts/client/remote", data);
} else if(subdomain[0] == "www") { } else if (subdomain[0] == "www") {
res.redirect("https://zoff.me"); res.redirect("https://zoff.me");
} else { } else {
var data = { var data = {
year: year, year: year,
javascript_file: "main.min.js", javascript_file: "main.min.js",
captcha: res.recaptcha, captcha: res.recaptcha,
adsense: adsense, adsense: adsense,
adds: adds, adds: adds,
analytics: analytics, analytics: analytics,
stylesheet: "style.css", stylesheet: "style.css",
type: "website", type: "website",
embed: false, embed: false,
client: false, client: false,
og_image: "https://zoff.me/assets/images/small-square.jpg", og_image: "https://zoff.me/assets/images/small-square.jpg",
channels: [], channels: []
} };
if(subdomain[0] == "client") { if (subdomain[0] == "client") {
data.client = true; data.client = true;
} }
Frontpage.get_frontpage_lists(function(err, docs){ Frontpage.get_frontpage_lists(function(err, docs) {
db.collection("connected_users").find({"_id": "total_users"}, function(err, tot) { db.collection("connected_users").find({ _id: "total_users" }, function(
if(docs.length > 0) { err,
data.channels_exist = true; tot
data.channels = docs.slice(0, 12); ) {
data.channel_list = JSON.stringify(docs); if (docs.length > 0) {
} else { data.channels_exist = true;
data.channels_exist = false; data.channels = docs.slice(0, 12);
data.channels = []; data.channel_list = JSON.stringify(docs);
data.channel_list = []; } else {
} data.channels_exist = false;
data.viewers = tot[0].total_users.length; data.channels = [];
res.render('layouts/client/frontpage', data); 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");
} }
} catch (e) {
console.log(e);
//res.redirect("https://zoff.me");
}
} }
function channel(req, res, next) { function channel(req, res, next) {
try{ try {
var url = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : req.headers.host.split(":")[0]; var url = req.headers["x-forwarded-host"]
var subdomain = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'].split(".") : req.headers.host.split(":")[0].split("."); ? req.headers["x-forwarded-host"]
/*if(url != "zoff.me" && url != "admin.localhost" && url != "admin.zoff.me" && url != "remote.zoff.me" && url != "fb.zoff.me" && url != "remote.localhost" && url != "localhost") { : 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"); res.redirect("https://zoff.me");
return; return;
}*/ }*/
if(subdomain[0] == "remote") { if (subdomain[0] == "remote") {
var data = { var data = {
year: year, year: year,
javascript_file: "remote.min.js", javascript_file: "remote.min.js",
captcha: res.recaptcha, captcha: res.recaptcha,
adsense: adsense, adsense: adsense,
adds: adds, adds: adds,
analytics: analytics, analytics: analytics,
type: "website", type: "website",
stylesheet: "style.css", stylesheet: "style.css",
embed: false, embed: false,
client: false, client: 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/remote', data); res.render("layouts/client/remote", data);
} else if(subdomain.length >= 2 && subdomain[0] == "www") { } else if (subdomain.length >= 2 && subdomain[0] == "www") {
res.redirect("https://zoff.me"); res.redirect("https://zoff.me");
} else { } else {
if(req.params.channel_name == "o_callback") { if (req.params.channel_name == "o_callback") {
res.redirect("/api/oauth"); res.redirect("/api/oauth");
//res.sendFile(path.join(pathThumbnails, '/public/assets/html/callback.html')); //res.sendFile(path.join(pathThumbnails, '/public/assets/html/callback.html'));
} else { } else {
/*db.collection("frontpage_lists").find({"_id": Functions.encodeChannelName(req.params.channel_name)}, function(err, docs) { /*db.collection("frontpage_lists").find({"_id": Functions.encodeChannelName(req.params.channel_name)}, function(err, docs) {
console.log(docs); console.log(docs);
var og_image = "https://zoff.me/assets/images/small-square.jpg"; var og_image = "https://zoff.me/assets/images/small-square.jpg";
if(docs.length == 1) { 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"; og_image = "https://img.youtube.com/vi/" + docs[0].id + "/hqdefault.jpg";
} }
}*/ }*/
var data = { var data = {
title: "404: File Not Found", title: "404: File Not Found",
//list_name: capitalizeFirstLetter(Functions.decodeChannelName(req.params.channel_name)), //list_name: capitalizeFirstLetter(Functions.decodeChannelName(req.params.channel_name)),
list_name: capitalizeFirstLetter(req.params.channel_name), list_name: capitalizeFirstLetter(req.params.channel_name),
year: year, year: year,
javascript_file: "main.min.js", javascript_file: "main.min.js",
captcha: res.recaptcha, captcha: res.recaptcha,
adsense: adsense, adsense: adsense,
adds: adds, adds: adds,
analytics: analytics, analytics: analytics,
type: "video", type: "video",
stylesheet: "style.css", stylesheet: "style.css",
embed: false, embed: false,
client:false, client: false,
og_image: "https://zoff.me/assets/images/small-square.jpg" og_image: "https://zoff.me/assets/images/small-square.jpg"
} };
if(subdomain[0] == "client") { if (subdomain[0] == "client") {
data.client = true; data.client = true;
}
if(req.params.channel_name == "404") {
res.status(404);
}
res.render('layouts/client/channel', data);
//});
}
} }
} catch(e) { if (req.params.channel_name == "404") {
res.redirect("https://zoff.me"); res.status(404);
}
res.render("layouts/client/channel", data);
//});
}
} }
} catch (e) {
res.redirect("https://zoff.me");
}
} }
function capitalizeFirstLetter(string) { function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1); return string.charAt(0).toUpperCase() + string.slice(1);
} }
module.exports = router; module.exports = router;