Merge pull request #511 from zoff-music/refactor/prettifier

Prettified som more files and fixed some logging of missing files so …
This commit is contained in:
Kasper Rynning-Tønnesen
2019-07-26 08:46:42 +02:00
committed by GitHub
18 changed files with 5629 additions and 3697 deletions

View File

@@ -1,146 +1,155 @@
var cluster = require('cluster'),
net = require('net'),
path = require('path'),
//publicPath = path.join(__dirname, 'public'),
http = require('http'),
port = 8080,
//farmhash = require('farmhash'),
uniqid = require('uniqid'),
num_processes = require('os').cpus().length;
var cluster = require("cluster"),
net = require("net"),
path = require("path"),
//publicPath = path.join(__dirname, 'public'),
http = require("http"),
port = 8080,
//farmhash = require('farmhash'),
uniqid = require("uniqid"),
num_processes = require("os").cpus().length;
publicPath = path.join(__dirname, 'public');
publicPath = path.join(__dirname, "public");
pathThumbnails = __dirname;
try {
var redis = require("redis");
var client = redis.createClient({host: "localhost", port: 6379});
client.on("error", function (err) {
console.log("Couldn't connect to redis-server, assuming non-clustered run");
num_processes = 1;
startSingle(false, false);
client.quit();
});
client.on("connect", function() {
startClustered(true);
client.quit();
});
} catch(e) {
var redis = require("redis");
var client = redis.createClient({ host: "localhost", port: 6379 });
client.on("error", function(err) {
console.log("Couldn't connect to redis-server, assuming non-clustered run");
num_processes = 1;
startSingle(false, false);
client.quit();
});
client.on("connect", function() {
startClustered(true);
client.quit();
});
} catch (e) {
console.log("Couldn't connect to redis-server, assuming non-clustered run");
num_processes = 1;
startSingle(false, false);
}
function startClustered(redis_enabled) {
//Found https://stackoverflow.com/questions/40885592/use-node-js-cluster-with-socket-io-chat-application
if (cluster.isMaster) {
var workers = [];
var spawn = function(i) {
workers[i] = cluster.fork();
workers[i].on('exit', function(code, signal) {
if(code == 1) {
process.exit(1);
return;
}
console.log('respawning worker', i);
spawn(i);
});
};
for (var i = 0; i < num_processes; i++) {
spawn(i);
//Found https://stackoverflow.com/questions/40885592/use-node-js-cluster-with-socket-io-chat-application
if (cluster.isMaster) {
var workers = [];
var spawn = function(i) {
workers[i] = cluster.fork();
workers[i].on("exit", function(code, signal) {
if (code == 1) {
process.exit(1);
return;
}
console.log("respawning worker", i);
spawn(i);
});
};
var worker_index = function(ip, len) {
//console.log(ip);
var s = '';
if(ip == undefined) ip = uniqid.time();
for (var i = 0, _len = ip.length; i < _len; i++) {
if(!isNaN(ip[i])) {
s += ip[i];
}
}
return Number(s)%len;
//eturn farmhash.fingerprint32(ip) % len;
};
var server = net.createServer({ pauseOnConnect: true }, function(connection, a) {
var worker = workers[worker_index(connection.remoteAddress, num_processes)];
worker.send('sticky-session:connection', connection);
}).listen(port);
} else {
startSingle(true, redis_enabled);
for (var i = 0; i < num_processes; i++) {
spawn(i);
}
var worker_index = function(ip, len) {
//console.log(ip);
var s = "";
if (ip == undefined) ip = uniqid.time();
for (var i = 0, _len = ip.length; i < _len; i++) {
if (!isNaN(ip[i])) {
s += ip[i];
}
}
return Number(s) % len;
//eturn farmhash.fingerprint32(ip) % len;
};
var server = net
.createServer({ pauseOnConnect: true }, function(connection, a) {
var worker =
workers[worker_index(connection.remoteAddress, num_processes)];
worker.send("sticky-session:connection", connection);
})
.listen(port);
} else {
startSingle(true, redis_enabled);
}
}
function startSingle(clustered, redis_enabled) {
var server;
var client = require('./apps/client.js');
var server;
var client = require("./apps/client.js");
try {
var cert_config = require(path.join(
path.join(__dirname, "config"),
"cert_config.js"
));
var fs = require("fs");
var privateKey = fs.readFileSync(cert_config.privateKey).toString();
var certificate = fs.readFileSync(cert_config.certificate).toString();
var ca = fs.readFileSync(cert_config.ca).toString();
var credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
var https = require("https");
server = https.Server(credentials, routingFunction);
} catch (err) {
console.log("Starting without https (probably on localhost)");
server = http.createServer(routingFunction);
}
if (clustered) {
server.listen(onListen);
} else {
server.listen(port, onListen);
}
var socketIO = client.socketIO;
if (redis_enabled) {
var redis = require("socket.io-redis");
try {
var cert_config = require(path.join(path.join(__dirname, 'config'), 'cert_config.js'));
var fs = require('fs');
var privateKey = fs.readFileSync(cert_config.privateKey).toString();
var certificate = fs.readFileSync(cert_config.certificate).toString();
var ca = fs.readFileSync(cert_config.ca).toString();
var credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
var https = require('https');
server = https.Server(credentials, routingFunction);
} catch(err){
console.log("Starting without https (probably on localhost)");
server = http.createServer(routingFunction);
socketIO.adapter(redis({ host: "localhost", port: 6379 }));
} catch (e) {
console.log("No redis-server to connect to..");
}
}
socketIO.listen(server);
if(clustered) {
server.listen(onListen);
} else {
server.listen(port, onListen);
process.on("message", function(message, connection) {
if (message !== "sticky-session:connection") {
return;
}
var socketIO = client.socketIO;
if(redis_enabled) {
var redis = require('socket.io-redis');
try {
socketIO.adapter(redis({ host: 'localhost', port: 6379 }));
} catch(e) {
console.log("No redis-server to connect to..");
}
}
socketIO.listen(server);
process.on('message', function(message, connection) {
if (message !== 'sticky-session:connection') {
return;
}
server.emit('connection', connection);
connection.resume();
});
server.emit("connection", connection);
connection.resume();
});
}
function onListen() {
console.log("Started with pid [" + process.pid + "]");
console.log("Started with pid [" + process.pid + "]");
}
function routingFunction(req, res, next) {
var client = require('./apps/client.js');
var admin = require('./apps/admin.js');
try {
var url = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : req.headers.host.split(":")[0];
var subdomain = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'].split(".") : req.headers.host.split(":")[0].split(".");
var client = require("./apps/client.js");
var admin = require("./apps/admin.js");
try {
var url = req.headers["x-forwarded-host"]
? req.headers["x-forwarded-host"]
: req.headers.host.split(":")[0];
var subdomain = req.headers["x-forwarded-host"]
? req.headers["x-forwarded-host"].split(".")
: req.headers.host.split(":")[0].split(".");
if(subdomain.length > 1 && subdomain[0] == "admin") {
admin(req, res, next);
} else {
client(req, res, next);
}
} catch(e) {
console.log("Bad request for " + req.headers.host + req.url, e);
res.statusCode = 500;
res.write('Bad request'); //write a response to the client
res.end(); //end the response
if (subdomain.length > 1 && subdomain[0] == "admin") {
admin(req, res, next);
} else {
client(req, res, next);
}
} catch (e) {
console.log("Bad request for " + req.headers.host + req.url, e);
res.statusCode = 500;
res.write("Bad request"); //write a response to the client
res.end(); //end the response
}
}

View File

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

View File

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

View File

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

View File

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

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 {
var mongo_config = require(path.join(path.join(__dirname, '../config/'), 'mongo_config.js'));
} catch(e) {
console.log("Error - missing file");
console.log("Seems you forgot to create the file mongo_config.js in /server/config/. Have a look at mongo_config.example.js.");
process.exit(1);
var mongo_config = require(path.join(
path.join(__dirname, "../config/"),
"mongo_config.js"
));
} catch (e) {
console.log(
"(!) Missing file - /config/mongo_config.js. Have a look at /config/mongo_config.example.js. The server won't run without this existing."
);
process.exit(1);
}
var mongojs = require('mongojs');
var db = mongojs('mongodb://' + mongo_config.host + '/' + mongo_config.config);
var connected_db = mongojs('mongodb://' + mongo_config.host + '/user_credentials');
var mongojs = require("mongojs");
var db = mongojs("mongodb://" + mongo_config.host + "/" + mongo_config.config);
var connected_db = mongojs(
"mongodb://" + mongo_config.host + "/user_credentials"
);
var ObjectId = mongojs.ObjectId;
db.collection("chat_logs").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 600 }, function(){});
db.collection("timeout_api").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 120 }, function(){});
db.collection("api_links").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 86400 }, function(){});
db.on('connected', function(err) {
console.log("connected");
db.collection("chat_logs").createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 600 },
function() {}
);
db.collection("timeout_api").createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 120 },
function() {}
);
db.collection("api_links").createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 86400 },
function() {}
);
db.on("connected", function(err) {
console.log("connected");
});
db.on('error',function(err) {
console.log("\n" + new Date().toString() + "\n Database error: ", err);
db.on("error", function(err) {
console.log("\n" + new Date().toString() + "\n Database error: ", err);
});
db.on('error',function(err) {
console.log("\n" + new Date().toString() + "\n Database error: ", err);
db.on("error", function(err) {
console.log("\n" + new Date().toString() + "\n Database error: ", err);
});
/* Resetting usernames, and connected users */
db.collection("unique_ids").update({"_id": "unique_ids"}, {$set: {unique_ids: []}}, {multi: true, upsert: true}, function(err, docs){});
db.collection("user_names").remove({"guid": {$exists: true}}, {multi: true, upsert: true}, function(err, docs){});
db.collection("user_names").update({"_id": "all_names"}, {$set: {names: []}}, {multi: true, upsert: true}, function(err, docs){});
db.collection("connected_users").update({users: {$exists: true}}, {$set: {users: []}}, {multi: true, upsert: true}, function(err, docs){});
db.collection("connected_users").update({"_id": "total_users"}, {$set: {total_users: []}}, {multi: true, upsert: true}, function(err, docs) {});
db.collection("frontpage_lists").update({viewers: {$ne: 0}}, {$set: {"viewers": 0}}, {multi: true, upsert: true}, function(err, docs) {});
db.collection("unique_ids").update(
{ _id: "unique_ids" },
{ $set: { unique_ids: [] } },
{ multi: true, upsert: true },
function(err, docs) {}
);
db.collection("user_names").remove(
{ guid: { $exists: true } },
{ multi: true, upsert: true },
function(err, docs) {}
);
db.collection("user_names").update(
{ _id: "all_names" },
{ $set: { names: [] } },
{ multi: true, upsert: true },
function(err, docs) {}
);
db.collection("connected_users").update(
{ users: { $exists: true } },
{ $set: { users: [] } },
{ multi: true, upsert: true },
function(err, docs) {}
);
db.collection("connected_users").update(
{ _id: "total_users" },
{ $set: { total_users: [] } },
{ multi: true, upsert: true },
function(err, docs) {}
);
db.collection("frontpage_lists").update(
{ viewers: { $ne: 0 } },
{ $set: { viewers: 0 } },
{ multi: true, upsert: true },
function(err, docs) {}
);
module.exports = db;

View File

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

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 crypto = require('crypto');
var Filter = require('bad-words');
var filter = new Filter({ placeHolder: 'x'});
var Functions = require(pathThumbnails + "/handlers/functions.js");
var crypto = require("crypto");
var Filter = require("bad-words");
var filter = new Filter({ placeHolder: "x" });
/*var filter = {
clean: function(str) {
return str;
}
}*/
var projects = require(pathThumbnails + "/handlers/aggregates.js");
var db = require(pathThumbnails + '/handlers/db.js');
var db = require(pathThumbnails + "/handlers/db.js");
function password(inp, coll, guid, offline, socket) {
var sessionId = Functions.getSession(socket);
if(sessionId == "") sessionId = "empty";
if(inp !== undefined && inp !== null && inp !== "")
{
if(!inp.hasOwnProperty("password") || !inp.hasOwnProperty("channel") ||
typeof(inp.password) != "string" || typeof(inp.channel) != "string") {
var result = {
channel: {
expected: "string",
got: inp.hasOwnProperty("channel") ? typeof(inp.channel) : undefined,
},
password: {
expected: "password",
got: inp.hasOwnProperty("password") ? typeof(inp.password) : undefined,
},
};
socket.emit('update_required', result);
return;
var sessionId = Functions.getSession(socket);
if (sessionId == "") sessionId = "empty";
if (inp !== undefined && inp !== null && inp !== "") {
if (
!inp.hasOwnProperty("password") ||
!inp.hasOwnProperty("channel") ||
typeof inp.password != "string" ||
typeof inp.channel != "string"
) {
var result = {
channel: {
expected: "string",
got: inp.hasOwnProperty("channel") ? typeof inp.channel : undefined
},
password: {
expected: "password",
got: inp.hasOwnProperty("password") ? typeof inp.password : undefined
}
pw = inp.password;
try {
coll = inp.channel;
if(coll.length == 0) return;
coll = Functions.removeEmojis(coll).toLowerCase();
//coll = coll.replace(/_/g, "");
//coll = filter.clean(coll);
} catch(e) {
return;
}
//coll = coll.replace(/ /g,'');
uncrypted = pw;
pw = Functions.hash_pass(Functions.decrypt_string(pw), true);
Functions.check_inlist(coll, guid, socket, offline, undefined, "place 8");
Functions.getSessionAdminUser(sessionId, coll, function(userpass, adminpass) {
adminpass = Functions.hash_pass(adminpass);
db.collection(coll + "_settings").find(function(err, docs){
if(docs !== null && docs.length !== 0)
{
if(docs[0].adminpass === "" || docs[0].adminpass == Functions.hash_pass(pw))
{
Functions.setSessionAdminPass(sessionId, inp.password, coll, function() {
db.collection(coll + "_settings").update({ id: "config" }, {$set:{adminpass:Functions.hash_pass(pw)}}, function(err, docs){
if(adminpass != pw && adminpass != "") {
socket.emit("toast", "changedpass");
} else {
socket.emit("toast", "correctpass");
}
socket.emit("pw", true);
});
});
} else if(docs[0].adminpass === "" || docs[0].adminpass == adminpass) {
Functions.setSessionAdminPass(sessionId, inp.password, coll, function() {
db.collection(coll + "_settings").update({ id: "config" }, {$set:{adminpass:Functions.hash_pass(pw)}}, function(err, docs){
if(adminpass != pw) {
socket.emit("toast", "changedpass");
}
socket.emit("pw", true);
});
});
} else {
Functions.setSessionAdminPass(Functions.getSession(socket), "", coll, function() {
socket.emit("toast", "wrongpass");
socket.emit("pw", false);
});
}
}
});
});
} else {
var result = {
inp: {
expected: "string",
got: typeof(inpt)
},
};
socket.emit('update_required', result);
};
socket.emit("update_required", result);
return;
}
pw = inp.password;
try {
coll = inp.channel;
if (coll.length == 0) return;
coll = Functions.removeEmojis(coll).toLowerCase();
//coll = coll.replace(/_/g, "");
//coll = filter.clean(coll);
} catch (e) {
return;
}
//coll = coll.replace(/ /g,'');
uncrypted = pw;
pw = Functions.hash_pass(Functions.decrypt_string(pw), true);
Functions.check_inlist(coll, guid, socket, offline, undefined, "place 8");
Functions.getSessionAdminUser(sessionId, coll, function(
userpass,
adminpass
) {
adminpass = Functions.hash_pass(adminpass);
db.collection(coll + "_settings").find(function(err, docs) {
if (docs !== null && docs.length !== 0) {
if (
docs[0].adminpass === "" ||
docs[0].adminpass == Functions.hash_pass(pw)
) {
Functions.setSessionAdminPass(
sessionId,
inp.password,
coll,
function() {
db.collection(coll + "_settings").update(
{ id: "config" },
{ $set: { adminpass: Functions.hash_pass(pw) } },
function(err, docs) {
if (adminpass != pw && adminpass != "") {
socket.emit("toast", "changedpass");
} else {
socket.emit("toast", "correctpass");
}
socket.emit("pw", true);
}
);
}
);
} else if (
docs[0].adminpass === "" ||
docs[0].adminpass == adminpass
) {
Functions.setSessionAdminPass(
sessionId,
inp.password,
coll,
function() {
db.collection(coll + "_settings").update(
{ id: "config" },
{ $set: { adminpass: Functions.hash_pass(pw) } },
function(err, docs) {
if (adminpass != pw) {
socket.emit("toast", "changedpass");
}
socket.emit("pw", true);
}
);
}
);
} else {
Functions.setSessionAdminPass(
Functions.getSession(socket),
"",
coll,
function() {
socket.emit("toast", "wrongpass");
socket.emit("pw", false);
}
);
}
}
});
});
} else {
var result = {
inp: {
expected: "string",
got: typeof inpt
}
};
socket.emit("update_required", result);
}
}
function conf_function(params, coll, guid, offline, socket) {
if(params !== undefined && params !== null && params !== "")
{
if(coll !== undefined) {
try {
coll = params.channel;//.replace(/ /g,'');
if(coll.length == 0) return;
coll = Functions.removeEmojis(coll).toLowerCase();
//coll = coll.replace(/_/g, "");
if (params !== undefined && params !== null && params !== "") {
if (coll !== undefined) {
try {
coll = params.channel; //.replace(/ /g,'');
if (coll.length == 0) return;
coll = Functions.removeEmojis(coll).toLowerCase();
//coll = coll.replace(/_/g, "");
//coll = filter.clean(coll);
} catch(e) {
return;
}
}
if(coll == "" || coll == undefined || coll == null) {
socket.emit("update_required");
return;
}
Functions.check_inlist(coll, guid, socket, offline, undefined, "place 9");
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) {
if(gotten) {
params.adminpass = adminpass;
if(!params.userpass_changed) params.userpass = userpass;
}
if(!params.hasOwnProperty('voting') || !params.hasOwnProperty('addsongs') ||
!params.hasOwnProperty('longsongs') || !params.hasOwnProperty('frontpage') ||
!params.hasOwnProperty('allvideos') || !params.hasOwnProperty('removeplay') ||
!params.hasOwnProperty('adminpass') || !params.hasOwnProperty('skipping') ||
!params.hasOwnProperty('shuffling') || !params.hasOwnProperty('channel') ||
typeof(params.userpass) != "string" || typeof(params.adminpass) != "string" ||
typeof(params.voting) != "boolean" || typeof(params.addsongs) != "boolean" ||
typeof(params.longsongs) != "boolean" || typeof(params.frontpage) != "boolean" ||
typeof(params.allvideos) != "boolean" || typeof(params.removeplay) != "boolean" ||
typeof(params.skipping) != "boolean" || typeof(params.shuffling) != "boolean" ||
typeof(params.userpass_changed) != "boolean") {
var result = {
adminpass: {
expected: "string",
got: params.hasOwnProperty("adminpass") ? typeof(params.adminpass) : undefined,
},
userpass: {
expected: "string",
got: params.hasOwnProperty("userpass") ? typeof(params.userpass) : undefined,
},
vote: {
expected: "boolean",
got: params.hasOwnProperty("vote") ? typeof(params.vote) : undefined,
},
addsongs: {
expected: "boolean",
got: params.hasOwnProperty("addsongs") ? typeof(params.addsongs) : undefined,
},
longsongs: {
expected: "boolean",
got: params.hasOwnProperty("longsongs") ? typeof(params.longsongs) : undefined,
},
frontpage: {
expected: "boolean",
got: params.hasOwnProperty("frontpage") ? typeof(params.frontpage) : undefined,
},
skipping: {
expected: "boolean",
got: params.hasOwnProperty("skipping") ? typeof(params.skipping) : undefined,
},
shuffling: {
expected: "boolean",
got: params.hasOwnProperty("shuffling") ? typeof(params.shuffling) : undefined,
},
userpass_changed: {
expected: "boolean",
got: params.hasOwnProperty("userpass_changed") ? typeof(params.userpass_changed) : undefined,
}
};
socket.emit("update_required", result);
return;
}
var voting = params.voting;
var addsongs = params.addsongs;
var longsongs = params.longsongs;
var frontpage = params.frontpage;
var allvideos = params.allvideos;
var removeplay = params.removeplay;
var adminpass = params.adminpass;
var skipping = params.skipping;
var shuffling = params.shuffling;
var userpass = Functions.decrypt_string(params.userpass);
if((!params.userpass_changed && frontpage) || (params.userpass_changed && userpass == "")) {
userpass = "";
} else if(params.userpass_changed && userpass != "") {
frontpage = false;
}
var description = "";
var hash;
if(params.description) description = params.description;
if(adminpass !== "" && !gotten) {
hash = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(adminpass), true));
} else if(adminpass !== "" && gotten) {
hash = Functions.hash_pass(adminpass);
} else {
hash = adminpass;
}
if(userpass != "") {
if(!params.userpass_changed && gotten) {
} else {
userpass = crypto.createHash('sha256').update(userpass).digest("base64");
}
}
db.collection(coll + "_settings").find({id: "config"}, function(err, docs){
if(docs !== null && docs.length !== 0 && (docs[0].adminpass === "" || docs[0].adminpass == hash)) {
var obj = {
addsongs:addsongs,
allvideos:allvideos,
frontpage:frontpage,
skip:skipping,
vote:voting,
removeplay:removeplay,
shuffle:shuffling,
longsongs:longsongs,
adminpass:hash,
desc: description,
};
if(params.hasOwnProperty("toggleChat") && docs[0].adminpass != "" && docs[0].adminpass != undefined && docs[0].adminpass == hash) {
obj.toggleChat = params.toggleChat;
}
if(params.hasOwnProperty("strictSkip") && docs[0].adminpass != "" && docs[0].adminpass != undefined && docs[0].adminpass == hash) {
obj.strictSkip = params.strictSkip;
}
if(params.hasOwnProperty("strictSkipNumber") && docs[0].adminpass != "" && docs[0].adminpass != undefined && docs[0].adminpass == hash) {
try {
obj.strictSkipNumber = parseInt(params.strictSkipNumber);
} catch(e) {}
}
if(params.userpass_changed) {
obj["userpass"] = userpass;
} else if (frontpage) {
obj["userpass"] = "";
}
db.collection(coll + "_settings").update({ id: "config" }, {
$set:obj
}, function(err, docs){
Functions.setSessionUserPass(Functions.getSession(socket), obj["userpass"], coll, function() {
db.collection(coll + "_settings").aggregate([
{
"$match": {
id: "config"
}
},
{
"$project": projects.toShowConfig
},
], function(err, docs){
if(docs[0].adminpass !== "") docs[0].adminpass = true;
if(docs[0].hasOwnProperty("userpass") && docs[0].userpass != "") docs[0].userpass = true;
else docs[0].userpass = false;
io.to(coll).emit("conf", docs);
socket.emit("toast", "savedsettings");
db.collection("frontpage_lists").update({_id: coll}, {$set:{
frontpage:frontpage, accessed: Functions.get_time()}
},
{upsert:true}, function(err, docs){});
});
});
});
} else {
socket.emit("toast", "wrongpass");
}
});
});
} else {
var result = {
params: {
expected: "object",
got: typeof(params),
}
}
socket.emit('update_required', result);
//coll = filter.clean(coll);
} catch (e) {
return;
}
}
if (coll == "" || coll == undefined || coll == null) {
socket.emit("update_required");
return;
}
Functions.check_inlist(coll, guid, socket, offline, undefined, "place 9");
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(
userpass,
adminpass,
gotten
) {
if (gotten) {
params.adminpass = adminpass;
if (!params.userpass_changed) params.userpass = userpass;
}
if (
!params.hasOwnProperty("voting") ||
!params.hasOwnProperty("addsongs") ||
!params.hasOwnProperty("longsongs") ||
!params.hasOwnProperty("frontpage") ||
!params.hasOwnProperty("allvideos") ||
!params.hasOwnProperty("removeplay") ||
!params.hasOwnProperty("adminpass") ||
!params.hasOwnProperty("skipping") ||
!params.hasOwnProperty("shuffling") ||
!params.hasOwnProperty("channel") ||
typeof params.userpass != "string" ||
typeof params.adminpass != "string" ||
typeof params.voting != "boolean" ||
typeof params.addsongs != "boolean" ||
typeof params.longsongs != "boolean" ||
typeof params.frontpage != "boolean" ||
typeof params.allvideos != "boolean" ||
typeof params.removeplay != "boolean" ||
typeof params.skipping != "boolean" ||
typeof params.shuffling != "boolean" ||
typeof params.userpass_changed != "boolean"
) {
var result = {
adminpass: {
expected: "string",
got: params.hasOwnProperty("adminpass")
? typeof params.adminpass
: undefined
},
userpass: {
expected: "string",
got: params.hasOwnProperty("userpass")
? typeof params.userpass
: undefined
},
vote: {
expected: "boolean",
got: params.hasOwnProperty("vote") ? typeof params.vote : undefined
},
addsongs: {
expected: "boolean",
got: params.hasOwnProperty("addsongs")
? typeof params.addsongs
: undefined
},
longsongs: {
expected: "boolean",
got: params.hasOwnProperty("longsongs")
? typeof params.longsongs
: undefined
},
frontpage: {
expected: "boolean",
got: params.hasOwnProperty("frontpage")
? typeof params.frontpage
: undefined
},
skipping: {
expected: "boolean",
got: params.hasOwnProperty("skipping")
? typeof params.skipping
: undefined
},
shuffling: {
expected: "boolean",
got: params.hasOwnProperty("shuffling")
? typeof params.shuffling
: undefined
},
userpass_changed: {
expected: "boolean",
got: params.hasOwnProperty("userpass_changed")
? typeof params.userpass_changed
: undefined
}
};
socket.emit("update_required", result);
return;
}
var voting = params.voting;
var addsongs = params.addsongs;
var longsongs = params.longsongs;
var frontpage = params.frontpage;
var allvideos = params.allvideos;
var removeplay = params.removeplay;
var adminpass = params.adminpass;
var skipping = params.skipping;
var shuffling = params.shuffling;
var userpass = Functions.decrypt_string(params.userpass);
if (
(!params.userpass_changed && frontpage) ||
(params.userpass_changed && userpass == "")
) {
userpass = "";
} else if (params.userpass_changed && userpass != "") {
frontpage = false;
}
var description = "";
var hash;
if (params.description) description = params.description;
if (adminpass !== "" && !gotten) {
hash = Functions.hash_pass(
Functions.hash_pass(Functions.decrypt_string(adminpass), true)
);
} else if (adminpass !== "" && gotten) {
hash = Functions.hash_pass(adminpass);
} else {
hash = adminpass;
}
if (userpass != "") {
if (!params.userpass_changed && gotten) {
} else {
userpass = crypto
.createHash("sha256")
.update(userpass)
.digest("base64");
}
}
db.collection(coll + "_settings").find({ id: "config" }, function(
err,
docs
) {
if (
docs !== null &&
docs.length !== 0 &&
(docs[0].adminpass === "" || docs[0].adminpass == hash)
) {
var obj = {
addsongs: addsongs,
allvideos: allvideos,
frontpage: frontpage,
skip: skipping,
vote: voting,
removeplay: removeplay,
shuffle: shuffling,
longsongs: longsongs,
adminpass: hash,
desc: description
};
if (
params.hasOwnProperty("toggleChat") &&
docs[0].adminpass != "" &&
docs[0].adminpass != undefined &&
docs[0].adminpass == hash
) {
obj.toggleChat = params.toggleChat;
}
if (
params.hasOwnProperty("strictSkip") &&
docs[0].adminpass != "" &&
docs[0].adminpass != undefined &&
docs[0].adminpass == hash
) {
obj.strictSkip = params.strictSkip;
}
if (
params.hasOwnProperty("strictSkipNumber") &&
docs[0].adminpass != "" &&
docs[0].adminpass != undefined &&
docs[0].adminpass == hash
) {
try {
obj.strictSkipNumber = parseInt(params.strictSkipNumber);
} catch (e) {}
}
if (params.userpass_changed) {
obj["userpass"] = userpass;
} else if (frontpage) {
obj["userpass"] = "";
}
db.collection(coll + "_settings").update(
{ id: "config" },
{
$set: obj
},
function(err, docs) {
Functions.setSessionUserPass(
Functions.getSession(socket),
obj["userpass"],
coll,
function() {
db.collection(coll + "_settings").aggregate(
[
{
$match: {
id: "config"
}
},
{
$project: projects.toShowConfig
}
],
function(err, docs) {
if (docs[0].adminpass !== "") docs[0].adminpass = true;
if (
docs[0].hasOwnProperty("userpass") &&
docs[0].userpass != ""
)
docs[0].userpass = true;
else docs[0].userpass = false;
io.to(coll).emit("conf", docs);
socket.emit("toast", "savedsettings");
db.collection("frontpage_lists").update(
{ _id: coll },
{
$set: {
frontpage: frontpage,
accessed: Functions.get_time()
}
},
{ upsert: true },
function(err, docs) {}
);
}
);
}
);
}
);
} else {
socket.emit("toast", "wrongpass");
}
});
});
} else {
var result = {
params: {
expected: "object",
got: typeof params
}
};
socket.emit("update_required", result);
}
}
module.exports.password = password;

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,183 +1,284 @@
var Functions = require(pathThumbnails + '/handlers/functions.js');
var Notifications = require(pathThumbnails + '/handlers/notifications.js');
var crypto = require('crypto');
var db = require(pathThumbnails + '/handlers/db.js');
var Functions = require(pathThumbnails + "/handlers/functions.js");
var Notifications = require(pathThumbnails + "/handlers/notifications.js");
var crypto = require("crypto");
var db = require(pathThumbnails + "/handlers/db.js");
function thumbnail(msg, coll, guid, offline, socket) {
if(msg.thumbnail != undefined && msg.channel && msg.channel != undefined && Functions.isUrl(msg.thumbnail)){
if(typeof(msg.channel) != "string" || typeof(msg.thumbnail) != "string")
{
var result = {
channel: {
expected: "string",
got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined,
},
pass: {
expected: "string",
got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined,
},
thumbnail: {
expected: "string",
got: msg.hasOwnProperty("thumbnail") ? typeof(msg.thumbnail) : undefined,
},
adminpass: {
expected: "string",
got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined,
},
};
socket.emit("update_required", result);
return;
}
//coll = coll.replace(/ /g,'');
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) {
if(userpass != "" || msg.pass == undefined) {
msg.pass = userpass;
} else if(msg.hasOwnProperty("pass")){
msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64");
}
if(adminpass != "" || msg.adminpass == undefined) {
msg.adminpass = Functions.hash_pass(adminpass);
} else {
msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass),true));
}
if(msg.thumbnail != "") {
msg.thumbnail = msg.thumbnail.replace(/^https?\:\/\//i, "");
if(msg.thumbnail.substring(0,2) != "//") msg.thumbnail = "//" + msg.thumbnail;
}
var channel = msg.channel.toLowerCase();
var hash = msg.adminpass;
db.collection(channel + "_settings").find({id: "config"}, function(err, docs){
if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) {
if(docs !== null && docs.length !== 0 && docs[0].adminpass !== "" && docs[0].adminpass == hash){
db.collection("suggested_thumbnails").update({channel: channel}, {$set:{thumbnail: msg.thumbnail}}, {upsert:true}, function(err, docs){
Notifications.requested_change("thumbnail", msg.thumbnail, channel);
socket.emit("toast", "suggested_thumbnail");
});
}
} else {
socket.emit("auth_required");
}
});
});
} else {
socket.emit("toast", "thumbnail_denied");
if (
msg.thumbnail != undefined &&
msg.channel &&
msg.channel != undefined &&
Functions.isUrl(msg.thumbnail)
) {
if (typeof msg.channel != "string" || typeof msg.thumbnail != "string") {
var result = {
channel: {
expected: "string",
got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined
},
pass: {
expected: "string",
got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined
},
thumbnail: {
expected: "string",
got: msg.hasOwnProperty("thumbnail")
? typeof msg.thumbnail
: undefined
},
adminpass: {
expected: "string",
got: msg.hasOwnProperty("adminpass")
? typeof msg.adminpass
: undefined
}
};
socket.emit("update_required", result);
return;
}
//coll = coll.replace(/ /g,'');
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(
userpass,
adminpass
) {
if (userpass != "" || msg.pass == undefined) {
msg.pass = userpass;
} else if (msg.hasOwnProperty("pass")) {
msg.pass = crypto
.createHash("sha256")
.update(Functions.decrypt_string(msg.pass))
.digest("base64");
}
if (adminpass != "" || msg.adminpass == undefined) {
msg.adminpass = Functions.hash_pass(adminpass);
} else {
msg.adminpass = Functions.hash_pass(
Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true)
);
}
if (msg.thumbnail != "") {
msg.thumbnail = msg.thumbnail.replace(/^https?\:\/\//i, "");
if (msg.thumbnail.substring(0, 2) != "//")
msg.thumbnail = "//" + msg.thumbnail;
}
var channel = msg.channel.toLowerCase();
var hash = msg.adminpass;
db.collection(channel + "_settings").find({ id: "config" }, function(
err,
docs
) {
if (
docs.length > 0 &&
(docs[0].userpass == undefined ||
docs[0].userpass == "" ||
(msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass))
) {
if (
docs !== null &&
docs.length !== 0 &&
docs[0].adminpass !== "" &&
docs[0].adminpass == hash
) {
db.collection("suggested_thumbnails").update(
{ channel: channel },
{ $set: { thumbnail: msg.thumbnail } },
{ upsert: true },
function(err, docs) {
Notifications.requested_change(
"thumbnail",
msg.thumbnail,
channel
);
socket.emit("toast", "suggested_thumbnail");
}
);
}
} else {
socket.emit("auth_required");
}
});
});
} else {
socket.emit("toast", "thumbnail_denied");
}
}
function description(msg, coll, guid, offline, socket) {
if(msg.description && msg.channel && msg.description.length < 100){
if(typeof(msg.channel) != "string" || typeof(msg.description) != "string") {
var result = {
channel: {
expected: "string",
got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined,
},
pass: {
expected: "string",
got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined,
},
description: {
expected: "string",
got: msg.hasOwnProperty("description") ? typeof(msg.description) : undefined,
},
adminpass: {
expected: "string",
got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined,
},
};
socket.emit("update_required", result);
return;
}
//coll = coll.replace(/ /g,'');
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) {
if(userpass != "" || msg.pass == undefined) {
msg.pass = userpass;
} else if(msg.hasOwnProperty("pass")) {
msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64");
}
if(adminpass != "" || msg.adminpass == undefined) {
msg.adminpass = Functions.hash_pass(adminpass);
} else {
msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true));
}
var channel = msg.channel.toLowerCase();
var hash = msg.adminpass;
db.collection(channel + "_settings").find({id: "config"}, function(err, docs){
if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) {
if(docs !== null && docs.length !== 0 && docs[0].adminpass !== "" && docs[0].adminpass == hash){
db.collection("suggested_descriptions").update({channel: channel}, {$set:{description: msg.description}}, {upsert:true}, function(err, docs){
Notifications.requested_change("description", msg.description, channel);
socket.emit("toast", "suggested_description");
});
}
} else {
socket.emit("auth_required");
}
});
});
} else {
socket.emit("toast", "description_denied");
if (msg.description && msg.channel && msg.description.length < 100) {
if (typeof msg.channel != "string" || typeof msg.description != "string") {
var result = {
channel: {
expected: "string",
got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined
},
pass: {
expected: "string",
got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined
},
description: {
expected: "string",
got: msg.hasOwnProperty("description")
? typeof msg.description
: undefined
},
adminpass: {
expected: "string",
got: msg.hasOwnProperty("adminpass")
? typeof msg.adminpass
: undefined
}
};
socket.emit("update_required", result);
return;
}
//coll = coll.replace(/ /g,'');
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(
userpass,
adminpass,
gotten
) {
if (userpass != "" || msg.pass == undefined) {
msg.pass = userpass;
} else if (msg.hasOwnProperty("pass")) {
msg.pass = crypto
.createHash("sha256")
.update(Functions.decrypt_string(msg.pass))
.digest("base64");
}
if (adminpass != "" || msg.adminpass == undefined) {
msg.adminpass = Functions.hash_pass(adminpass);
} else {
msg.adminpass = Functions.hash_pass(
Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true)
);
}
var channel = msg.channel.toLowerCase();
var hash = msg.adminpass;
db.collection(channel + "_settings").find({ id: "config" }, function(
err,
docs
) {
if (
docs.length > 0 &&
(docs[0].userpass == undefined ||
docs[0].userpass == "" ||
(msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass))
) {
if (
docs !== null &&
docs.length !== 0 &&
docs[0].adminpass !== "" &&
docs[0].adminpass == hash
) {
db.collection("suggested_descriptions").update(
{ channel: channel },
{ $set: { description: msg.description } },
{ upsert: true },
function(err, docs) {
Notifications.requested_change(
"description",
msg.description,
channel
);
socket.emit("toast", "suggested_description");
}
);
}
} else {
socket.emit("auth_required");
}
});
});
} else {
socket.emit("toast", "description_denied");
}
}
function rules(msg, coll, guid, offline, socket) {
if(msg.rules && msg.channel && msg.rules.length < 250){
if(typeof(msg.channel) != "string" || typeof(msg.rules) != "string") {
var result = {
channel: {
expected: "string",
got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined,
},
pass: {
expected: "string",
got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined,
},
rules: {
expected: "string",
got: msg.hasOwnProperty("rules") ? typeof(msg.rules) : undefined,
},
adminpass: {
expected: "string",
got: msg.hasOwnProperty("adminpass") ? typeof(msg.adminpass) : undefined,
},
};
socket.emit("update_required", result);
return;
}
//coll = coll.replace(/ /g,'');
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) {
if(userpass != "" || msg.pass == undefined) {
msg.pass = userpass;
} else if(msg.hasOwnProperty("pass")) {
msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64");
}
if(adminpass != "" || msg.adminpass == undefined) {
msg.adminpass = Functions.hash_pass(adminpass);
} else {
msg.adminpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true));
}
var channel = msg.channel.toLowerCase();
var hash = msg.adminpass;
db.collection(channel + "_settings").find({id: "config"}, function(err, docs){
if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (msg.hasOwnProperty('pass') && docs[0].userpass == msg.pass))) {
if(docs !== null && docs.length !== 0 && docs[0].adminpass !== "" && docs[0].adminpass == hash){
db.collection("suggested_rules").update({channel: channel}, {$set:{rules: msg.rules}}, {upsert:true}, function(err, docs){
Notifications.requested_change("rules", msg.rules, channel);
socket.emit("toast", "suggested_rules");
});
}
} else {
socket.emit("auth_required");
}
});
});
} else {
socket.emit("toast", "rules_denied");
if (msg.rules && msg.channel && msg.rules.length < 250) {
if (typeof msg.channel != "string" || typeof msg.rules != "string") {
var result = {
channel: {
expected: "string",
got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined
},
pass: {
expected: "string",
got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined
},
rules: {
expected: "string",
got: msg.hasOwnProperty("rules") ? typeof msg.rules : undefined
},
adminpass: {
expected: "string",
got: msg.hasOwnProperty("adminpass")
? typeof msg.adminpass
: undefined
}
};
socket.emit("update_required", result);
return;
}
//coll = coll.replace(/ /g,'');
Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(
userpass,
adminpass,
gotten
) {
if (userpass != "" || msg.pass == undefined) {
msg.pass = userpass;
} else if (msg.hasOwnProperty("pass")) {
msg.pass = crypto
.createHash("sha256")
.update(Functions.decrypt_string(msg.pass))
.digest("base64");
}
if (adminpass != "" || msg.adminpass == undefined) {
msg.adminpass = Functions.hash_pass(adminpass);
} else {
msg.adminpass = Functions.hash_pass(
Functions.hash_pass(Functions.decrypt_string(msg.adminpass), true)
);
}
var channel = msg.channel.toLowerCase();
var hash = msg.adminpass;
db.collection(channel + "_settings").find({ id: "config" }, function(
err,
docs
) {
if (
docs.length > 0 &&
(docs[0].userpass == undefined ||
docs[0].userpass == "" ||
(msg.hasOwnProperty("pass") && docs[0].userpass == msg.pass))
) {
if (
docs !== null &&
docs.length !== 0 &&
docs[0].adminpass !== "" &&
docs[0].adminpass == hash
) {
db.collection("suggested_rules").update(
{ channel: channel },
{ $set: { rules: msg.rules } },
{ upsert: true },
function(err, docs) {
Notifications.requested_change("rules", msg.rules, channel);
socket.emit("toast", "suggested_rules");
}
);
}
} else {
socket.emit("auth_required");
}
});
});
} else {
socket.emit("toast", "rules_denied");
}
}
module.exports.thumbnail = thumbnail;
module.exports.description = description;
module.exports.rules = rules;

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,7 @@ try {
} catch (e) {
allowed_key = ["***"];
console.log(
"Allowed API-key for skipping songs from API has not been configured, so all keys are allowed by default (!). Have a look at config/allowed_api.example.js"
"(!) Missing file - /config/allowed_api.js Have a look at /config/allowed_api.example.js."
);
}
var crypto = require("crypto");

View File

@@ -1,24 +1,33 @@
var express = require('express');
const path = require('path');
var express = require("express");
const path = require("path");
var router = express.Router();
router.use(function(req, res, next) {
next(); // make sure we go to the next routes and don't stop here
next(); // make sure we go to the next routes and don't stop here
});
router.route('/favicon.ico').get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/images/favicon.ico'));
router.route("/favicon.ico").get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, "/public/assets/images/favicon.ico"));
});
router.route('/browserconfig.xml').get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/images/browserconfig.xml'));
router.route("/browserconfig.xml").get(function(req, res, next) {
res.sendFile(
path.join(pathThumbnails, "/public/assets/images/browserconfig.xml")
);
});
router.route('/apple-touch-icon.png').get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/images/apple-touch-icon.png'));
router.route("/apple-touch-icon.png").get(function(req, res, next) {
res.sendFile(
path.join(pathThumbnails, "/public/assets/images/apple-touch-icon.png")
);
});
router.route('/apple-touch-icon-precomposed.png').get(function(req, res, next) {
res.sendFile(path.join(pathThumbnails, '/public/assets/images/apple-touch-icon-precomposed.png'));
router.route("/apple-touch-icon-precomposed.png").get(function(req, res, next) {
res.sendFile(
path.join(
pathThumbnails,
"/public/assets/images/apple-touch-icon-precomposed.png"
)
);
});
module.exports = router;

View File

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