diff --git a/gulpfile.js b/gulpfile.js index f28d14d1..1ed3afd2 100755 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,120 +1,198 @@ -var gulp = require('gulp'), - gutil = require('gulp-util'), - uglify = require('gulp-uglify'), - //sourcemaps = require('gulp-sourcemaps'), - gutil = require('gulp-util'), - concat = require('gulp-concat'), - cssnano = require('gulp-cssnano'); +var gulp = require("gulp"), + gutil = require("gulp-util"), + uglify = require("gulp-uglify"), + //sourcemaps = require('gulp-sourcemaps'), + gutil = require("gulp-util"), + concat = require("gulp-concat"), + cleanCSS = require("gulp-clean-css"); -gulp.task('css', function() { - return gulp.src('server/public/assets/css/style.css') - .pipe(cssnano({ - preset: ['default', { - discardComments: { - removeAll: true, - }, - }] - })) - .pipe(gulp.dest('server/public/assets/dist')); +gulp.task("css", function() { + return gulp + .src("server/public/assets/css/style.css") + .pipe(cleanCSS({ compatibility: "ie8" })) + .pipe(gulp.dest("server/public/assets/dist")); }); -gulp.task('css-embed', function() { - return gulp.src('server/public/assets/css/embed.css') - .pipe(cssnano({ - preset: ['default', { - discardComments: { - removeAll: true, - }, - }] - })) - .pipe(gulp.dest('server/public/assets/dist')); +gulp.task("css-embed", function() { + return gulp + .src("server/public/assets/css/embed.css") + .pipe(cleanCSS({ compatibility: "ie8" })) + .pipe(gulp.dest("server/public/assets/dist")); }); -gulp.task('js', function () { - return gulp.src(['server/VERSION.js', 'server/config/api_key.js', 'server/public/assets/js/*.js', '!server/public/assets/js/embed*', '!server/public/assets/js/token*', '!server/public/assets/js/remotecontroller.js', '!server/public/assets/js/callback.js']) - //.pipe(sourcemaps.init()) - .pipe(concat('main.min.js')) - .pipe(uglify({ - mangle: true, - compress: true, - enclose: true, - })) - .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); }) - //.pipe(sourcemaps.write('maps')) - .pipe(gulp.dest('server/public/assets/dist')); +gulp.task("js", function() { + return ( + gulp + .src([ + "server/VERSION.js", + "server/config/api_key.js", + "server/public/assets/js/*.js", + "!server/public/assets/js/embed*", + "!server/public/assets/js/token*", + "!server/public/assets/js/remotecontroller.js", + "!server/public/assets/js/callback.js" + ]) + //.pipe(sourcemaps.init()) + .pipe(concat("main.min.js")) + .pipe( + uglify({ + mangle: true, + compress: true, + enclose: true + }) + ) + .on("error", function(err) { + gutil.log(gutil.colors.red("[Error]"), err.toString()); + }) + //.pipe(sourcemaps.write('maps')) + .pipe(gulp.dest("server/public/assets/dist")) + ); }); -gulp.task('embed', function () { - return gulp.src(['server/VERSION.js', 'server/config/api_key.js', 'server/public/assets/js/player.js', 'server/public/assets/js/functions.js', 'server/public/assets/js/helpers.js', 'server/public/assets/js/playercontrols.js', 'server/public/assets/js/list.js', 'server/public/assets/js/embed.js', '!server/public/assets/js/frontpage*', '!server/public/assets/js/remotecontroller.js', 'server/public/assets/js/hostcontroller.js']) - //.pipe(sourcemaps.init()) - .pipe(concat('embed.min.js')) - .pipe(uglify({ - mangle: true, - compress: true, - enclose: true - })) - .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); }) - //.pipe(sourcemaps.write('maps')) - .pipe(gulp.dest('server/public/assets/dist')); +gulp.task("embed", function() { + return ( + gulp + .src([ + "server/VERSION.js", + "server/config/api_key.js", + "server/public/assets/js/player.js", + "server/public/assets/js/functions.js", + "server/public/assets/js/helpers.js", + "server/public/assets/js/playercontrols.js", + "server/public/assets/js/list.js", + "server/public/assets/js/embed.js", + "!server/public/assets/js/frontpage*", + "!server/public/assets/js/remotecontroller.js", + "server/public/assets/js/hostcontroller.js" + ]) + //.pipe(sourcemaps.init()) + .pipe(concat("embed.min.js")) + .pipe( + uglify({ + mangle: true, + compress: true, + enclose: true + }) + ) + .on("error", function(err) { + gutil.log(gutil.colors.red("[Error]"), err.toString()); + }) + //.pipe(sourcemaps.write('maps')) + .pipe(gulp.dest("server/public/assets/dist")) + ); }); -gulp.task('token', function() { - return gulp.src(['server/public/assets/js/token*', 'server/public/assets/js/helpers.js']) - //.pipe(sourcemaps.init()) - .pipe(concat('token.min.js')) - .pipe(uglify({ - mangle: true, - compress: true, - enclose: true - })) - .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); }) +gulp.task("token", function() { + return ( + gulp + .src([ + "server/public/assets/js/token*", + "server/public/assets/js/helpers.js" + ]) + //.pipe(sourcemaps.init()) + .pipe(concat("token.min.js")) + .pipe( + uglify({ + mangle: true, + compress: true, + enclose: true + }) + ) + .on("error", function(err) { + gutil.log(gutil.colors.red("[Error]"), err.toString()); + }) - //.pipe(sourcemaps.write('maps')) - .pipe(gulp.dest('server/public/assets/dist')); -}) - -gulp.task('callback', function () { - return gulp.src(['server/VERSION.js', 'server/config/api_key.js', 'server/public/assets/js/callback.js']) - //.pipe(sourcemaps.init()) - .pipe(concat('callback.min.js')) - .pipe(uglify({ - mangle: true, - compress: true, - enclose: true - })) - .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); }) - - //.pipe(sourcemaps.write('maps')) - .pipe(gulp.dest('server/public/assets/dist')); + //.pipe(sourcemaps.write('maps')) + .pipe(gulp.dest("server/public/assets/dist")) + ); }); -gulp.task('build', done => { - gulp.series('css', 'css-embed', 'js', 'embed', 'remotecontroller', 'callback', 'token')(); - done(); +gulp.task("callback", function() { + return ( + gulp + .src([ + "server/VERSION.js", + "server/config/api_key.js", + "server/public/assets/js/callback.js" + ]) + //.pipe(sourcemaps.init()) + .pipe(concat("callback.min.js")) + .pipe( + uglify({ + mangle: true, + compress: true, + enclose: true + }) + ) + .on("error", function(err) { + gutil.log(gutil.colors.red("[Error]"), err.toString()); + }) + + //.pipe(sourcemaps.write('maps')) + .pipe(gulp.dest("server/public/assets/dist")) + ); }); -gulp.task('remotecontroller', function () { - return gulp.src(['server/VERSION.js', 'server/config/api_key.js', 'server/public/assets/js/remotecontroller.js', 'server/public/assets/js/helpers.js']) - ////.pipe(sourcemaps.init()) - .pipe(concat('remote.min.js')) - .pipe(uglify({ - mangle: true, - compress: true, - enclose: true - })) - .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); }) - - //.pipe(sourcemaps.write('maps')) - .pipe(gulp.dest('server/public/assets/dist')); +gulp.task("build", done => { + gulp.series( + "css", + "css-embed", + "js", + "embed", + "remotecontroller", + "callback", + "token" + )(); + done(); }); -gulp.task('default', function(){ - gulp.watch(['server/VERSION.js', 'server/public/assets/js/*.js'], ['js']); - gulp.watch(['server/public/assets/css/*.css'], ['css']); - gulp.watch(['server/public/assets/css/*.css'], ['css-embed']); - gulp.watch(['server/public/assets/js/token*.js', 'server/public/assets/js/helpers.js'], ['token']); - gulp.watch(['server/VERSION.js', 'server/public/assets/js/*.js'], ['embed']); - gulp.watch(['server/VERSION.js', 'server/public/assets/js/callback.js', 'server/public/assets/js/helpers.js'], ['callback']); - //gulp.watch('server/public/assets/js/*.js', ['nochan']); - gulp.watch(['server/VERSION.js', 'server/public/assets/js/remotecontroller.js'], ['remotecontroller']); +gulp.task("remotecontroller", function() { + return ( + gulp + .src([ + "server/VERSION.js", + "server/config/api_key.js", + "server/public/assets/js/remotecontroller.js", + "server/public/assets/js/helpers.js" + ]) + ////.pipe(sourcemaps.init()) + .pipe(concat("remote.min.js")) + .pipe( + uglify({ + mangle: true, + compress: true, + enclose: true + }) + ) + .on("error", function(err) { + gutil.log(gutil.colors.red("[Error]"), err.toString()); + }) + + //.pipe(sourcemaps.write('maps')) + .pipe(gulp.dest("server/public/assets/dist")) + ); +}); + +gulp.task("default", function() { + gulp.watch(["server/VERSION.js", "server/public/assets/js/*.js"], ["js"]); + gulp.watch(["server/public/assets/css/*.css"], ["css"]); + gulp.watch(["server/public/assets/css/*.css"], ["css-embed"]); + gulp.watch( + ["server/public/assets/js/token*.js", "server/public/assets/js/helpers.js"], + ["token"] + ); + gulp.watch(["server/VERSION.js", "server/public/assets/js/*.js"], ["embed"]); + gulp.watch( + [ + "server/VERSION.js", + "server/public/assets/js/callback.js", + "server/public/assets/js/helpers.js" + ], + ["callback"] + ); + //gulp.watch('server/public/assets/js/*.js', ['nochan']); + gulp.watch( + ["server/VERSION.js", "server/public/assets/js/remotecontroller.js"], + ["remotecontroller"] + ); }); diff --git a/package-lock.json b/package-lock.json index d75b50c5..f867e7c2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -750,6 +750,14 @@ } } }, + "clean-css": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.2.1.tgz", + "integrity": "sha512-4ZxI6dy4lrY6FHzfiy1aEOXgu4LIsW2MhwG0VBKdcoGoH/XLFgaHSdLTGr4O8Be6A8r3MOphEiI8Gc1n0ecf3g==", + "requires": { + "source-map": "~0.6.0" + } + }, "cliui": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", @@ -2899,6 +2907,45 @@ } } }, + "gulp-clean-css": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/gulp-clean-css/-/gulp-clean-css-4.2.0.tgz", + "integrity": "sha512-r4zQsSOAK2UYUL/ipkAVCTRg/2CLZ2A+oPVORopBximRksJ6qy3EX1KGrIWT4ZrHxz3Hlobb1yyJtqiut7DNjA==", + "requires": { + "clean-css": "4.2.1", + "plugin-error": "1.0.1", + "through2": "3.0.1", + "vinyl-sourcemaps-apply": "0.2.1" + }, + "dependencies": { + "readable-stream": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", + "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "string_decoder": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.2.0.tgz", + "integrity": "sha512-6YqyX6ZWEYguAxgZzHGL7SsCeGx3V2TtOTqZz1xSTSWnqsbWwbptafNyvf/ACquZUXV3DANr5BDIwNYe1mN42w==", + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "through2": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/through2/-/through2-3.0.1.tgz", + "integrity": "sha512-M96dvTalPT3YbYLaKaCuwu+j06D/8Jfib0o/PxbVt6Amhv3dUAtW6rTV1jPgJSBG83I/e04Y6xkVdVhSRhi0ww==", + "requires": { + "readable-stream": "2 || 3" + } + } + } + }, "gulp-concat": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/gulp-concat/-/gulp-concat-2.6.1.tgz", @@ -3850,6 +3897,11 @@ "strip-bom": "^2.0.0" } }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + }, "lodash._basecopy": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", @@ -4150,9 +4202,9 @@ "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=" }, "mixin-deep": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", - "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", + "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", "dev": true, "requires": { "for-in": "^1.0.2", @@ -4324,11 +4376,6 @@ "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz", "integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==" }, - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" - }, "mongodb": { "version": "3.1.13", "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.13.tgz", @@ -5835,9 +5882,9 @@ "dev": true }, "set-value": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", - "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", + "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", "dev": true, "requires": { "extend-shallow": "^2.0.1", @@ -6647,38 +6694,15 @@ "dev": true }, "union-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", - "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", + "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", "dev": true, "requires": { "arr-union": "^3.1.0", "get-value": "^2.0.6", "is-extendable": "^0.1.1", - "set-value": "^0.4.3" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "^0.1.0" - } - }, - "set-value": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", - "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", - "dev": true, - "requires": { - "extend-shallow": "^2.0.1", - "is-extendable": "^0.1.1", - "is-plain-object": "^2.0.1", - "to-object-path": "^0.3.0" - } - } + "set-value": "^2.0.1" } }, "uniq": { diff --git a/package.json b/package.json index c128f80b..532ee0d8 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "express-recaptcha": "^3.0.1", "express-session": "^1.15.6", "feature-policy": "^0.2.0", + "gulp-clean-css": "^4.2.0", "gulp-sourcemaps": "^2.6.5", "gulp-uglify-es": "^1.0.4", "helmet": "^3.16.0", diff --git a/server/handlers/io.js b/server/handlers/io.js index 32b18ff4..a1b6bccb 100644 --- a/server/handlers/io.js +++ b/server/handlers/io.js @@ -1,734 +1,924 @@ var cookieParser = require("cookie-parser"); var cookie = require("cookie"); -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var ListChange = require(pathThumbnails + '/handlers/list_change.js'); -var Chat = require(pathThumbnails + '/handlers/chat.js'); -var List = require(pathThumbnails + '/handlers/list.js'); -var Suggestions = require(pathThumbnails + '/handlers/suggestions.js'); -var ListSettings = require(pathThumbnails + '/handlers/list_settings.js'); -var Frontpage = require(pathThumbnails + '/handlers/frontpage.js'); -var Search = require(pathThumbnails + '/handlers/search.js'); -var crypto = require('crypto'); -var Filter = require('bad-words'); -var filter = new Filter({ placeHolder: 'x'}); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var ListChange = require(pathThumbnails + "/handlers/list_change.js"); +var Chat = require(pathThumbnails + "/handlers/chat.js"); +var List = require(pathThumbnails + "/handlers/list.js"); +var Suggestions = require(pathThumbnails + "/handlers/suggestions.js"); +var ListSettings = require(pathThumbnails + "/handlers/list_settings.js"); +var Frontpage = require(pathThumbnails + "/handlers/frontpage.js"); +var Search = require(pathThumbnails + "/handlers/search.js"); +var crypto = require("crypto"); +var Filter = require("bad-words"); +var filter = new Filter({ placeHolder: "x" }); /*var filter = { clean: function(str) { return str; } }*/ -var db = require(pathThumbnails + '/handlers/db.js'); +var db = require(pathThumbnails + "/handlers/db.js"); module.exports = function() { - io.on('connection', function(socket){ - try { - var parsedCookies = cookie.parse(socket.handshake.headers.cookie); - socket.cookie_id = parsedCookies["_uI"]; - //return socket.guid; - } catch(e) { - socket.cookie_id = "empty"; - } - socket.zoff_id = socket.id; - socket.emit("get_list"); + io.on("connection", function(socket) { + try { + var parsedCookies = cookie.parse(socket.handshake.headers.cookie); + socket.cookie_id = parsedCookies["_uI"]; + //return socket.guid; + } catch (e) { + socket.cookie_id = "empty"; + } + socket.zoff_id = socket.id; + socket.emit("get_list"); + var guid = socket.cookie_id; + if (guid == "empty" || guid == null || guid == undefined) + guid = Functions.hash_pass( + socket.handshake.headers["user-agent"] + + socket.handshake.address + + socket.handshake.headers["accept-language"] + ); - var guid = socket.cookie_id; - if(guid == "empty" || guid == null || guid == undefined) guid = Functions.hash_pass(socket.handshake.headers["user-agent"] + socket.handshake.address + socket.handshake.headers["accept-language"]); - - socket.guid = guid; - socket.on('close', function() { - }); - - socket.on('pinging', function() { - socket.emit("ok"); - }); - - var ping_timeout; - var socketid = socket.zoff_id; - var coll; - var in_list = false; - var name = ""; - var short_id; - Chat.get_name(guid, {announce: false, socket: socket}); - var offline = false; - var chromecast_object = false; - - socket.emit("guid", guid); - - socket.on('self_ping', function(msg) { - - var channel = msg.channel; - if(channel.indexOf("?") > -1){ - channel = channel.substring(0, channel.indexOf("?")); - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - //channel = channel.replace(/ /g,''); - if(offline) { - db.collection("connected_users").update({"_id": "offline_users"}, {$addToSet: {users: guid}}, {upsert: true}, function(err, docs){}); - } else { - db.collection("connected_users").update({"_id": channel}, {$addToSet: {users: guid}}, {upsert: true}, function(err, docs){ - db.collection("frontpage_lists").update({"_id": channel}, {$inc: {viewers: 1}}, {upsert: true}, function(){}); - }); - } - if(channel != "" && channel != undefined) { - db.collection("connected_users").update({"_id": "total_users"}, {$addToSet: {total_users: guid + channel}}, {upsert: true}, function(err, docs){}); - } - }); - - socket.on("logout", function() { - Functions.removeSessionAdminPass(Functions.getSession(socket), coll, function() {}) - }); - - socket.on('next_song', function(obj) { - if(obj == undefined || !obj.hasOwnProperty("channel")) return; - db.collection(obj.channel + "_settings").find(function(e, docs) { - if(docs.length == 0) return; - var pass = ""; - if(obj.hasOwnProperty("pass")) { - pass = crypto.createHash('sha256').update(Functions.decrypt_string(obj.pass)).digest("base64"); - } - if((docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || docs[0].userpass == pass))) { - List.getNextSong(obj.channel, socket); - } - }); - }); - - socket.on('chromecast', function(msg) { - try { - if(typeof(msg) == "object" && msg.hasOwnProperty("guid") && - msg.hasOwnProperty("socket_id") && msg.hasOwnProperty("channel") && typeof(msg.guid) == "string" && - typeof(msg.channel) == "string" && typeof(msg.socket_id) == "string" && msg.channel != "") { - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - db.collection("connected_users").find({"_id": msg.channel}, function(err, connected_users_channel) { - if(connected_users_channel.length > 0 && connected_users_channel[0].users.indexOf(msg.guid) > -1) { - coll = msg.channel.toLowerCase();//.replace(/ /g,''); - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - if(coll.indexOf("?") > -1){ - coll = coll.substring(0, coll.indexOf("?")); - } - Functions.setChromecastHost(socket.cookie_id, msg.socket_id, msg.channel, function(results) { - }); - //socket.cookie_id = msg.guid; - guid = msg.guid; - socketid = msg.socket_id; - socket.zoff_id = socketid; - - in_list = true; - chromecast_object = true; - socket.join(coll); - } - }); - } - } catch(e) { - return; - } - }); - - socket.on("get_id", function() { - socket.emit("id_chromecast", {cookie_id: Functions.getSession(socket), guid: guid}); - }); - - socket.on("error_video", function(msg) { - try { - msg.channel = Functions.encodeChannelName(msg.channel); - var _list = msg.channel;//.replace(/ /g,''); - if(_list.length == 0) return; - if(_list.indexOf("?") > -1){ - _list = _list.substring(0, _list.indexOf("?")); - msg.channel = _list; - } - coll = Functions.removeEmojis(_list).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - Search.check_error_video(msg, coll); - }); - - socket.on("get_spread", function(){ - db.collection("connected_users").find({"_id": "total_users"}, function(err, tot) { - db.collection("connected_users").find({"_id": "offline_users"}, function(err, off) { - db.collection("connected_users").find({"_id": {$ne: "total_users"}, "_id": {$ne: "offline_users"}}, function(err, users_list) { - if(tot.length > 0 && off.length == 0) { - socket.emit("spread_listeners", {offline: 0, total: tot[0].total_users.length, online_users: users_list}); - } else if(tot.length > 0 && off.length > 0){ - socket.emit("spread_listeners", {offline: off[0].users.length, total: tot[0].total_users.length, online_users: users_list}); - } - }); - }); - }); - }); - - socket.on('suggest_thumbnail', function(msg){ - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - Suggestions.thumbnail(msg, coll, guid, offline, socket); - }); - - socket.on('suggest_description', function(msg){ - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - Suggestions.description(msg, coll, guid, offline, socket); - }); - - socket.on('suggest_rules', function(msg){ - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - Suggestions.rules(msg, coll, guid, offline, socket); - }); - - socket.on("namechange", function(msg) { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - Chat.namechange(msg, guid, socket); - }); - - socket.on("removename", function(msg) { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - if(typeof(msg) != "object" || !msg.hasOwnProperty("channel")) { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - } - }; - socket.emit('update_required', result); - return; - } - Chat.removename(guid, msg.channel, socket); - }); - - socket.on("offline", function(msg){ - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - if(!msg.hasOwnProperty('status') || !msg.hasOwnProperty('channel') || - typeof(msg.status) != "boolean" || typeof(msg.channel) != "string") { - var result = { - status: { - expected: "boolean", - got: msg.hasOwnProperty("status") ? typeof(msg.status) : undefined, - }, - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined - } - }; - socket.emit('update_required', result); - return; - } - var status = msg.status; - var channel = Functions.encodeChannelName(msg.channel);//.replace(/ /g,''); - if(status){ - in_list = false; - offline = true; - if(channel != "") coll = channel; - if(coll !== undefined) { - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - db.collection("connected_users").findAndModify({ - query: {"_id": coll}, - update: {$pull: {users: guid}}, - upsert: true, - }, function(err, updated, d) { - if(d.n == 1) { - var num = 0; - if(updated && updated.users) { - num = updated.users.length; - } - io.to(coll).emit("viewers", num); - db.collection("frontpage_lists").update({"_id": coll, "viewers": {$gt: 0}}, {$inc: {viewers: -1}}, function(err, docs) { }); - db.collection("connected_users").update({"_id": "total_users"}, {$pull: {total_users: guid + coll}}, function(err, docs){ - db.collection("connected_users").update({"_id": "offline_users"}, {$addToSet: {users: guid}}, {upsert: true}, function(err, docs) { - if(docs.nModified == 1 && (coll != undefined && coll != "")) { - db.collection("connected_users").update({"_id": "total_users"}, {$addToSet: {total_users: guid + coll}}, function(err, docs) {}); - } - }); - }); - } - Functions.remove_name_from_db(guid, coll); - }); - } - - Functions.remove_unique_id(short_id); - } else { - offline = false; - db.collection("connected_users").update({"_id": "offline_users"}, {$pull: {users: guid}}, function(err, docs) { - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 3"); - }); - } - }); - - socket.on('get_history', function(msg) { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - if(!msg.hasOwnProperty("channel") || !msg.hasOwnProperty("all") || - typeof(msg.channel) != "string" || typeof(msg.all) != "boolean") { - var result = { - all: { - expected: "boolean", - got: msg.hasOwnProperty("all") ? typeof(msg.all) : undefined, - }, - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - } - }; - socket.emit('update_required', result); - return; - } - Chat.get_history(msg.channel, msg.all, socket); - }); - - socket.on('chat', function (msg) { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - Chat.chat(msg, guid, offline, socket); - }); - - socket.on("all,chat", function(data) - { - if(data.hasOwnProperty("channel") && data.channel.indexOf("?") > -1){ - var _list = data.channel.substring(0, data.channel.indexOf("?")); - data.channel = _list; - } - if(data.hasOwnProperty("channel")) { - data.channel = Functions.encodeChannelName(data.channel); - } - Chat.all_chat(data, guid, offline, socket); - }); - - socket.on('frontpage_lists', function(msg) - { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - Frontpage.frontpage_lists(msg, socket); - }); - - socket.on('import_zoff', function(msg) { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - ListChange.addFromOtherList(msg, guid, offline, socket); - }) - - socket.on('now_playing', function(list, fn) - { - List.now_playing(list, fn, socket); - }); - - socket.on('id', function(arr) - { - if(arr.hasOwnProperty("channel") && arr.channel.indexOf("?") > -1){ - var _list = arr.channel.substring(0, arr.channel.indexOf("?")); - arr.channel = _list; - } - if(arr.hasOwnProperty("channel")) { - arr.channel = Functions.encodeChannelName(arr.channel); - } - if(typeof(arr) == 'object') - io.to(arr.id).emit(arr.id.toLowerCase(), {type: arr.type, value: arr.value}); - }); - - socket.on('list', function(msg) - { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - try { - //var _list = msg.channel.replace(/ /g,''); - var _list = msg.channel; - if(_list.length == 0) return; - if(_list.indexOf("?") > -1){ - _list = _list.substring(0, _list.indexOf("?")); - msg.channel = _list; - } - coll = Functions.removeEmojis(_list).toLowerCase(); - //coll = coll.replace(/_/g, ""); - // - //coll = filter.clean(coll); - } catch(e) { - return; - } - - if(msg.hasOwnProperty("offline") && msg.offline) { - offline = true; - } - List.list(msg, guid, coll, offline, socket); - Functions.get_short_id(socket); - }); - - socket.on('end', function(obj) - { - if(obj.hasOwnProperty("channel") && obj.channel.indexOf("?") > -1){ - var _list = obj.channel.substring(0, obj.channel.indexOf("?")); - obj.channel = _list; - } - if(obj.hasOwnProperty("channel")) { - obj.channel = Functions.encodeChannelName(obj.channel); - try { - coll = obj.channel.toLowerCase();//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - } - - List.end(obj, coll, guid, offline, socket); - }); - - socket.on('addPlaylist', function(arr) { - if(arr.hasOwnProperty("channel") && arr.channel.indexOf("?") > -1){ - var _list = arr.channel.substring(0, arr.channel.indexOf("?")); - arr.channel = _list; - } - if(arr.hasOwnProperty("channel")) { - arr.channel = Functions.encodeChannelName(arr.channel); - } - ListChange.addPlaylist(arr, guid, offline, socket); - }) - - socket.on('add', function(arr) - { - if(arr.hasOwnProperty("list") && arr.list.indexOf("?") > -1){ - var _list = arr.list.substring(0, arr.list.indexOf("?")); - arr.list = _list; - } - if(arr.hasOwnProperty("list")) { - arr.list = Functions.encodeChannelName(arr.list); - } - if(coll !== undefined && ((arr.hasOwnProperty("offsiteAdd") && !arr.offsiteAdd) || !arr.hasOwnProperty("offsiteAdd"))) { - try { - coll = arr.list;//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - } else if(arr.hasOwnProperty("offsiteAdd") && arr.offsiteAdd) { - arr.list = Functions.removeEmojis(arr.list).toLowerCase(); - } - ListChange.add_function(arr, coll, guid, offline, socket); - }); - - socket.on('delete_all', function(msg) { - try { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - coll = msg.channel.toLowerCase();//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - - ListChange.delete_all(msg, coll, guid, offline, socket); - }); - - socket.on('vote', function(msg) - { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - if(coll !== undefined) { - try { - coll = msg.channel.toLowerCase();//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - } - ListChange.voteUndecided(msg, coll, guid, offline, socket); - }); - - socket.on('password', function(inp) - { - if(inp.hasOwnProperty("channel") && inp.channel.indexOf("?") > -1){ - var _list = inp.channel.substring(0, inp.channel.indexOf("?")); - inp.channel = _list; - } - if(inp.hasOwnProperty("channel")) { - inp.channel = Functions.encodeChannelName(inp.channel); - } - //if(coll != undefined) coll.replace(/ /g,''); - ListSettings.password(inp, coll, guid, offline, socket); - }); - - socket.on('skip', function(list) - { - if(list.hasOwnProperty("channel") && list.channel.indexOf("?") > -1){ - var _list = list.channel.substring(0, list.channel.indexOf("?")); - list.channel = _list; - coll = list.channel; - } - if(list.hasOwnProperty("channel")) { - list.channel = Functions.encodeChannelName(list.channel); - } - //if(coll != undefined) coll.replace(/ /g,''); - List.skip(list, guid, coll, offline, socket); - }); - - socket.on('conf', function(conf) - { - if(conf.hasOwnProperty("channel") && conf.channel.indexOf("?") > -1){ - var _list = conf.channel.substring(0, conf.channel.indexOf("?")); - conf.channel = _list; - coll = conf.channel; - } - if(conf.hasOwnProperty("channel")) { - conf.channel = Functions.encodeChannelName(conf.channel); - coll = conf.channel; - } - //if(coll != undefined) coll.replace(/ /g,''); - ListSettings.conf_function(conf, coll, guid, offline, socket); - }); - - socket.on('shuffle', function(msg) - { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - try { - coll = msg.channel.toLowerCase();//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - - ListChange.shuffle(msg, coll, guid, offline, socket); - }); - - socket.on('change_channel', function(obj) - { - if(obj == undefined && coll != undefined) { - obj = {}; - obj.channel = coll; - } else if(obj != undefined && obj.hasOwnProperty("channel") && obj.channel.indexOf("?") > -1){ - var _list = obj.channel.substring(0, obj.channel.indexOf("?")); - obj.channel = _list; - } - if(obj == undefined && coll == undefined) { - return; - } - if(obj.hasOwnProperty("channel")) { - obj.channel = Functions.encodeChannelName(obj.channel); - } - if(coll === undefined && obj !== undefined && obj.channel !== undefined){ - try { - coll = obj.channel.toLowerCase();//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - } - Functions.left_channel(coll, guid, short_id, in_list, socket, true, "left 1"); - in_list = false; - }); - - socket.on('disconnect', function() - { - Functions.left_channel(coll, guid, short_id, in_list, socket, false, "left 2"); - }); - - socket.on('disconnected', function() - { - Functions.left_channel(coll, guid, short_id, in_list, socket, false, "left 3"); - }); - - socket.on("left_channel", function(msg) { - if(msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1){ - var _list = msg.channel.substring(0, msg.channel.indexOf("?")); - msg.channel = _list; - } - if(msg.hasOwnProperty("channel")) { - msg.channel = Functions.encodeChannelName(msg.channel); - } - if(msg.hasOwnProperty("channel") && msg.channel != "" && typeof(msg.channel) == "string") { - coll = msg.channel;//.replace(/ /g,''); - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - Functions.left_channel(coll, guid, short_id, in_list, socket, false, "left 4"); - } - }) - - socket.on('reconnect_failed', function() - { - Functions.left_channel(coll, guid, short_id, in_list, socket, false, "left 5"); - }); - - socket.on('connect_timeout', function() - { - Functions.left_channel(coll, guid, short_id, in_list, socket, false, "left 6"); - }); - - socket.on('error', function() - { - Functions.left_channel(coll, guid, short_id, in_list, socket, false, "left 7"); - }); - - socket.on('pos', function(obj) - { - if(obj != undefined && obj.hasOwnProperty("channel") && obj.channel.indexOf("?") > -1){ - var _list = obj.channel.substring(0, obj.channel.indexOf("?")); - obj.channel = _list; - } - if(obj != undefined && obj.hasOwnProperty("channel")) { - obj.channel = Functions.encodeChannelName(obj.channel); - } - if(obj == undefined && coll == undefined) { - return; - } - if(coll !== undefined) { - try { - coll = obj.channel.toLowerCase();//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); - - //coll = filter.clean(coll); - } catch(e) { - return; - } - } - - if(!obj.hasOwnProperty("channel") || typeof(obj.channel) != "string") { - var result = { - channel: { - expected: "string", - got: obj.hasOwnProperty("channel") ? typeof(obj.channel) : undefined - }, - pass: { - expected: "string", - got: obj.hasOwnProperty("pass") ? typeof(obj.pass) : undefined - } - }; - socket.emit('update_required', result); - return; - } - if(coll == undefined) return; - db.collection(coll + "_settings").find(function(err, docs) { - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { - if(userpass != "" || obj.pass == undefined) { - obj.pass = userpass; - } else { - obj.pass = crypto.createHash('sha256').update(Functions.decrypt_string(obj.pass)).digest("base64") - } - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (obj.hasOwnProperty('pass') && docs[0].userpass == obj.pass))) { - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 4"); - List.send_play(coll, socket); - } else { - socket.emit("auth_required"); - } - }); - }); - }); + socket.guid = guid; + socket.on("close", function() {}); + socket.on("pinging", function() { + socket.emit("ok"); }); - //send_ping(); -} + var ping_timeout; + var socketid = socket.zoff_id; + var coll; + var in_list = false; + var name = ""; + var short_id; + Chat.get_name(guid, { announce: false, socket: socket }); + var offline = false; + var chromecast_object = false; + socket.emit("guid", guid); + + socket.on("self_ping", function(msg) { + var channel = msg.channel; + if (channel.indexOf("?") > -1) { + channel = channel.substring(0, channel.indexOf("?")); + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + //channel = channel.replace(/ /g,''); + if (offline) { + db.collection("connected_users").update( + { _id: "offline_users" }, + { $addToSet: { users: guid } }, + { upsert: true }, + function(err, docs) {} + ); + } else { + db.collection("connected_users").update( + { _id: channel }, + { $addToSet: { users: guid } }, + { upsert: true }, + function(err, docs) { + db.collection("frontpage_lists").update( + { _id: channel }, + { $inc: { viewers: 1 } }, + { upsert: true }, + function() {} + ); + } + ); + } + if (channel != "" && channel != undefined) { + db.collection("connected_users").update( + { _id: "total_users" }, + { $addToSet: { total_users: guid + channel } }, + { upsert: true }, + function(err, docs) {} + ); + } + }); + + socket.on("logout", function() { + Functions.removeSessionAdminPass( + Functions.getSession(socket), + coll, + function() {} + ); + }); + + socket.on("next_song", function(obj) { + if (obj == undefined || !obj.hasOwnProperty("channel")) return; + db.collection(obj.channel + "_settings").find(function(e, docs) { + if (docs.length == 0) return; + var pass = ""; + if (obj.hasOwnProperty("pass")) { + pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(obj.pass)) + .digest("base64"); + } + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + docs[0].userpass == pass) + ) { + List.getNextSong(obj.channel, socket); + } + }); + }); + + socket.on("chromecast", function(msg) { + try { + if ( + typeof msg == "object" && + msg.hasOwnProperty("guid") && + msg.hasOwnProperty("socket_id") && + msg.hasOwnProperty("channel") && + typeof msg.guid == "string" && + typeof msg.channel == "string" && + typeof msg.socket_id == "string" && + msg.channel != "" + ) { + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + db.collection("connected_users").find({ _id: msg.channel }, function( + err, + connected_users_channel + ) { + if ( + connected_users_channel.length > 0 && + connected_users_channel[0].users.indexOf(msg.guid) > -1 + ) { + coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + if (coll.indexOf("?") > -1) { + coll = coll.substring(0, coll.indexOf("?")); + } + Functions.setChromecastHost( + socket.cookie_id, + msg.socket_id, + msg.channel, + function(results) {} + ); + //socket.cookie_id = msg.guid; + guid = msg.guid; + socketid = msg.socket_id; + socket.zoff_id = socketid; + + in_list = true; + chromecast_object = true; + socket.join(coll); + } + }); + } + } catch (e) { + return; + } + }); + + socket.on("get_id", function() { + socket.emit("id_chromecast", { + cookie_id: Functions.getSession(socket), + guid: guid + }); + }); + + socket.on("error_video", function(msg) { + try { + msg.channel = Functions.encodeChannelName(msg.channel); + var _list = msg.channel; //.replace(/ /g,''); + if (_list.length == 0) return; + if (_list.indexOf("?") > -1) { + _list = _list.substring(0, _list.indexOf("?")); + msg.channel = _list; + } + coll = Functions.removeEmojis(_list).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + Search.check_error_video(msg, coll); + }); + + socket.on("get_spread", function() { + db.collection("connected_users").find({ _id: "total_users" }, function( + err, + tot + ) { + db.collection("connected_users").find( + { _id: "offline_users" }, + function(err, off) { + db.collection("connected_users").find( + { _id: { $ne: "total_users" }, _id: { $ne: "offline_users" } }, + function(err, users_list) { + if (tot.length > 0 && off.length == 0) { + socket.emit("spread_listeners", { + offline: 0, + total: tot[0].total_users.length, + online_users: users_list + }); + } else if (tot.length > 0 && off.length > 0) { + socket.emit("spread_listeners", { + offline: off[0].users.length, + total: tot[0].total_users.length, + online_users: users_list + }); + } + } + ); + } + ); + }); + }); + + socket.on("suggest_thumbnail", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + Suggestions.thumbnail(msg, coll, guid, offline, socket); + }); + + socket.on("suggest_description", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + Suggestions.description(msg, coll, guid, offline, socket); + }); + + socket.on("suggest_rules", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + Suggestions.rules(msg, coll, guid, offline, socket); + }); + + socket.on("namechange", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + Chat.namechange(msg, guid, socket); + }); + + socket.on("removename", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + if (typeof msg != "object" || !msg.hasOwnProperty("channel")) { + var result = { + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + } + }; + socket.emit("update_required", result); + return; + } + Chat.removename(guid, msg.channel, socket); + }); + + socket.on("offline", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + if ( + !msg.hasOwnProperty("status") || + !msg.hasOwnProperty("channel") || + typeof msg.status != "boolean" || + typeof msg.channel != "string" + ) { + var result = { + status: { + expected: "boolean", + got: msg.hasOwnProperty("status") ? typeof msg.status : undefined + }, + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + } + }; + socket.emit("update_required", result); + return; + } + var status = msg.status; + var channel = Functions.encodeChannelName(msg.channel); //.replace(/ /g,''); + if (status) { + in_list = false; + offline = true; + if (channel != "") coll = channel; + if (coll !== undefined) { + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + db.collection("connected_users").findAndModify( + { + query: { _id: coll }, + update: { $pull: { users: guid } }, + upsert: true + }, + function(err, updated, d) { + if (d.n == 1) { + var num = 0; + if (updated && updated.users) { + num = updated.users.length; + } + io.to(coll).emit("viewers", num); + db.collection("frontpage_lists").update( + { _id: coll, viewers: { $gt: 0 } }, + { $inc: { viewers: -1 } }, + function(err, docs) {} + ); + db.collection("connected_users").update( + { _id: "total_users" }, + { $pull: { total_users: guid + coll } }, + function(err, docs) { + db.collection("connected_users").update( + { _id: "offline_users" }, + { $addToSet: { users: guid } }, + { upsert: true }, + function(err, docs) { + if ( + docs.nModified == 1 && + (coll != undefined && coll != "") + ) { + db.collection("connected_users").update( + { _id: "total_users" }, + { $addToSet: { total_users: guid + coll } }, + function(err, docs) {} + ); + } + } + ); + } + ); + } + Functions.remove_name_from_db(guid, coll); + } + ); + } + + Functions.remove_unique_id(short_id); + } else { + offline = false; + db.collection("connected_users").update( + { _id: "offline_users" }, + { $pull: { users: guid } }, + function(err, docs) { + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 3" + ); + } + ); + } + }); + + socket.on("get_history", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + if ( + !msg.hasOwnProperty("channel") || + !msg.hasOwnProperty("all") || + typeof msg.channel != "string" || + typeof msg.all != "boolean" + ) { + var result = { + all: { + expected: "boolean", + got: msg.hasOwnProperty("all") ? typeof msg.all : undefined + }, + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined + } + }; + socket.emit("update_required", result); + return; + } + Chat.get_history(msg.channel, msg.all, socket); + }); + + socket.on("chat", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + Chat.chat(msg, guid, offline, socket); + }); + + socket.on("all,chat", function(data) { + if (data.hasOwnProperty("channel") && data.channel.indexOf("?") > -1) { + var _list = data.channel.substring(0, data.channel.indexOf("?")); + data.channel = _list; + } + if (data.hasOwnProperty("channel")) { + data.channel = Functions.encodeChannelName(data.channel); + } + Chat.all_chat(data, guid, offline, socket); + }); + + socket.on("frontpage_lists", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + Frontpage.frontpage_lists(msg, socket); + }); + + socket.on("import_zoff", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + ListChange.addFromOtherList(msg, guid, offline, socket); + }); + + socket.on("now_playing", function(list, fn) { + List.now_playing(list, fn, socket); + }); + + socket.on("id", function(arr) { + if (arr.hasOwnProperty("channel") && arr.channel.indexOf("?") > -1) { + var _list = arr.channel.substring(0, arr.channel.indexOf("?")); + arr.channel = _list; + } + if (arr.hasOwnProperty("channel")) { + arr.channel = Functions.encodeChannelName(arr.channel); + } + if (typeof arr == "object") + io.to(arr.id).emit(arr.id.toLowerCase(), { + type: arr.type, + value: arr.value + }); + }); + + socket.on("list", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + try { + //var _list = msg.channel.replace(/ /g,''); + var _list = msg.channel; + if (_list.length == 0) return; + if (_list.indexOf("?") > -1) { + _list = _list.substring(0, _list.indexOf("?")); + msg.channel = _list; + } + coll = Functions.removeEmojis(_list).toLowerCase(); + //coll = coll.replace(/_/g, ""); + // + //coll = filter.clean(coll); + } catch (e) { + return; + } + + if (msg.hasOwnProperty("offline") && msg.offline) { + offline = true; + } + List.list(msg, guid, coll, offline, socket); + Functions.get_short_id(socket); + }); + + socket.on("end", function(obj) { + if (obj.hasOwnProperty("channel") && obj.channel.indexOf("?") > -1) { + var _list = obj.channel.substring(0, obj.channel.indexOf("?")); + obj.channel = _list; + } + if (obj.hasOwnProperty("channel")) { + obj.channel = Functions.encodeChannelName(obj.channel); + try { + coll = obj.channel.toLowerCase(); //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + } + + List.end(obj, coll, guid, offline, socket); + }); + + socket.on("addPlaylist", function(arr) { + if (arr.hasOwnProperty("channel") && arr.channel.indexOf("?") > -1) { + var _list = arr.channel.substring(0, arr.channel.indexOf("?")); + arr.channel = _list; + } + if (arr.hasOwnProperty("channel")) { + arr.channel = Functions.encodeChannelName(arr.channel); + } + ListChange.addPlaylist(arr, guid, offline, socket); + }); + + socket.on("add", function(arr) { + if (arr.hasOwnProperty("list") && arr.list.indexOf("?") > -1) { + var _list = arr.list.substring(0, arr.list.indexOf("?")); + arr.list = _list; + } + if (arr.hasOwnProperty("list")) { + arr.list = Functions.encodeChannelName(arr.list); + } + if ( + coll !== undefined && + ((arr.hasOwnProperty("offsiteAdd") && !arr.offsiteAdd) || + !arr.hasOwnProperty("offsiteAdd")) + ) { + try { + coll = arr.list; //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + } else if (arr.hasOwnProperty("offsiteAdd") && arr.offsiteAdd) { + arr.list = Functions.removeEmojis(arr.list).toLowerCase(); + } + ListChange.add_function(arr, coll, guid, offline, socket); + }); + + socket.on("delete_all", function(msg) { + try { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + + ListChange.delete_all(msg, coll, guid, offline, socket); + }); + + socket.on("vote", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + if (coll !== undefined) { + try { + coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + } + ListChange.voteUndecided(msg, coll, guid, offline, socket); + }); + + socket.on("password", function(inp) { + if (inp.hasOwnProperty("channel") && inp.channel.indexOf("?") > -1) { + var _list = inp.channel.substring(0, inp.channel.indexOf("?")); + inp.channel = _list; + } + if (inp.hasOwnProperty("channel")) { + inp.channel = Functions.encodeChannelName(inp.channel); + } + //if(coll != undefined) coll.replace(/ /g,''); + ListSettings.password(inp, coll, guid, offline, socket); + }); + + socket.on("skip", function(list) { + if (list.hasOwnProperty("channel") && list.channel.indexOf("?") > -1) { + var _list = list.channel.substring(0, list.channel.indexOf("?")); + list.channel = _list; + coll = list.channel; + } + if (list.hasOwnProperty("channel")) { + list.channel = Functions.encodeChannelName(list.channel); + } + //if(coll != undefined) coll.replace(/ /g,''); + List.skip(list, guid, coll, offline, socket); + }); + + socket.on("conf", function(conf) { + if (conf.hasOwnProperty("channel") && conf.channel.indexOf("?") > -1) { + var _list = conf.channel.substring(0, conf.channel.indexOf("?")); + conf.channel = _list; + coll = conf.channel; + } + if (conf.hasOwnProperty("channel")) { + conf.channel = Functions.encodeChannelName(conf.channel); + coll = conf.channel; + } + //if(coll != undefined) coll.replace(/ /g,''); + ListSettings.conf_function(conf, coll, guid, offline, socket); + }); + + socket.on("shuffle", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + try { + coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + + ListChange.shuffle(msg, coll, guid, offline, socket); + }); + + socket.on("change_channel", function(obj) { + if (obj == undefined && coll != undefined) { + obj = {}; + obj.channel = coll; + } else if ( + obj != undefined && + obj.hasOwnProperty("channel") && + obj.channel.indexOf("?") > -1 + ) { + var _list = obj.channel.substring(0, obj.channel.indexOf("?")); + obj.channel = _list; + } + if (obj == undefined && coll == undefined) { + return; + } + if (obj.hasOwnProperty("channel")) { + obj.channel = Functions.encodeChannelName(obj.channel); + } + if ( + coll === undefined && + obj !== undefined && + obj.channel !== undefined + ) { + try { + coll = obj.channel.toLowerCase(); //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + } + Functions.left_channel( + coll, + guid, + short_id, + in_list, + socket, + true, + "left 1" + ); + in_list = false; + }); + + socket.on("disconnect", function() { + Functions.left_channel( + coll, + guid, + short_id, + in_list, + socket, + false, + "left 2" + ); + }); + + socket.on("disconnected", function() { + Functions.left_channel( + coll, + guid, + short_id, + in_list, + socket, + false, + "left 3" + ); + }); + + socket.on("left_channel", function(msg) { + if (msg.hasOwnProperty("channel") && msg.channel.indexOf("?") > -1) { + var _list = msg.channel.substring(0, msg.channel.indexOf("?")); + msg.channel = _list; + } + if (msg.hasOwnProperty("channel")) { + msg.channel = Functions.encodeChannelName(msg.channel); + } + if ( + msg.hasOwnProperty("channel") && + msg.channel != "" && + typeof msg.channel == "string" + ) { + coll = msg.channel; //.replace(/ /g,''); + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + Functions.left_channel( + coll, + guid, + short_id, + in_list, + socket, + false, + "left 4" + ); + } + }); + + socket.on("reconnect_failed", function() { + Functions.left_channel( + coll, + guid, + short_id, + in_list, + socket, + false, + "left 5" + ); + }); + + socket.on("connect_timeout", function() { + Functions.left_channel( + coll, + guid, + short_id, + in_list, + socket, + false, + "left 6" + ); + }); + + socket.on("error", function() { + Functions.left_channel( + coll, + guid, + short_id, + in_list, + socket, + false, + "left 7" + ); + }); + + socket.on("pos", function(obj) { + if ( + obj != undefined && + obj.hasOwnProperty("channel") && + obj.channel.indexOf("?") > -1 + ) { + var _list = obj.channel.substring(0, obj.channel.indexOf("?")); + obj.channel = _list; + } + if (obj != undefined && obj.hasOwnProperty("channel")) { + obj.channel = Functions.encodeChannelName(obj.channel); + } + if (obj == undefined && coll == undefined) { + return; + } + if (coll !== undefined) { + try { + coll = obj.channel.toLowerCase(); //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); + + //coll = filter.clean(coll); + } catch (e) { + return; + } + } + + if (!obj.hasOwnProperty("channel") || typeof obj.channel != "string") { + var result = { + channel: { + expected: "string", + got: obj.hasOwnProperty("channel") ? typeof obj.channel : undefined + }, + pass: { + expected: "string", + got: obj.hasOwnProperty("pass") ? typeof obj.pass : undefined + } + }; + socket.emit("update_required", result); + return; + } + if (coll == undefined) return; + db.collection(coll + "_settings").find(function(err, docs) { + Functions.getSessionAdminUser( + Functions.getSession(socket), + coll, + function(userpass, adminpass) { + if (userpass != "" || obj.pass == undefined) { + obj.pass = userpass; + } else { + obj.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(obj.pass)) + .digest("base64"); + } + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (obj.hasOwnProperty("pass") && docs[0].userpass == obj.pass)) + ) { + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 4" + ); + List.send_play(coll, socket); + } else { + socket.emit("auth_required"); + } + } + ); + }); + }); + }); + + //send_ping(); +}; /* function send_ping() { diff --git a/server/handlers/list.js b/server/handlers/list.js index a8b7db77..d8fbded2 100644 --- a/server/handlers/list.js +++ b/server/handlers/list.js @@ -1,772 +1,1248 @@ -var ColorThief = require('color-thief-jimp'); -var Jimp = require('jimp'); -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var Frontpage = require(pathThumbnails + '/handlers/frontpage.js'); +var ColorThief = require("color-thief-jimp"); +var Jimp = require("jimp"); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var Frontpage = require(pathThumbnails + "/handlers/frontpage.js"); var projects = require(pathThumbnails + "/handlers/aggregates.js"); -var crypto = require('crypto'); -var Filter = require('bad-words'); -var Search = require(pathThumbnails + '/handlers/search.js'); -var filter = new Filter({ placeHolder: 'x'}); +var crypto = require("crypto"); +var Filter = require("bad-words"); +var Search = require(pathThumbnails + "/handlers/search.js"); +var filter = new Filter({ placeHolder: "x" }); /*var filter = { clean: function(str) { return str; } }*/ -var request = require('request'); -var db = require(pathThumbnails + '/handlers/db.js'); +var request = require("request"); +var db = require(pathThumbnails + "/handlers/db.js"); function now_playing(list, fn, socket) { - if(typeof(list) !== 'string' || typeof(fn) !== 'function') { - socket.emit('update_required'); - return; + if (typeof list !== "string" || typeof fn !== "function") { + socket.emit("update_required"); + return; + } + db.collection(list).find({ now_playing: true }, function(err, docs) { + if (docs.length === 0) { + fn("No song currently playing"); + return; } - db.collection(list).find({now_playing:true}, function(err, docs){ - if(docs.length === 0){ - fn("No song currently playing"); - return; - } - var title = docs[0].title; - if(title === undefined) fn("No song currently playing"); - else fn(title); - }); + var title = docs[0].title; + if (title === undefined) fn("No song currently playing"); + else fn(title); + }); } function list(msg, guid, coll, offline, socket) { - var socketid = socket.zoff_id; - - if(typeof(msg) === 'object' && msg !== undefined && msg !== null) - { - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass, gotten) { - if(gotten && userpass != "" && !msg.hasOwnProperty("pass")) { - msg.pass = userpass; - } else { - msg.pass = crypto.createHash('sha256').update(Functions.decrypt_string(msg.pass)).digest("base64"); - } - adminpass = Functions.hash_pass(adminpass); - if(!msg.hasOwnProperty('version') || !msg.hasOwnProperty("channel") || - msg.version != VERSION || msg.version == undefined || - typeof(msg.channel) != "string") { - var result = { - channel: { - expected: "string", - got: msg.hasOwnProperty("channel") ? typeof(msg.channel) : undefined, - }, - version: { - expected: VERSION, - got: msg.version, - }, - pass: { - expected: "string", - got: msg.hasOwnProperty("pass") ? typeof(msg.pass) : undefined, - }, - }; - socket.emit('update_required', result); - return; - } - coll = msg.channel.toLowerCase(); //.replace(/ /g,''); - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = filter.clean(coll); - var pass = msg.pass; - db.collection('frontpage_lists').find({"_id": coll}, function(err, frontpage_lists){ - if(frontpage_lists.length == 1) { - db.collection(coll + "_settings").find(function(err, docs) { - if(docs.length == 0 || (docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || docs[0].userpass == pass))) { - if(docs.length > 0 && docs[0].hasOwnProperty('userpass') && docs[0].userpass != "" && docs[0].userpass == pass) { - Functions.setSessionUserPass(Functions.getSession(socket), msg.pass, coll, function(){}) - socket.emit("auth_accepted", {value: true}); - } - if(docs.length > 0 && docs[0].userpass != pass) { - Functions.setSessionUserPass(Functions.getSession(socket), "", coll, function(){}) - } - if(docs.length > 0 && docs[0].hasOwnProperty("adminpass") && docs[0].adminpass != "" && docs[0].adminpass == adminpass) { - socket.emit("pw", true); - } - in_list = true; - socket.join(coll); - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 10"); - - if(frontpage_lists[0].viewers != undefined){ - io.to(coll).emit("viewers", frontpage_lists[0].viewers); - } else { - io.to(coll).emit("viewers", 1); - } - - send_list(coll, socket, true, false, true); - - } else { - socket.emit("auth_required"); - } - }); - } else { - db.createCollection(coll, function(err, docs){ - db.collection(coll).createIndex({ id: 1}, {unique: true}, function(e, d) { - var configs = {"addsongs":false, "adminpass":"", "allvideos":true, "frontpage":true, "longsongs":false, "removeplay": false, "shuffle": true, "skip": false, "skips": [], "startTime":Functions.get_time(), "views": [], "vote": false, "description": "", "thumbnail": "", "rules": "", userpass: "", id: "config", "toggleChat": true}; - db.collection(coll + "_settings").insert(configs, function(err, docs){ - socket.join(coll); - send_list(coll, socket, true, false, true); - db.collection("frontpage_lists").insert({"_id": coll, "count" : 0, "frontpage": true, "accessed": Functions.get_time(), "viewers": 1}, function(e,d){ - }); - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 11"); - }); - }); - }); - } - }); - }); - } else { + var socketid = socket.zoff_id; + if (typeof msg === "object" && msg !== undefined && msg !== null) { + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass, + gotten + ) { + if (gotten && userpass != "" && !msg.hasOwnProperty("pass")) { + msg.pass = userpass; + } else { + msg.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(msg.pass)) + .digest("base64"); + } + adminpass = Functions.hash_pass(adminpass); + if ( + !msg.hasOwnProperty("version") || + !msg.hasOwnProperty("channel") || + msg.version != VERSION || + msg.version == undefined || + typeof msg.channel != "string" + ) { var result = { - msg: { - expected: "object", - got: typeof(msg) - }, + channel: { + expected: "string", + got: msg.hasOwnProperty("channel") ? typeof msg.channel : undefined + }, + version: { + expected: VERSION, + got: msg.version + }, + pass: { + expected: "string", + got: msg.hasOwnProperty("pass") ? typeof msg.pass : undefined + } }; - socket.emit('update_required', result); - } + socket.emit("update_required", result); + return; + } + coll = msg.channel.toLowerCase(); //.replace(/ /g,''); + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = filter.clean(coll); + var pass = msg.pass; + db.collection("frontpage_lists").find({ _id: coll }, function( + err, + frontpage_lists + ) { + if (frontpage_lists.length == 1) { + db.collection(coll + "_settings").find(function(err, docs) { + if ( + docs.length == 0 || + (docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + docs[0].userpass == pass)) + ) { + if ( + docs.length > 0 && + docs[0].hasOwnProperty("userpass") && + docs[0].userpass != "" && + docs[0].userpass == pass + ) { + Functions.setSessionUserPass( + Functions.getSession(socket), + msg.pass, + coll, + function() {} + ); + socket.emit("auth_accepted", { value: true }); + } + if (docs.length > 0 && docs[0].userpass != pass) { + Functions.setSessionUserPass( + Functions.getSession(socket), + "", + coll, + function() {} + ); + } + if ( + docs.length > 0 && + docs[0].hasOwnProperty("adminpass") && + docs[0].adminpass != "" && + docs[0].adminpass == adminpass + ) { + socket.emit("pw", true); + } + in_list = true; + socket.join(coll); + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 10" + ); + + if (frontpage_lists[0].viewers != undefined) { + io.to(coll).emit("viewers", frontpage_lists[0].viewers); + } else { + io.to(coll).emit("viewers", 1); + } + + send_list(coll, socket, true, false, true); + } else { + socket.emit("auth_required"); + } + }); + } else { + db.createCollection(coll, function(err, docs) { + db.collection(coll).createIndex( + { id: 1 }, + { unique: true }, + function(e, d) { + var configs = { + addsongs: false, + adminpass: "", + allvideos: true, + frontpage: true, + longsongs: false, + removeplay: false, + shuffle: true, + skip: false, + skips: [], + startTime: Functions.get_time(), + views: [], + vote: false, + description: "", + thumbnail: "", + rules: "", + userpass: "", + id: "config", + toggleChat: true + }; + db.collection(coll + "_settings").insert(configs, function( + err, + docs + ) { + socket.join(coll); + send_list(coll, socket, true, false, true); + db.collection("frontpage_lists").insert( + { + _id: coll, + count: 0, + frontpage: true, + accessed: Functions.get_time(), + viewers: 1 + }, + function(e, d) {} + ); + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 11" + ); + }); + } + ); + }); + } + }); + }); + } else { + var result = { + msg: { + expected: "object", + got: typeof msg + } + }; + socket.emit("update_required", result); + } } function skip(list, guid, coll, offline, socket, callback) { - var socketid = socket.zoff_id; + var socketid = socket.zoff_id; - if(list !== undefined && list !== null && list !== "") - { - if(coll == undefined && list.hasOwnProperty('channel')) coll = list.channel.toLowerCase(); - if(coll !== undefined) { - try { - coll = list.channel.toLowerCase();//.replace(/ /g,''); - if(coll.length == 0) return; - coll = Functions.removeEmojis(coll).toLowerCase(); - //coll = coll.replace(/_/g, ""); + if (list !== undefined && list !== null && list !== "") { + if (coll == undefined && list.hasOwnProperty("channel")) + coll = list.channel.toLowerCase(); + if (coll !== undefined) { + try { + coll = list.channel.toLowerCase(); //.replace(/ /g,''); + if (coll.length == 0) return; + coll = Functions.removeEmojis(coll).toLowerCase(); + //coll = coll.replace(/_/g, ""); - //coll = filter.clean(coll); - } catch(e) { - return; - } - } - if(!list.hasOwnProperty("id") || list.id == undefined) { - socket.emit('toast', "The list is empty."); - return; - } - if(!list.hasOwnProperty("id") || !list.hasOwnProperty("channel") || - (typeof(list.id) != "string" && typeof(list.id) != "number") || typeof(list.channel) != "string") { - var result = { - channel: { - expected: "string", - got: list.hasOwnProperty("channel") ? typeof(list.channel) : undefined, - }, - pass: { - expected: "string", - got: list.hasOwnProperty("pass") ? typeof(list.pass) : undefined, - }, - userpass: { - expected: "string", - got: list.hasOwnProperty("userpass") ? typeof(list.userpass) : undefined, - }, - id: { - expected: "string", - got: list.hasOwnProperty("id") ? typeof(list.id) : undefined, - }, - }; - socket.emit('update_required', result); - return; - } - list.id = list.id + ""; - Functions.getSessionAdminUser(Functions.getSession(socket), coll, function(userpass, adminpass) { - if(adminpass != "" || list.pass == undefined) { - list.pass = Functions.hash_pass(adminpass); - } else if(list.pass != "") { - list.pass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(list.pass),true));; - } else { - list.pass = ""; - } - if(userpass != "" || list.userpass == undefined) { - list.userpass = userpass; - } else { - list.userpass = crypto.createHash('sha256').update(Functions.decrypt_string(list.userpass)).digest("base64"); - } - - db.collection(coll + "_settings").find(function(_err, docs){ - if(docs.length > 0 && (docs[0].userpass == undefined || docs[0].userpass == "" || (list.hasOwnProperty('userpass') && docs[0].userpass == list.userpass))) { - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 12"); - - var video_id; - adminpass = ""; - video_id = list.id; - var err = list.error; - Search.check_if_error_or_blocked(video_id, coll, err == "5" || err == "100" || err == "101" || err == "150" || err == 5 || err == 100 || err == 101 || err == 150, function(trueError) { - var error = false; - if (!trueError) { - adminpass = list.pass; - } else if(trueError) { - error = true; - } - hash = adminpass; - //db.collection(coll + "_settings").find(function(err, docs){ - var strictSkip = false; - var strictSkipNumber = 10; - if(docs[0].strictSkip) strictSkip = docs[0].strictSkip; - if(docs[0].strictSkipNumber) strictSkipNumber = docs[0].strictSkipNumber; - if(docs !== null && docs.length !== 0) - { - if(!docs[0].skip || (docs[0].adminpass == hash && docs[0].adminpass !== "") || error) - { - db.collection("frontpage_lists").find({"_id": coll}, function(err, frontpage_viewers){ - if(error || - ((strictSkip && ((docs[0].adminpass == hash && docs[0].adminpass !== "") || (docs[0].skips.length+1 >= strictSkipNumber))) || - (!strictSkip && ((frontpage_viewers[0].viewers/2 <= docs[0].skips.length+1 && !Functions.contains(docs[0].skips, guid) && frontpage_viewers[0].viewers != 2) || - (frontpage_viewers[0].viewers == 2 && docs[0].skips.length+1 == 2 && !Functions.contains(docs[0].skips, guid)) || - (docs[0].adminpass == hash && docs[0].adminpass !== "" && docs[0].skip))))) - { - Functions.checkTimeout("skip", 1, coll, coll, error, true, socket, function() { - change_song(coll, error, video_id, docs); - socket.emit("toast", "skip"); - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 1) { - db.collection("registered_users").find({"_id": docs[0].name}, function(err, n) { - var icon = false; - if(n.length > 0 && n[0].icon) { - icon = n[0].icon; - } - io.to(coll).emit('chat', {from: docs[0].name, icon: icon, msg: " skipped"}); - }); - } - }); - }, "The channel is skipping too often, please wait "); - } else if(!Functions.contains(docs[0].skips, guid)){ - db.collection(coll + "_settings").update({ id: "config" }, {$push:{skips:guid}}, function(err, d){ - if(frontpage_viewers[0].viewers == 2 && !strictSkip) { - to_skip = 1; - } else if(strictSkip) { - to_skip = (strictSkipNumber) - docs[0].skips.length-1; - } else { - to_skip = (Math.ceil(frontpage_viewers[0].viewers/2) - docs[0].skips.length-1); - } - socket.emit("toast", to_skip + " more are needed to skip!"); - db.collection("user_names").find({"guid": guid}, function(err, docs) { - if(docs.length == 1) { - db.collection("registered_users").find({"_id": docs[0].name}, function(err, n) { - var icon = false; - if(n.length > 0 && n[0].icon) { - icon = n[0].icon; - } - socket.to(coll).emit('chat', {from: docs[0].name, msg: " voted to skip"}); - }) - } - }); - }); - }else{ - socket.emit("toast", "alreadyskip"); - } - }); - }else - socket.emit("toast", "noskip"); - } - }); - //}); - } else { - socket.emit("auth_required"); - } - }); - }); - } else { - var result = { - msg: { - expected: "object", - got: typeof(list), - }, - }; - socket.emit("update_required", result); + //coll = filter.clean(coll); + } catch (e) { + return; + } } + if (!list.hasOwnProperty("id") || list.id == undefined) { + socket.emit("toast", "The list is empty."); + return; + } + if ( + !list.hasOwnProperty("id") || + !list.hasOwnProperty("channel") || + (typeof list.id != "string" && typeof list.id != "number") || + typeof list.channel != "string" + ) { + var result = { + channel: { + expected: "string", + got: list.hasOwnProperty("channel") ? typeof list.channel : undefined + }, + pass: { + expected: "string", + got: list.hasOwnProperty("pass") ? typeof list.pass : undefined + }, + userpass: { + expected: "string", + got: list.hasOwnProperty("userpass") + ? typeof list.userpass + : undefined + }, + id: { + expected: "string", + got: list.hasOwnProperty("id") ? typeof list.id : undefined + } + }; + socket.emit("update_required", result); + return; + } + list.id = list.id + ""; + Functions.getSessionAdminUser(Functions.getSession(socket), coll, function( + userpass, + adminpass + ) { + if (adminpass != "" || list.pass == undefined) { + list.pass = Functions.hash_pass(adminpass); + } else if (list.pass != "") { + list.pass = Functions.hash_pass( + Functions.hash_pass(Functions.decrypt_string(list.pass), true) + ); + } else { + list.pass = ""; + } + if (userpass != "" || list.userpass == undefined) { + list.userpass = userpass; + } else { + list.userpass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(list.userpass)) + .digest("base64"); + } + + db.collection(coll + "_settings").find(function(_err, docs) { + if ( + docs.length > 0 && + (docs[0].userpass == undefined || + docs[0].userpass == "" || + (list.hasOwnProperty("userpass") && + docs[0].userpass == list.userpass)) + ) { + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 12" + ); + + var video_id; + adminpass = ""; + video_id = list.id; + var err = list.error; + Search.check_if_error_or_blocked( + video_id, + coll, + err == "5" || + err == "100" || + err == "101" || + err == "150" || + err == 5 || + err == 100 || + err == 101 || + err == 150, + function(trueError) { + var error = false; + if (!trueError) { + adminpass = list.pass; + } else if (trueError) { + error = true; + } + hash = adminpass; + //db.collection(coll + "_settings").find(function(err, docs){ + var strictSkip = false; + var strictSkipNumber = 10; + if (docs[0].strictSkip) strictSkip = docs[0].strictSkip; + if (docs[0].strictSkipNumber) + strictSkipNumber = docs[0].strictSkipNumber; + if (docs !== null && docs.length !== 0) { + if ( + !docs[0].skip || + (docs[0].adminpass == hash && docs[0].adminpass !== "") || + error + ) { + db.collection("frontpage_lists").find({ _id: coll }, function( + err, + frontpage_viewers + ) { + if ( + error || + ((strictSkip && + ((docs[0].adminpass == hash && + docs[0].adminpass !== "") || + docs[0].skips.length + 1 >= strictSkipNumber)) || + (!strictSkip && + ((frontpage_viewers[0].viewers / 2 <= + docs[0].skips.length + 1 && + !Functions.contains(docs[0].skips, guid) && + frontpage_viewers[0].viewers != 2) || + (frontpage_viewers[0].viewers == 2 && + docs[0].skips.length + 1 == 2 && + !Functions.contains(docs[0].skips, guid)) || + (docs[0].adminpass == hash && + docs[0].adminpass !== "" && + docs[0].skip)))) + ) { + Functions.checkTimeout( + "skip", + 1, + coll, + coll, + error, + true, + socket, + function() { + change_song(coll, error, video_id, docs); + socket.emit("toast", "skip"); + db.collection("user_names").find( + { guid: guid }, + function(err, docs) { + if (docs.length == 1) { + db.collection("registered_users").find( + { _id: docs[0].name }, + function(err, n) { + var icon = false; + if (n.length > 0 && n[0].icon) { + icon = n[0].icon; + } + io.to(coll).emit("chat", { + from: docs[0].name, + icon: icon, + msg: " skipped" + }); + } + ); + } + } + ); + }, + "The channel is skipping too often, please wait " + ); + } else if (!Functions.contains(docs[0].skips, guid)) { + db.collection(coll + "_settings").update( + { id: "config" }, + { $push: { skips: guid } }, + function(err, d) { + if ( + frontpage_viewers[0].viewers == 2 && + !strictSkip + ) { + to_skip = 1; + } else if (strictSkip) { + to_skip = + strictSkipNumber - docs[0].skips.length - 1; + } else { + to_skip = + Math.ceil(frontpage_viewers[0].viewers / 2) - + docs[0].skips.length - + 1; + } + socket.emit( + "toast", + to_skip + " more are needed to skip!" + ); + db.collection("user_names").find( + { guid: guid }, + function(err, docs) { + if (docs.length == 1) { + db.collection("registered_users").find( + { _id: docs[0].name }, + function(err, n) { + var icon = false; + if (n.length > 0 && n[0].icon) { + icon = n[0].icon; + } + socket.to(coll).emit("chat", { + from: docs[0].name, + msg: " voted to skip" + }); + } + ); + } + } + ); + } + ); + } else { + socket.emit("toast", "alreadyskip"); + } + }); + } else socket.emit("toast", "noskip"); + } + } + ); + //}); + } else { + socket.emit("auth_required"); + } + }); + }); + } else { + var result = { + msg: { + expected: "object", + got: typeof list + } + }; + socket.emit("update_required", result); + } } function change_song(coll, error, id, conf, callback, socket) { - //coll = coll.replace(/ /g,''); - //db.collection(coll + "_settings").find(function(err, docs){ - var startTime = conf[0].startTime; - if(conf !== null && conf.length !== 0) + //coll = coll.replace(/ /g,''); + //db.collection(coll + "_settings").find(function(err, docs){ + var startTime = conf[0].startTime; + if (conf !== null && conf.length !== 0) { + db.collection(coll).aggregate( + [ { - db.collection(coll).aggregate([{ - $match:{ - views:{ - $exists: false - }, - type:{ - $ne: "suggested" - } - } - }, { - $sort:{ - now_playing: -1, - votes:-1, - added:1, - title: 1 - } - }, { - $limit:2 - }], function(err, now_playing_doc){ - if(now_playing_doc.length == 0) { - console.log("empty list", coll, callback, id, conf); - } - if(now_playing_doc.length > 0 && ((id && id == now_playing_doc[0].id) || !id)) { - if(error){ - db.collection(coll).remove({now_playing:true, id:id}, function(err, docs){ - var next_song; - if(now_playing_doc.length == 2) next_song = now_playing_doc[1].id; - change_song_post(coll, next_song, conf, callback, socket, error); - if(!callback) { - io.to(coll).emit("channel", {type: "deleted", value: now_playing_doc[0].id, removed: true}); - } - if(docs.deletedCount == 1) { - db.collection("frontpage_lists").update({_id: coll, count: {$gt: 0}}, {$inc: {count: -1}, $set:{accessed: Functions.get_time()}}, {upsert: true}, function(err, docs){}); - } - }); - } else if(conf[0].removeplay === true){ - db.collection(coll).remove({now_playing:true, id:id}, function(err, docs){ - var next_song; - if(now_playing_doc.length == 2) next_song = now_playing_doc[1].id; - change_song_post(coll, next_song, conf, callback, socket, error); - if(!callback) { - io.to(coll).emit("channel", {type: "deleted", value: now_playing_doc[0].id, removed: true}); - } - if(docs.deletedCount == 1) { - db.collection("frontpage_lists").update({_id: coll, count: {$gt: 0}}, {$inc: {count: -1}, $set:{accessed: Functions.get_time()}}, {upsert: true}, function(err, docs){}); - } - }); - } else { - if((conf[0].skipped_time != undefined && conf[0].skipped_time != Functions.get_time()) ||conf[0].skipped_time == undefined) { - db.collection(coll).update({now_playing:true, id:id}, { - $set:{ - now_playing:false, - votes:0, - guids:[] - } - },{multi:true}, function(err, docs){ - var next_song; - if(now_playing_doc.length == 2) next_song = now_playing_doc[1].id; - change_song_post(coll, next_song, conf, callback, socket, error); - }); - } - } - } else { - if(now_playing_doc.length > 0 && now_playing_doc[0].now_playing == true && now_playing_doc.length > 1 && now_playing_doc[1].id == id) { - db.collection(coll).update({id: now_playing_doc[0].id}, {$set: {now_playing: false}}, function(e, d) { - change_song(coll, error, id, conf, callback, socket, error); - }) - } else { - return; - } - } - }); + $match: { + views: { + $exists: false + }, + type: { + $ne: "suggested" + } + } + }, + { + $sort: { + now_playing: -1, + votes: -1, + added: 1, + title: 1 + } + }, + { + $limit: 2 } - //}); + ], + function(err, now_playing_doc) { + if (now_playing_doc.length == 0) { + console.log("empty list", coll, callback, id, conf); + } + if ( + now_playing_doc.length > 0 && + ((id && id == now_playing_doc[0].id) || !id) + ) { + if (error) { + db.collection(coll).remove({ now_playing: true, id: id }, function( + err, + docs + ) { + var next_song; + if (now_playing_doc.length == 2) + next_song = now_playing_doc[1].id; + change_song_post(coll, next_song, conf, callback, socket, error); + if (!callback) { + io.to(coll).emit("channel", { + type: "deleted", + value: now_playing_doc[0].id, + removed: true + }); + } + if (docs.deletedCount == 1) { + db.collection("frontpage_lists").update( + { _id: coll, count: { $gt: 0 } }, + { + $inc: { count: -1 }, + $set: { accessed: Functions.get_time() } + }, + { upsert: true }, + function(err, docs) {} + ); + } + }); + } else if (conf[0].removeplay === true) { + db.collection(coll).remove({ now_playing: true, id: id }, function( + err, + docs + ) { + var next_song; + if (now_playing_doc.length == 2) + next_song = now_playing_doc[1].id; + change_song_post(coll, next_song, conf, callback, socket, error); + if (!callback) { + io.to(coll).emit("channel", { + type: "deleted", + value: now_playing_doc[0].id, + removed: true + }); + } + if (docs.deletedCount == 1) { + db.collection("frontpage_lists").update( + { _id: coll, count: { $gt: 0 } }, + { + $inc: { count: -1 }, + $set: { accessed: Functions.get_time() } + }, + { upsert: true }, + function(err, docs) {} + ); + } + }); + } else { + if ( + (conf[0].skipped_time != undefined && + conf[0].skipped_time != Functions.get_time()) || + conf[0].skipped_time == undefined + ) { + db.collection(coll).update( + { now_playing: true, id: id }, + { + $set: { + now_playing: false, + votes: 0, + guids: [] + } + }, + { multi: true }, + function(err, docs) { + var next_song; + if (now_playing_doc.length == 2) + next_song = now_playing_doc[1].id; + change_song_post( + coll, + next_song, + conf, + callback, + socket, + error + ); + } + ); + } + } + } else { + if ( + now_playing_doc.length > 0 && + now_playing_doc[0].now_playing == true && + now_playing_doc.length > 1 && + now_playing_doc[1].id == id + ) { + db.collection(coll).update( + { id: now_playing_doc[0].id }, + { $set: { now_playing: false } }, + function(e, d) { + change_song(coll, error, id, conf, callback, socket, error); + } + ); + } else { + return; + } + } + } + ); + } + //}); } function change_song_post(coll, next_song, conf, callback, socket, removed) { - //coll = coll.replace(/ /g,''); - db.collection(coll).aggregate([{ - $match:{ - now_playing:false, - type:{ - $ne: "suggested" + //coll = coll.replace(/ /g,''); + db.collection(coll).aggregate( + [ + { + $match: { + now_playing: false, + type: { + $ne: "suggested" + } + } + }, + { + $sort: { + votes: -1, + added: 1, + title: 1 + } + }, + { + $limit: 2 + } + ], + function(err, docs) { + if (docs !== null && docs.length > 0) { + var id = docs[0].id; + if (next_song && next_song != id) { + if (docs.length == 2 && next_song == docs[1].id) { + id = docs[1].id; + } else { + return; + } + } + db.collection(coll).update( + { id: id, now_playing: false }, + { + $set: { + now_playing: true, + votes: 0, + guids: [], + added: Functions.get_time() } - } - }, { - $sort:{ - votes:-1, - added:1, - title: 1 - } - }, { - $limit:2 - }], function(err, docs){ - if(docs !== null && docs.length > 0){ - var id = docs[0].id; - if(next_song && next_song != id) { - if((docs.length == 2 && next_song == docs[1].id)) { - id = docs[1].id; + }, + function(err, returnDocs) { + if ( + (returnDocs.hasOwnProperty("nModified") && + returnDocs.nModified == 0) || + (returnDocs.hasOwnProperty("n") && returnDocs.n == 0) + ) { + if (!callback) return; + callback(); + return; + } + db.collection(coll + "_settings").update( + { id: "config" }, + { + $set: { + startTime: Functions.get_time(), + skips: [] + } + }, + function(err, returnDocs) { + //db.collection(coll + "_settings").find({id: "config"}, function(err, conf){ + if (!callback) { + io.to(coll).emit("channel", { + type: "song_change", + time: Functions.get_time(), + remove: conf[0].removeplay || removed, + id: id + }); + send_play(coll); } else { - return; + if (socket == undefined) { + io.to(coll).emit("channel", { + type: "song_change", + time: Functions.get_time(), + remove: conf[0].removeplay || removed, + id: id + }); + } else { + socket.to(coll).emit("channel", { + type: "song_change", + time: Functions.get_time(), + remove: conf[0].removeplay || removed, + id: id + }); + } + send_play(coll, socket, true); + callback(); } - } - db.collection(coll).update({id:id, now_playing: false},{ - $set:{ - now_playing:true, - votes:0, - guids:[], - added:Functions.get_time() - } - }, function(err, returnDocs){ - if((returnDocs.hasOwnProperty("nModified") && returnDocs.nModified == 0) || (returnDocs.hasOwnProperty("n") && returnDocs.n == 0)) { - if(!callback) return; - callback(); - return; - } - db.collection(coll + "_settings").update({id: "config"}, { - $set:{ - startTime:Functions.get_time(), - skips:[] - } - }, function(err, returnDocs){ - //db.collection(coll + "_settings").find({id: "config"}, function(err, conf){ - if(!callback) { - io.to(coll).emit("channel", {type: "song_change", time: Functions.get_time(), remove: conf[0].removeplay || removed, id: id}); - send_play(coll); - } else { - if(socket == undefined) { - io.to(coll).emit("channel", {type: "song_change", time: Functions.get_time(), remove: conf[0].removeplay || removed, id: id}); - } else { - socket.to(coll).emit("channel", {type: "song_change", time: Functions.get_time(), remove: conf[0].removeplay || removed, id: id}); - } - send_play(coll, socket, true); - callback(); - } - Frontpage.update_frontpage(coll, docs[0].id, docs[0].title, docs[0].thumbnail, docs[0].source); - //}); - }); - }); - } - }); + Frontpage.update_frontpage( + coll, + docs[0].id, + docs[0].title, + docs[0].thumbnail, + docs[0].source + ); + //}); + } + ); + } + ); + } + } + ); } -function send_list(coll, socket, send, list_send, configs, shuffled) -{ - //coll = coll.replace(/ /g,''); - db.collection(coll + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, _conf){ - var conf = _conf; - if(conf.length == 0) { - var conf = {"id": "config", "addsongs":false, "adminpass":"", "allvideos":true, "frontpage":true, "longsongs":false, "removeplay": false, "shuffle": true, "skip": false, "skips": [], "startTime":Functions.get_time(), "views": [], "vote": false, "description": "", "thumbnail": "", "rules": "", "toggleChat": true, userpass: ""}; - db.collection(coll + "_settings").update({id: "config"}, conf, {upsert: true}, function(err, docs) { - send_list(coll, socket, send, list_send, configs, shuffled); - }); - } else { - db.collection(coll).aggregate([ - { - "$match": {type: {$ne: "suggested"}} - }, - { - "$project": projects.project_object - }, - { "$sort" : { "now_playing" : -1, "votes": -1, "added": 1 } } - ], function(err, docs) - //db.collection(coll).find({type: {$ne: "suggested"}}, function(err, docs) - { - if(docs.length > 0) { - db.collection(coll).find({now_playing: true}, function(err, np_docs) { - if(np_docs.length == 0) { - db.collection(coll).aggregate([{ - $match:{ - views:{ - $exists: false - }, - type:{ - $ne: "suggested" - } - } - }, { - $sort:{ - now_playing: -1, - votes:-1, - added:1, - title: 1 - } - }, { - $limit:1 - }], function(err, now_playing_doc){ - if(now_playing_doc[0].now_playing == false) { - db.collection(coll).update({id:now_playing_doc[0].id, now_playing: false}, { - $set:{ - now_playing:true, - votes:0, - guids:[], - added:Functions.get_time() - } - }, function(err, returnDocs){ - db.collection(coll + "_settings").update({ id: "config" }, { - $set:{ - startTime: Functions.get_time(), - skips:[] - } - }, function(err, returnDocs){ - Frontpage.update_frontpage(coll, now_playing_doc[0].id, now_playing_doc[0].title, now_playing_doc[0].thumbnail, now_playing_doc[0].source); - send_list(coll, socket, send, list_send, configs, shuffled); - }); - }); - } - }); - } else if(np_docs.length > 1) { - db.collection(coll).aggregate([{ - $match:{ - now_playing: true - } - }, { - $sort:{ - now_playing: -1, - votes:-1, - added:1, - title: 1 - } - }], function(e, docs) { - var real_now_playing = docs[docs.length - 1]; - db.collection(coll).update({now_playing: true, id: {$ne: real_now_playing.id}}, {$set: {now_playing: false}}, {multi: true}, function(e, d) { - send_list(coll, socket, send, list_send, configs, shuffled); - }) - }) - } else { - if(Functions.get_time()-conf[0].startTime > np_docs[0].duration){ - change_song(coll, false, np_docs[0].id, conf, function() { - send_list(coll, socket, send, list_send, configs, shuffled); - }, socket); - } else { - if(list_send) { - io.to(coll).emit("channel", {type: "list", playlist: docs, shuffled: shuffled}); - } else if(!list_send) { - socket.emit("channel", {type: "list", playlist: docs, shuffled: shuffled}); - } - if(socket === undefined && send) { - send_play(coll); - } else if(send) { - send_play(coll, socket); - } - } - } - }); - } else { - if(list_send) { - io.to(coll).emit("channel", {type: "list", playlist: docs, shuffled: shuffled}); - } else if(!list_send) { - socket.emit("channel", {type: "list", playlist: docs, shuffled: shuffled}); - } - if(socket === undefined && send) { - send_play(coll); - } else if(send) { - send_play(coll, socket); - } - } - }); - if(configs) - { - if(conf.length > 0) { - if(conf[0].adminpass !== "") conf[0].adminpass = true; - if(conf[0].hasOwnProperty("userpass") && conf[0].userpass != "") conf[0].userpass = true; - else conf[0].userpass = false; - io.to(coll).emit("conf", conf); - } else if(conf.length == 0 && docs.length > 0) { - var conf = {"id": "config", "addsongs":false, "adminpass":"", "allvideos":true, "frontpage":true, "longsongs":false, "removeplay": false, "shuffle": true, "skip": false, "skips": [], "startTime":Functions.get_time(), "views": [], "vote": false, "desc": "", userpass: ""}; - db.collection(coll + "_settings").update({id: "config"}, conf, {upsert: true}, function(err, docs) { - io.to(coll).emit("conf", conf); - }); - } - } +function send_list(coll, socket, send, list_send, configs, shuffled) { + //coll = coll.replace(/ /g,''); + db.collection(coll + "_settings").aggregate( + [ + { + $match: { + id: "config" } - }); - if(socket){ - db.collection(coll).find({type:"suggested"}).sort({added: 1}, function(err, sugg){ - socket.emit("suggested", sugg); - }); + }, + { + $project: projects.toShowConfig + } + ], + function(err, _conf) { + var conf = _conf; + if (conf.length == 0) { + var conf = { + id: "config", + addsongs: false, + adminpass: "", + allvideos: true, + frontpage: true, + longsongs: false, + removeplay: false, + shuffle: true, + skip: false, + skips: [], + startTime: Functions.get_time(), + views: [], + vote: false, + description: "", + thumbnail: "", + rules: "", + toggleChat: true, + userpass: "" + }; + db.collection(coll + "_settings").update( + { id: "config" }, + conf, + { upsert: true }, + function(err, docs) { + send_list(coll, socket, send, list_send, configs, shuffled); + } + ); + } else { + db.collection(coll).aggregate( + [ + { + $match: { type: { $ne: "suggested" } } + }, + { + $project: projects.project_object + }, + { $sort: { now_playing: -1, votes: -1, added: 1 } } + ], + function( + err, + docs //db.collection(coll).find({type: {$ne: "suggested"}}, function(err, docs) + ) { + if (docs.length > 0) { + db.collection(coll).find({ now_playing: true }, function( + err, + np_docs + ) { + if (np_docs.length == 0) { + db.collection(coll).aggregate( + [ + { + $match: { + views: { + $exists: false + }, + type: { + $ne: "suggested" + } + } + }, + { + $sort: { + now_playing: -1, + votes: -1, + added: 1, + title: 1 + } + }, + { + $limit: 1 + } + ], + function(err, now_playing_doc) { + if (now_playing_doc[0].now_playing == false) { + db.collection(coll).update( + { id: now_playing_doc[0].id, now_playing: false }, + { + $set: { + now_playing: true, + votes: 0, + guids: [], + added: Functions.get_time() + } + }, + function(err, returnDocs) { + db.collection(coll + "_settings").update( + { id: "config" }, + { + $set: { + startTime: Functions.get_time(), + skips: [] + } + }, + function(err, returnDocs) { + Frontpage.update_frontpage( + coll, + now_playing_doc[0].id, + now_playing_doc[0].title, + now_playing_doc[0].thumbnail, + now_playing_doc[0].source + ); + send_list( + coll, + socket, + send, + list_send, + configs, + shuffled + ); + } + ); + } + ); + } + } + ); + } else if (np_docs.length > 1) { + db.collection(coll).aggregate( + [ + { + $match: { + now_playing: true + } + }, + { + $sort: { + now_playing: -1, + votes: -1, + added: 1, + title: 1 + } + } + ], + function(e, docs) { + var real_now_playing = docs[docs.length - 1]; + db.collection(coll).update( + { now_playing: true, id: { $ne: real_now_playing.id } }, + { $set: { now_playing: false } }, + { multi: true }, + function(e, d) { + send_list( + coll, + socket, + send, + list_send, + configs, + shuffled + ); + } + ); + } + ); + } else { + if ( + Functions.get_time() - conf[0].startTime > + np_docs[0].duration + ) { + change_song( + coll, + false, + np_docs[0].id, + conf, + function() { + send_list( + coll, + socket, + send, + list_send, + configs, + shuffled + ); + }, + socket + ); + } else { + if (list_send) { + io.to(coll).emit("channel", { + type: "list", + playlist: docs, + shuffled: shuffled + }); + } else if (!list_send) { + socket.emit("channel", { + type: "list", + playlist: docs, + shuffled: shuffled + }); + } + if (socket === undefined && send) { + send_play(coll); + } else if (send) { + send_play(coll, socket); + } + } + } + }); + } else { + if (list_send) { + io.to(coll).emit("channel", { + type: "list", + playlist: docs, + shuffled: shuffled + }); + } else if (!list_send) { + socket.emit("channel", { + type: "list", + playlist: docs, + shuffled: shuffled + }); + } + if (socket === undefined && send) { + send_play(coll); + } else if (send) { + send_play(coll, socket); + } + } + } + ); + if (configs) { + if (conf.length > 0) { + if (conf[0].adminpass !== "") conf[0].adminpass = true; + if (conf[0].hasOwnProperty("userpass") && conf[0].userpass != "") + conf[0].userpass = true; + else conf[0].userpass = false; + io.to(coll).emit("conf", conf); + } else if (conf.length == 0 && docs.length > 0) { + var conf = { + id: "config", + addsongs: false, + adminpass: "", + allvideos: true, + frontpage: true, + longsongs: false, + removeplay: false, + shuffle: true, + skip: false, + skips: [], + startTime: Functions.get_time(), + views: [], + vote: false, + desc: "", + userpass: "" + }; + db.collection(coll + "_settings").update( + { id: "config" }, + conf, + { upsert: true }, + function(err, docs) { + io.to(coll).emit("conf", conf); + } + ); + } + } + } } + ); + if (socket) { + db.collection(coll) + .find({ type: "suggested" }) + .sort({ added: 1 }, function(err, sugg) { + socket.emit("suggested", sugg); + }); + } } function end(obj, coll, guid, offline, socket) { - var socketid = socket.zoff_id; - if(typeof(obj) !== 'object') { - return; - } - id = obj.id; + var socketid = socket.zoff_id; + if (typeof obj !== "object") { + return; + } + id = obj.id; - if(id !== undefined && id !== null && id !== "") { - - if(!obj.hasOwnProperty("id") || !obj.hasOwnProperty("channel") || - (typeof(obj.id) != "string" && typeof(obj.id) != "number") || typeof(obj.channel) != "string") { - var result = { - channel: { - expected: "string", - got: obj.hasOwnProperty("channel") ? typeof(obj.channel) : undefined, - }, - pass: { - expected: "string", - got: obj.hasOwnProperty("pass") ? typeof(obj.pass) : undefined, - }, - id: { - expected: "string || number", - got: obj.hasOwnProperty("id") ? typeof(obj.id) : undefined, - }, - }; - socket.emit("update_required", result); - return; + if (id !== undefined && id !== null && id !== "") { + if ( + !obj.hasOwnProperty("id") || + !obj.hasOwnProperty("channel") || + (typeof obj.id != "string" && typeof obj.id != "number") || + typeof obj.channel != "string" + ) { + var result = { + channel: { + expected: "string", + got: obj.hasOwnProperty("channel") ? typeof obj.channel : undefined + }, + pass: { + expected: "string", + got: obj.hasOwnProperty("pass") ? typeof obj.pass : undefined + }, + id: { + expected: "string || number", + got: obj.hasOwnProperty("id") ? typeof obj.id : undefined } - obj.id = obj.id + ""; - id = id + ""; - var callback_function = function() { - for(var i = 0; i < arguments.length; i++) { - if(typeof(arguments[i]) == "function") { - arguments[i](); - } - } - } - db.collection(coll + "_settings").find(function(err, docs){ - var authentication_needed = false; - if(docs.length > 0 && (docs[0].userpass != undefined && docs[0].userpass != "")) { - callback_function = Functions.getSessionAdminUser; - authentication_needed = true; - } - callback_function(Functions.getSession(socket), coll, function(userpass) { - if(userpass != "" || obj.pass == undefined) { - obj.pass = userpass; - } else { - obj.pass = crypto.createHash('sha256').update(Functions.decrypt_string(obj.pass)).digest("base64"); - } - if(!authentication_needed || (authentication_needed && obj.hasOwnProperty('pass') && docs[0].userpass == obj.pass)) { - Functions.check_inlist(coll, guid, socket, offline, undefined, "place 13"); - db.collection(coll).find({now_playing:true}, function(err, np){ - if(err !== null) console.log(err); - if(np !== null && np !== undefined && np.length == 1 && np[0].id == id){ - var startTime = docs[0].startTime; - if(startTime+parseInt(np[0].duration)<=Functions.get_time()+5) { - change_song(coll, false, id, docs); - } - } - }); - } else { - socket.emit("auth_required"); - } - }) - }); - } else { - var result = { - msg: { - expected: "object", - got: typeof(obj) - }, - }; - socket.emit("update_required", result); + }; + socket.emit("update_required", result); + return; } + obj.id = obj.id + ""; + id = id + ""; + var callback_function = function() { + for (var i = 0; i < arguments.length; i++) { + if (typeof arguments[i] == "function") { + arguments[i](); + } + } + }; + db.collection(coll + "_settings").find(function(err, docs) { + var authentication_needed = false; + if ( + docs.length > 0 && + (docs[0].userpass != undefined && docs[0].userpass != "") + ) { + callback_function = Functions.getSessionAdminUser; + authentication_needed = true; + } + callback_function(Functions.getSession(socket), coll, function(userpass) { + if (userpass != "" || obj.pass == undefined) { + obj.pass = userpass; + } else { + obj.pass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(obj.pass)) + .digest("base64"); + } + if ( + !authentication_needed || + (authentication_needed && + obj.hasOwnProperty("pass") && + docs[0].userpass == obj.pass) + ) { + Functions.check_inlist( + coll, + guid, + socket, + offline, + undefined, + "place 13" + ); + db.collection(coll).find({ now_playing: true }, function(err, np) { + if (err !== null) console.log(err); + if ( + np !== null && + np !== undefined && + np.length == 1 && + np[0].id == id + ) { + var startTime = docs[0].startTime; + if ( + startTime + parseInt(np[0].duration) <= + Functions.get_time() + 5 + ) { + change_song(coll, false, id, docs); + } + } + }); + } else { + socket.emit("auth_required"); + } + }); + }); + } else { + var result = { + msg: { + expected: "object", + got: typeof obj + } + }; + socket.emit("update_required", result); + } } function send_play(coll, socket, broadcast) { - //coll = coll.replace(/ /g,''); - db.collection(coll).find({now_playing:true}, function(err, np){ - db.collection(coll + "_settings").find(function(err, conf){ - if(err !== null) console.log(err); - try{ - if(Functions.get_time()-conf[0].startTime > np[0].duration){ - change_song(coll, false, np[0].id, conf); - } else if(conf !== null && conf !== undefined && conf.length !== 0) - { - if(conf[0].adminpass !== "") conf[0].adminpass = true; - if(conf[0].hasOwnProperty("userpass") && conf[0].userpass != "") conf[0].userpass = true; - else conf[0].userpass = false; - if(!np.hasOwnProperty("start")) np.start = 0; - if(!np.hasOwnProperty("end")) np.end = np.duration; - toSend = {np: np, conf: conf, time: Functions.get_time()}; - if(socket === undefined) { - io.to(coll).emit("np", toSend); - // - getNextSong(coll, undefined) - var url = 'https://img.youtube.com/vi/'+np[0].id+'/mqdefault.jpg'; - if(np[0].source == "soundcloud") url = np[0].thumbnail; - sendColor(coll, false, url); - } else { - var url = 'https://img.youtube.com/vi/'+np[0].id+'/mqdefault.jpg'; - if(np[0].source == "soundcloud") url = np[0].thumbnail; - sendColor(coll, socket, url); - if(broadcast) { - socket.to(coll).emit("np", toSend); - return; - } - socket.emit("np", toSend); - } - } - } catch(e){ - if(socket) { - if(broadcast) { - socket.to(coll).emit("np", {}); - return; - } - socket.emit("np", {}); - } else { - io.to(coll).emit("np", {}); - } + //coll = coll.replace(/ /g,''); + db.collection(coll).find({ now_playing: true }, function(err, np) { + db.collection(coll + "_settings").find(function(err, conf) { + if (err !== null) console.log(err); + try { + if (Functions.get_time() - conf[0].startTime > np[0].duration) { + change_song(coll, false, np[0].id, conf); + } else if (conf !== null && conf !== undefined && conf.length !== 0) { + if (conf[0].adminpass !== "") conf[0].adminpass = true; + if (conf[0].hasOwnProperty("userpass") && conf[0].userpass != "") + conf[0].userpass = true; + else conf[0].userpass = false; + if (!np.hasOwnProperty("start")) np.start = 0; + if (!np.hasOwnProperty("end")) np.end = np.duration; + toSend = { np: np, conf: conf, time: Functions.get_time() }; + if (socket === undefined) { + io.to(coll).emit("np", toSend); + // + getNextSong(coll, undefined); + var url = + "https://img.youtube.com/vi/" + np[0].id + "/mqdefault.jpg"; + if (np[0].source == "soundcloud") url = np[0].thumbnail; + sendColor(coll, false, url); + } else { + var url = + "https://img.youtube.com/vi/" + np[0].id + "/mqdefault.jpg"; + if (np[0].source == "soundcloud") url = np[0].thumbnail; + sendColor(coll, socket, url); + if (broadcast) { + socket.to(coll).emit("np", toSend); + return; } - }); + socket.emit("np", toSend); + } + } + } catch (e) { + if (socket) { + if (broadcast) { + socket.to(coll).emit("np", {}); + return; + } + socket.emit("np", {}); + } else { + io.to(coll).emit("np", {}); + } + } }); + }); } function sendColor(coll, socket, url, ajax, res) { - if(coll != undefined && typeof(coll) == "string") { - //coll = coll.replace(/ /g,''); - } - if(url.indexOf("://") == -1) url = 'https://img.youtube.com/vi/'+url+'/mqdefault.jpg'; - //var url = 'https://img.youtube.com/vi/'+id+'/mqdefault.jpg'; + if (coll != undefined && typeof coll == "string") { + //coll = coll.replace(/ /g,''); + } + if (url.indexOf("://") == -1) + url = "https://img.youtube.com/vi/" + url + "/mqdefault.jpg"; + //var url = 'https://img.youtube.com/vi/'+id+'/mqdefault.jpg'; - Jimp.read(url).then(function (image) { - - var c = ColorThief.getColor(image); - if(ajax) { - res.header({"Content-Type": "application/json"}); - res.status(200).send(c); - return; + Jimp.read(url) + .then(function(image) { + var c = ColorThief.getColor(image); + if (ajax) { + res.header({ "Content-Type": "application/json" }); + res.status(200).send(c); + return; + } else { + if (socket) { + socket.emit("color", { color: c, only: true }); } else { - if(socket) { - socket.emit("color", {color: c, only: true}); - } else { - io.to(coll).emit("color", {color: c, only: false}); - } - } - }).catch(function(err) { - console.log("Crashed on fetching image, url is " + url); - console.log("Is ajax: " + ajax); - if(ajax) { - res.header({"Content-Type": "application/json"}); - res.status(404); - return; + io.to(coll).emit("color", { color: c, only: false }); } + } + }) + .catch(function(err) { + console.log("Crashed on fetching image, url is " + url); + console.log("Is ajax: " + ajax); + if (ajax) { + res.header({ "Content-Type": "application/json" }); + res.status(404); + return; + } }); } function getNextSong(coll, socket, callback) { - //coll = coll.replace(/ /g,''); - db.collection(coll).aggregate([{ - $match:{ - views:{ - $exists: false - }, - type:{ - $ne: "suggested" - } + //coll = coll.replace(/ /g,''); + db.collection(coll).aggregate( + [ + { + $match: { + views: { + $exists: false + }, + type: { + $ne: "suggested" + } } - }, { - $sort:{ - now_playing: 1, - votes:-1, - added:1, - title: 1 + }, + { + $sort: { + now_playing: 1, + votes: -1, + added: 1, + title: 1 } - }, { - $limit:1 - }], function(err, doc) { - if(doc.length == 1) { - var thumbnail = ""; - var source = "youtube"; - if(doc[0].source && doc[0].source == "soundcloud") { - source = "soundcloud"; - thumbnail = doc[0].thumbnail; - } - if(socket != undefined) { - socket.emit("next_song", {videoId: doc[0].id, title: doc[0].title, source: source, thumbnail: thumbnail}); - } else { - io.to(coll).emit("next_song", {videoId: doc[0].id, title: doc[0].title, source: source, thumbnail: thumbnail}); - } + }, + { + $limit: 1 + } + ], + function(err, doc) { + if (doc.length == 1) { + var thumbnail = ""; + var source = "youtube"; + if (doc[0].source && doc[0].source == "soundcloud") { + source = "soundcloud"; + thumbnail = doc[0].thumbnail; } - if(typeof(callback) == "function") callback(); - }); + if (socket != undefined) { + socket.emit("next_song", { + videoId: doc[0].id, + title: doc[0].title, + source: source, + thumbnail: thumbnail + }); + } else { + io.to(coll).emit("next_song", { + videoId: doc[0].id, + title: doc[0].title, + source: source, + thumbnail: thumbnail + }); + } + } + if (typeof callback == "function") callback(); + } + ); } module.exports.sendColor = sendColor; diff --git a/server/public/assets/js/channel.js b/server/public/assets/js/channel.js index b43b8444..81e9e8ae 100644 --- a/server/public/assets/js/channel.js +++ b/server/public/assets/js/channel.js @@ -1,245 +1,321 @@ var Channel = { - init: function() { - if(window.location.hash == "#small" || inIframe()) { - small_player = true; - document.querySelector("footer").style.display = "none"; - //addJoinBox(); - //hideAllExtra(); - //document.querySelectorAll(".tab.col.s3")[1].remove(); - //document.querySelectorAll(".tab.col.s3")[1].remove(); - } - if(client) { - Helper.addClass(".tabs", "hide"); - Helper.removeClass("#wrapper", "tabs_height"); - Helper.addClass("#wrapper", "client-wrapper"); - if(!Helper.mobilecheck()) { - Helper.tooltip(".skip_next_client", { - delay: 5, - position: "bottom", - html: "Skip" - }); - } - Helper.addClass("#chan", "chan-client"); - Helper.addClass("#results", "client-results-height"); - Helper.addClass(".pagination-results", "client-pagination-height"); - Helper.addClass(".control-list", "client-control-list"); - } else { - if(!api_key.hasOwnProperty("soundcloud")) soundcloud_enabled = false; - else { - /*SC.initialize({ + init: function() { + if (window.location.hash == "#small" || inIframe()) { + small_player = true; + document.querySelector("footer").style.display = "none"; + //addJoinBox(); + //hideAllExtra(); + //document.querySelectorAll(".tab.col.s3")[1].remove(); + //document.querySelectorAll(".tab.col.s3")[1].remove(); + } + if (client) { + Helper.addClass(".tabs", "hide"); + Helper.removeClass("#wrapper", "tabs_height"); + Helper.addClass("#wrapper", "client-wrapper"); + if (!Helper.mobilecheck()) { + Helper.tooltip(".skip_next_client", { + delay: 5, + position: "bottom", + html: "Skip" + }); + } + Helper.addClass("#chan", "chan-client"); + Helper.addClass("#results", "client-results-height"); + Helper.addClass(".pagination-results", "client-pagination-height"); + Helper.addClass(".control-list", "client-control-list"); + } else { + if (!api_key.hasOwnProperty("soundcloud")) soundcloud_enabled = false; + else { + /*SC.initialize({ client_id: api_key.soundcloud }, function() { });*/ - } - if(cast_ready_connect || chromecastAvailable || chromecastReady) { - Helper.addClass(".volume-container", "volume-container-cast"); - } - if(!embed) { - document.querySelector("#main-container").insertAdjacentHTML("beforeend", "keyboard_arrow_right"); - document.querySelector("#hide-playlist").style.left = (document.querySelector("#video-container").offsetWidth - document.querySelector("#hide-playlist").offsetWidth) + "px"; - } - //Player.soundcloud_player = document.querySelector("#soundcloud_player"); + } + if (cast_ready_connect || chromecastAvailable || chromecastReady) { + Helper.addClass(".volume-container", "volume-container-cast"); + } + if (!embed) { + document + .querySelector("#main-container") + .insertAdjacentHTML( + "beforeend", + "keyboard_arrow_right" + ); + document.querySelector("#hide-playlist").style.left = + document.querySelector("#video-container").offsetWidth - + document.querySelector("#hide-playlist").offsetWidth + + "px"; + } + //Player.soundcloud_player = document.querySelector("#soundcloud_player"); + } + List.calculate_song_heights(); + Admin.logged_in = false; + Admin.display_logged_out(); + number_suggested = 0; + var no_socket = true; + + //chan = Helper.decodeChannelName(Helper.html("#chan")); + var _p = window.location.pathname; + if (_p.substring(0, 1) == "/") _p = _p.substring(1); + if (_p.substring(_p.length - 1) == "/") _p = _p.substring(0, _p.length - 1); + chan = Helper.decodeChannelName(_p); + + mobile_beginning = Helper.mobilecheck(); + var side = Helper.mobilecheck() ? "left" : "right"; + + if (window.location.hostname != "localhost") { + var page = window.location.pathname; + if (page.substring(page.length - 1) != "/") page += "/"; + ga("send", "pageview", page); + } + + window.onpopstate = function(e) { + Channel.onepage_load(); + }; + + if (window.location.hostname == "fb.zoff.me") { + Helper.addClass("footer", "hide"); + } + + if (window.location.hostname != "fb.zoff.me") Channel.share_link_modifier(); + if ( + window.location.hostname == "zoff.me" || + window.location.hostname == "fb.zoff.me" + ) + add = "https://zoff.me"; + else add = window.location.hostname; + + if (Player !== undefined && !client) { + Player.stopInterval = false; + } + + if (!client) { + //Helper.tabs('.playlist-tabs'); + Helper.tabs(".playlist-tabs-loggedIn", { + onShow: function(e) { + if (this.index == 2) { + document.getElementById("text-chat-input").focus(); + Chat.channel_received = 0; + Chat.all_received = 0; + Helper.addClass( + document.querySelector(".chat-link span.badge.new.white"), + "hide" + ); + document + .getElementById("favicon") + .setAttribute("href", "/assets/images/favicon.png"); + + chat_active = true; + unseen = false; + chat_unseen = false; + document + .getElementsByClassName("chat-link")[0] + .setAttribute("style", "color: white !important;"); + blinking = false; + //Helper.css("#chat-container", "display", "block"); + //Helper.css("#wrapper", "display", "none"); + //Helper.css("#suggestions", "display", "none"); + document.getElementById("text-chat-input").focus(); + Helper.css("#pageButtons", "display", "none"); + scrollChat(); + window.scrollTo(0, 0); + } } - List.calculate_song_heights(); - Admin.logged_in = false; - Admin.display_logged_out(); - number_suggested = 0; - var no_socket = true; + }); - //chan = Helper.decodeChannelName(Helper.html("#chan")); - var _p = window.location.pathname; - if(_p.substring(0,1) == "/") _p = _p.substring(1); - if(_p.substring(_p.length - 1) == "/") _p = _p.substring(0, _p.length - 1); - chan = Helper.decodeChannelName(_p); + if (window.location.hash == "#chat-container") { + M.Tabs.getInstance( + document.querySelector(".playlist-tabs-loggedIn") + ).select("chat-container"); + } else if (window.location.hash == "#suggestions") { + M.Tabs.getInstance( + document.querySelector(".playlist-tabs-loggedIn") + ).select("suggestions"); + } else if (window.location.hash == "#wrapper") { + M.Tabs.getInstance( + document.querySelector(".playlist-tabs-loggedIn") + ).select("wrapper"); + } - mobile_beginning = Helper.mobilecheck(); - var side = Helper.mobilecheck() ? "left" : "right"; + Helper.tabs(".chatTabs"); + } + Helper.tabs(".results-tabs"); + var sidenavElem = document.getElementsByClassName("sidenav")[0]; + M.Sidenav.init(sidenavElem, { + menuWidth: 310, + edge: side, + closeOnClick: false, + draggable: Helper.mobilecheck(), + onOpenStart: function(el) { + Helper.addClass(".hamburger-sidenav", "open"); + }, + onCloseStart: function(el) { + Helper.removeClass(".hamburger-sidenav", "open"); + } + }); + M.Collapsible.init( + document.getElementsByClassName("settings-collapsible")[0], + { + accordion: true + } + ); - if(window.location.hostname != "localhost") { - var page = window.location.pathname; - if(page.substring(page.length - 1) != "/") page += "/"; - ga('send', 'pageview', page); + if (!client) { + M.Modal.init(document.getElementById("embed"), { + onCloseStart: function() { + document.querySelector(".embed-preview").innerHTML = ""; } + }); + } else { + Helper.removeElement("#embed"); + Helper.removeElement(".embed-button-footer"); + Helper.removeElement(".tabs"); + } + M.Modal.init(document.getElementById("advanced_filter"), { + onCloseEnd: function() { + document.querySelector(".filter-results").innerHTML = ""; + document.getElementById("filtersearch_input").value = ""; + document.getElementById("filtersearch_input").blur(); + }, + onOpenEnd: function() { + document.getElementById("filtersearch_input").focus(); + } + }); - window.onpopstate = function(e){ - Channel.onepage_load(); - }; + M.FormSelect.init(document.querySelector(".category-advanced-select")); + M.Modal.init(document.getElementById("help")); + M.Modal.init(document.getElementById("contact")); + M.Modal.init(document.getElementById("channel-share-modal")); + M.Modal.init(document.getElementById("delete_song_alert"), { + dismissible: false + }); + M.Modal.init(document.getElementById("user_password"), { + dismissible: false + }); - if(window.location.hostname == "fb.zoff.me") { - Helper.addClass("footer", "hide"); + Channel.spotify_is_authenticated(spotify_authenticated); + + result_html = document.getElementById("temp-results-container"); + pagination_buttons_html = + "
" + + document.getElementsByClassName("pagination-results")[0].cloneNode(true) + .innerHTML + + "
"; + empty_results_html = Helper.html("#empty-results-container"); + not_import_html = Helper.html(".not-imported-container"); + not_export_html = Helper.html(".not-exported-container"); + Helper.setHtml(".not-imported-container", ""); + Helper.setHtml(".not-exported-container", ""); + + if (socket === undefined) { + no_socket = false; + if (window.location.port != "") { + add = add + ":" + window.location.port + "/"; + } + socket = io.connect( + "" + add, + connection_options + ); + socket.on("update_required", function(msg) { + if (window.location.hostname == "localhost") { + console.error(msg); + return; } + window.location.reload(true); + }); + } - if(window.location.hostname != "fb.zoff.me") Channel.share_link_modifier(); - if(window.location.hostname == "zoff.me" || window.location.hostname == "fb.zoff.me") add = "https://zoff.me"; - else add = window.location.hostname; + Crypt.init(); - if(Player !== undefined && !client) { - Player.stopInterval = false; + setup_auth_listener(); + + if (Crypt.get_offline()) { + document.getElementsByClassName("offline_switch_class")[0].checked = true; + change_offline(true, offline); + } + if ( + !Helper.mobilecheck() && + (document.querySelectorAll("#alreadychannel").length === 0 || + !Hostcontroller.old_id || + document.getElementById("code-text").innerText.toUpperCase() == + "ABBADUR") + ) + setup_host_initialization(); + setup_suggested_listener(); + if (!Helper.mobilecheck()) { + showOnSmallNotMobile(); + } + if ( + document.querySelectorAll("#alreadychannel").length === 0 || + Helper.mobilecheck() + ) { + setup_now_playing_listener(); + get_list_listener(); + + if (!client) { + setup_viewers_listener(); + } + } else { + Helper.css("#channel-load", "display", "none"); + Helper.css("#player", "opacity", "1"); + Helper.css("#controls", "opacity", "1"); + Helper.css(".playlist", "opacity", "1"); + if (!client) { + Player.readyLooks(); + Playercontrols.initYoutubeControls(Player.player); + Playercontrols.initSlider(); + if (player_ready) { + try { + Player.player.setVolume(Crypt.get_volume()); + } catch (e) {} + try { + if (scUsingWidget) + Player.soundcloud_player.setVolume( + embed ? 1 : Crypt.get_volume() + ); + else + Player.soundcloud_player.setVolume( + embed ? 1 : Crypt.get_volume() / 100 + ); + } catch (e) {} } + Helper.removeClass(".video-container", "no-opacity"); + var codeURL = "https://remote." + window.location.hostname + "/" + id; + Helper.setHtml("#code-text", id); + document + .getElementById("code-qr") + .setAttribute( + "src", + "https://chart.googleapis.com/chart?chs=221x221&cht=qr&choe=UTF-8&chld=L|1&chl=" + + codeURL + ); + document.getElementById("code-link").setAttribute("href", codeURL); + } + } - if(!client) { - //Helper.tabs('.playlist-tabs'); - Helper.tabs('.playlist-tabs-loggedIn', { - onShow: function(e) { - if(this.index == 2) { - document.getElementById("text-chat-input").focus(); - Chat.channel_received = 0; - Chat.all_received = 0; - Helper.addClass(document.querySelector(".chat-link span.badge.new.white"), "hide"); - document.getElementById("favicon").setAttribute("href", "/assets/images/favicon.png"); - - chat_active = true; - unseen = false; - chat_unseen = false; - document.getElementsByClassName("chat-link")[0].setAttribute("style", "color: white !important;"); - blinking = false; - //Helper.css("#chat-container", "display", "block"); - //Helper.css("#wrapper", "display", "none"); - //Helper.css("#suggestions", "display", "none"); - document.getElementById("text-chat-input").focus(); - Helper.css("#pageButtons", "display", "none"); - scrollChat(); - window.scrollTo(0, 0); - } - } - }); - - if(window.location.hash == "#chat-container") { - M.Tabs.getInstance(document.querySelector('.playlist-tabs-loggedIn')).select("chat-container"); - } else if(window.location.hash == "#suggestions") { - M.Tabs.getInstance(document.querySelector('.playlist-tabs-loggedIn')).select("suggestions"); - } else if(window.location.hash == "#wrapper") { - M.Tabs.getInstance(document.querySelector('.playlist-tabs-loggedIn')).select("wrapper"); - } - - Helper.tabs('.chatTabs'); - } - Helper.tabs('.results-tabs'); - var sidenavElem = document.getElementsByClassName("sidenav")[0]; - M.Sidenav.init(sidenavElem, { - menuWidth: 310, - edge: side, - closeOnClick: false, - draggable: Helper.mobilecheck(), - onOpenStart: function(el) { - Helper.addClass(".hamburger-sidenav", "open"); - }, - onCloseStart: function(el) { - Helper.removeClass(".hamburger-sidenav", "open"); - }, - }); - M.Collapsible.init(document.getElementsByClassName("settings-collapsible")[0], { - accordion : true - }); - - if(!client) { - M.Modal.init(document.getElementById("embed"), { - onCloseStart: function() { - document.querySelector(".embed-preview").innerHTML = ""; - } - }); - } else { - Helper.removeElement("#embed"); - Helper.removeElement(".embed-button-footer"); - Helper.removeElement(".tabs"); - } - M.Modal.init(document.getElementById("advanced_filter"), { - onCloseEnd: function() { - document.querySelector(".filter-results").innerHTML = ""; - document.getElementById("filtersearch_input").value = ""; - document.getElementById("filtersearch_input").blur(); - }, - onOpenEnd: function() { - document.getElementById("filtersearch_input").focus(); - } - }); - - M.FormSelect.init(document.querySelector('.category-advanced-select')); - M.Modal.init(document.getElementById("help")); - M.Modal.init(document.getElementById("contact")); - M.Modal.init(document.getElementById("channel-share-modal")); - M.Modal.init(document.getElementById("delete_song_alert"), { - dismissible: false - }); - M.Modal.init(document.getElementById("user_password"), { - dismissible: false, - }); - - Channel.spotify_is_authenticated(spotify_authenticated); - - result_html = document.getElementById("temp-results-container"); - pagination_buttons_html = "
" + document.getElementsByClassName("pagination-results")[0].cloneNode(true).innerHTML + "
"; - empty_results_html = Helper.html("#empty-results-container"); - not_import_html = Helper.html(".not-imported-container"); - not_export_html = Helper.html(".not-exported-container"); - Helper.setHtml(".not-imported-container", ""); - Helper.setHtml(".not-exported-container", ""); - - if(socket === undefined){ - no_socket = false; - socket = io.connect(''+add, connection_options); - socket.on('update_required', function(msg) { - if(window.location.hostname == "localhost") { - console.error(msg); - return; - } - window.location.reload(true); - }); - } - - Crypt.init(); - - setup_auth_listener(); - - if(Crypt.get_offline()){ - document.getElementsByClassName("offline_switch_class")[0].checked = true; - change_offline(true, offline); - } - if(!Helper.mobilecheck() && (document.querySelectorAll("#alreadychannel").length === 0 || !Hostcontroller.old_id || document.getElementById("code-text").innerText.toUpperCase() == "ABBADUR")) setup_host_initialization(); - setup_suggested_listener(); - if(!Helper.mobilecheck()) { - showOnSmallNotMobile(); - } - if(document.querySelectorAll("#alreadychannel").length === 0 || Helper.mobilecheck()){ - setup_now_playing_listener(); - get_list_listener(); - - if(!client) { - setup_viewers_listener(); - } - } else { - Helper.css("#channel-load", "display", "none"); - Helper.css("#player", "opacity", "1"); - Helper.css("#controls", "opacity", "1"); - Helper.css(".playlist", "opacity", "1"); - if(!client) { - Player.readyLooks(); - Playercontrols.initYoutubeControls(Player.player); - Playercontrols.initSlider(); - if(player_ready) { - try { - Player.player.setVolume(Crypt.get_volume()); - } catch(e){} - try { - if(scUsingWidget) Player.soundcloud_player.setVolume(embed ? 1 : Crypt.get_volume()); - else Player.soundcloud_player.setVolume(embed ? 1 : Crypt.get_volume() / 100); - } catch(e){} - } - Helper.removeClass(".video-container", "no-opacity"); - var codeURL = "https://remote."+window.location.hostname+"/"+id; - Helper.setHtml("#code-text", id); - document.getElementById("code-qr").setAttribute("src", "https://chart.googleapis.com/chart?chs=221x221&cht=qr&choe=UTF-8&chld=L|1&chl="+codeURL); - document.getElementById("code-link").setAttribute("href", codeURL); - } - } - - - if(!client) { - if(!Helper.mobilecheck()) { - var shareCodeUrl = window.location.protocol + "//client."+window.location.hostname+"/r/"+btoa(encodeURIComponent(chan.toLowerCase())); - document.getElementById("share-join-qr").setAttribute("src", "https://chart.googleapis.com/chart?chs=221x221&cht=qr&choe=UTF-8&chld=L|1&chl="+shareCodeUrl); - Helper.setHtml("#channel-name-join", "client." + window.location.hostname + "/" + encodeURIComponent(chan.toLowerCase())); - } /*else if(small_player) { + if (!client) { + if (!Helper.mobilecheck()) { + var shareCodeUrl = + window.location.protocol + + "//client." + + window.location.hostname + + "/r/" + + btoa(encodeURIComponent(chan.toLowerCase())); + document + .getElementById("share-join-qr") + .setAttribute( + "src", + "https://chart.googleapis.com/chart?chs=221x221&cht=qr&choe=UTF-8&chld=L|1&chl=" + + shareCodeUrl + ); + Helper.setHtml( + "#channel-name-join", + "client." + + window.location.hostname + + "/" + + encodeURIComponent(chan.toLowerCase()) + ); + } /*else if(small_player) { document.querySelector("#channel-share-modal .modal-content").innerHTML = "

To listen to this channel with more features, go to

https://zoff.me/" + encodeURIComponent(chan.toLowerCase()) + "

circle-logo-zoff"; //M.Modal.getInstance(document.getElementById("channel-share-modal")).open(); if(!Helper.mobilecheck()) { @@ -248,110 +324,119 @@ var Channel = { }, 10000); } }*/ - } else { - Helper.removeElement(".video-container"); - Helper.removeElement(".offline-panel"); - Helper.removeElement(".remote-panel"); - Helper.removeElement(".mobile-remote-panel"); - Helper.removeElement(".import-panel"); - Helper.removeElement(".export-panel"); - } - if(no_socket || Helper.mobilecheck()){ - emit_list(); - } + } else { + Helper.removeElement(".video-container"); + Helper.removeElement(".offline-panel"); + Helper.removeElement(".remote-panel"); + Helper.removeElement(".mobile-remote-panel"); + Helper.removeElement(".import-panel"); + Helper.removeElement(".export-panel"); + } + if (no_socket || Helper.mobilecheck()) { + emit_list(); + } - if(!Helper.mobilecheck()) { - if(!client) { - Helper.tooltip("#chan", { - delay: 5, - position: "bottom", - html: "Show join URL", - }); - } + if (!Helper.mobilecheck()) { + if (!client) { + Helper.tooltip("#chan", { + delay: 5, + position: "bottom", + html: "Show join URL" + }); + } - Helper.tooltip("#viewers", { - delay: 5, - position: "top", - html: "Viewers" - }); + Helper.tooltip("#viewers", { + delay: 5, + position: "top", + html: "Viewers" + }); - Helper.tooltip("#addToOtherList", { - delay: 5, - position: "top", - html: "Add to other playlist" - }); + Helper.tooltip("#addToOtherList", { + delay: 5, + position: "top", + html: "Add to other playlist" + }); - Helper.tooltip("#fullscreen", { - delay: 5, - position: "top", - html: "Fullscreen" - }); + Helper.tooltip("#fullscreen", { + delay: 5, + position: "top", + html: "Fullscreen" + }); - Helper.tooltip(".search-btn-container", { - delay: 5, - position: "bottom", - html: "Search" - }); + Helper.tooltip(".search-btn-container", { + delay: 5, + position: "bottom", + html: "Search" + }); + Helper.tooltip(".shuffle-btn-container", { + delay: 5, + position: "bottom", + html: "Shuffle" + }); - Helper.tooltip(".shuffle-btn-container", { - delay: 5, - position: "bottom", - html: "Shuffle", - }); + Helper.tooltip("#settings", { + delay: 5, + position: "bottom", + html: "Settings" + }); + } - Helper.tooltip("#settings", { - delay: 5, - position: "bottom", - html: "Settings", - }); - } + if (!client) { + window.onYouTubeIframeAPIReady = Player.onYouTubeIframeAPIReady; + if ( + Player.player === "" || + Player.player === undefined || + Helper.mobilecheck() + ) + Player.loadPlayer(); + } else { + Player.loadSoundCloudPlayer(); + } + //} - if(!client) { - window.onYouTubeIframeAPIReady = Player.onYouTubeIframeAPIReady; - if(Player.player === "" || Player.player === undefined || Helper.mobilecheck()) Player.loadPlayer(); - } else { - Player.loadSoundCloudPlayer(); - } - //} + if (Helper.mobilecheck()) { + if (!client) { + Mobile_remote.initiate_volume(); + } + Helper.addClass(".close-settings", "hide"); + } else { + if (!client) { + Channel.window_width_volume_slider(); + } + } - if(Helper.mobilecheck()) { - if(!client) { - Mobile_remote.initiate_volume(); - } - Helper.addClass(".close-settings", "hide"); - } else { - if(!client) { - Channel.window_width_volume_slider(); - } - } + setup_admin_listener(); + setup_list_listener(); + if (!client) { + setup_chat_listener(); + get_history(); + } + if (client || Helper.mobilecheck()) { + get_list_ajax(); + get_np_ajax(); + } - setup_admin_listener(); - setup_list_listener(); - if(!client) { - setup_chat_listener(); - get_history(); - } - if(client || Helper.mobilecheck()){ - get_list_ajax(); - get_np_ajax(); + try { + if ( + !Helper.msieversion() && + !Helper.mobilecheck() && + !client && + Notification != undefined + ) + Notification.requestPermission(); + } catch (e) {} + document.getElementsByClassName("search_input")[0].focus(); - } + Helper.sample(); + if (!Helper.mobilecheck() && !client) { + Helper.tooltip(".castButton", { + delay: 5, + position: "top", + html: "Cast Zoff to TV" + }); - try { - if(!Helper.msieversion() && !Helper.mobilecheck() && !client && Notification != undefined) Notification.requestPermission(); - }catch(e){} - document.getElementsByClassName("search_input")[0].focus(); - - Helper.sample(); - if(!Helper.mobilecheck() && !client) { - Helper.tooltip('.castButton', { - delay: 5, - position: "top", - html: "Cast Zoff to TV" - }); - - /*$("#color_embed").spectrum({ + /*$("#color_embed").spectrum({ color: "#808080", change: function(c) { color = c.toHexString().substring(1); // #ff0000 @@ -363,383 +448,513 @@ var Channel = { }, });*/ - /*Helper.addClass(".sp-choose", "hide"); + /*Helper.addClass(".sp-choose", "hide"); Helper.addClass(".sp-cancel", "btn-flat waves-effect waves-red"); Helper.removeClass(".sp-cancel", "sp-cancel"); document.getElementsByClassName("sp-button-container")[0].insertAdjacentHTML("beforeend", "
CHOOSE"); */ - } + } - addListener("click", ".sp-choose-link", function(e) { - event.preventDefault(); - document.getElementsByClassName("sp-choose")[0].click(); - }); + addListener("click", ".sp-choose-link", function(e) { + event.preventDefault(); + document.getElementsByClassName("sp-choose")[0].click(); + }); - //$("#results" ).hover( function() { Helper.removeClass(".result", "hoverResults"); i = 0; }, function(){ }); - document.getElementById("search").focus(); - Helper.css("#embed-button", "display", "inline-block"); - document.getElementById("search").setAttribute("placeholder", "Search..."); + //$("#results" ).hover( function() { Helper.removeClass(".result", "hoverResults"); i = 0; }, function(){ }); + document.getElementById("search").focus(); + Helper.css("#embed-button", "display", "inline-block"); + document.getElementById("search").setAttribute("placeholder", "Search..."); - if(!client) { - Helper.addClass("footer", "padding-bottom-novideo"); - document.getElementById("embed-area").value = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - } + if (!client) { + Helper.addClass("footer", "padding-bottom-novideo"); + document.getElementById("embed-area").value = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + } - if(!/chrom(e|ium)/.test(navigator.userAgent.toLowerCase()) && !Helper.mobilecheck() && !client){ - Helper.css(".castButton", "display", "none"); - } + if ( + !/chrom(e|ium)/.test(navigator.userAgent.toLowerCase()) && + !Helper.mobilecheck() && + !client + ) { + Helper.css(".castButton", "display", "none"); + } - Helper.log(["chromecastAvailable " + chromecastAvailable, "chromecastReady " + chromecastReady]); + Helper.log([ + "chromecastAvailable " + chromecastAvailable, + "chromecastReady " + chromecastReady + ]); - if(chromecastAvailable && !client){ - hide_native(1); - } else if(chromecastReady && !client) { + if (chromecastAvailable && !client) { + hide_native(1); + } else if (chromecastReady && !client) { + initializeCastApi(); + } else if (!client) { + window["__onGCastApiAvailable"] = function(loaded, errorInfo) { + if (loaded) { + setTimeout(function() { + chromecastReady = true; initializeCastApi(); - } else if(!client){ - window['__onGCastApiAvailable'] = function(loaded, errorInfo) { - if (loaded) { - setTimeout(function(){ - chromecastReady = true; - initializeCastApi(); - }, 1000); - } else { - chromecastReady = true; - } - } - } - Channel.listeners(true); - Channel.add_context_menu(); - - if(!Helper.mobilecheck() && navigator.userAgent.match(/iPad/i) == null){ - setTimeout(function(){Channel.set_title_width();}, 100); - } - }, - - set_title_width: function(start){ - if(window.innerWidth > 600){ - var add_width = document.getElementsByClassName("brand-logo")[0].offsetWidth - if(start){ - add_width = window.innerWidth * 0.15; - } - var test_against_width = window.innerWidth - document.getElementsByClassName("control-list")[0].offsetWidth - add_width - 11; - title_width = test_against_width; - document.getElementsByClassName("title-container")[0].style.width = title_width + "px"; + }, 1000); } else { - document.getElementsByClassName("title-container")[0].style.width = "100%"; + chromecastReady = true; } - }, + }; + } + Channel.listeners(true); + Channel.add_context_menu(); - spotify_is_authenticated: function(bool){ - if(bool){ - Helper.log([ - "Spotify is authenticated", - "access_token: " + access_token_data.access_token, - "token_type:" + access_token_data.token_type, - "expires_in: " + access_token_data.expires_in - ]); + if (!Helper.mobilecheck() && navigator.userAgent.match(/iPad/i) == null) { + setTimeout(function() { + Channel.set_title_width(); + }, 100); + } + }, - Helper.css(".spotify_authenticated", "display", "block"); - Helper.css(".spotify_unauthenticated", "display", "none"); - } else { - Helper.log(["Spotify is not authenticated"]); - Helper.css(".spotify_authenticated", "display", "none"); - Helper.css(".spotify_unauthenticated", "display", "flex"); + set_title_width: function(start) { + if (window.innerWidth > 600) { + var add_width = document.getElementsByClassName("brand-logo")[0] + .offsetWidth; + if (start) { + add_width = window.innerWidth * 0.15; + } + var test_against_width = + window.innerWidth - + document.getElementsByClassName("control-list")[0].offsetWidth - + add_width - + 11; + title_width = test_against_width; + document.getElementsByClassName("title-container")[0].style.width = + title_width + "px"; + } else { + document.getElementsByClassName("title-container")[0].style.width = + "100%"; + } + }, + + spotify_is_authenticated: function(bool) { + if (bool) { + Helper.log([ + "Spotify is authenticated", + "access_token: " + access_token_data.access_token, + "token_type:" + access_token_data.token_type, + "expires_in: " + access_token_data.expires_in + ]); + + Helper.css(".spotify_authenticated", "display", "block"); + Helper.css(".spotify_unauthenticated", "display", "none"); + } else { + Helper.log(["Spotify is not authenticated"]); + Helper.css(".spotify_authenticated", "display", "none"); + Helper.css(".spotify_unauthenticated", "display", "flex"); + } + }, + + add_context_menu: function() { + addListener("contextmenu", ".vote-container", function(e) { + if (hostMode) { + return; + } + this.preventDefault(); + this.preventDefault(); + var that = this; + contextListener(e, that); + }); + + addListener("contextmenu", ".add-suggested", function(e) { + this.preventDefault(); + var that = this; + contextListener(e, that); + }); + + addListener("click", ".list-remove", function(e) { + this.preventDefault(); + var that = this; + contextListener(e, that); + }); + }, + + share_link_modifier: function() { + document + .getElementById("facebook-code-link") + .setAttribute( + "href", + "https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/" + + chan.toLowerCase() + ); + document + .getElementById("facebook-code-link") + .setAttribute( + "onclick", + "window.open('https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/" + + chan.toLowerCase() + + "', 'Share Playlist','width=600,height=300'); return false;" + ); + document + .getElementById("twitter-code-link") + .setAttribute( + "href", + "https://twitter.com/intent/tweet?url=https://zoff.me/" + + chan.toLowerCase() + + "&text=Check%20out%20this%20playlist%20" + + chan.toLowerCase() + + "%20on%20Zoff!&via=zoffmusic" + ); + document + .getElementById("twitter-code-link") + .setAttribute( + "onclick", + "window.open('https://twitter.com/intent/tweet?url=https://zoff.me/" + + chan.toLowerCase() + + "/&text=Check%20out%20this%20playlist%20" + + chan.toLowerCase() + + "%20on%20Zoff!&via=zoffmusic','Share Playlist','width=600,height=300'); return false;" + ); + }, + + window_width_volume_slider: function() { + if (window.innerWidth <= 600 && slider_type == "horizontal") { + slider_type = "vertical"; + Playercontrols.initSlider(); + } else if (window.innerWidth > 600 && slider_type == "vertical") { + slider_type = "horizontal"; + Playercontrols.initSlider(); + Helper.removeClass(".volume-container", "hide"); + } + }, + + listeners: function(on) { + var scrollListener = function(e) { + if (!programscroll) { + userscroll = true; + if ( + document.getElementById("chatchannel").scrollTop + + document.getElementById("chatchannel").offsetHeight >= + document.getElementById("chatchannel").scrollHeight + ) { + userscroll = false; } - }, - - add_context_menu: function() { - addListener("contextmenu", ".vote-container", function(e) { - if(hostMode) { - return; - } - this.preventDefault(); - this.preventDefault(); - var that = this; - contextListener(e, that); - }); - - addListener("contextmenu", ".add-suggested", function(e) { - this.preventDefault(); - var that = this; - contextListener(e, that); - }); - - addListener("click", ".list-remove", function(e) { - this.preventDefault(); - var that = this; - contextListener(e, that); - }); - }, - - share_link_modifier: function(){ - document.getElementById("facebook-code-link").setAttribute("href", "https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/" + chan.toLowerCase()); - document.getElementById("facebook-code-link").setAttribute("onclick", "window.open('https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/" + chan.toLowerCase() + "', 'Share Playlist','width=600,height=300'); return false;"); - document.getElementById("twitter-code-link").setAttribute("href", "https://twitter.com/intent/tweet?url=https://zoff.me/" + chan.toLowerCase() + "&text=Check%20out%20this%20playlist%20" + chan.toLowerCase() + "%20on%20Zoff!&via=zoffmusic"); - document.getElementById("twitter-code-link").setAttribute("onclick", "window.open('https://twitter.com/intent/tweet?url=https://zoff.me/" + chan.toLowerCase() + "/&text=Check%20out%20this%20playlist%20" + chan.toLowerCase() + "%20on%20Zoff!&via=zoffmusic','Share Playlist','width=600,height=300'); return false;"); - }, - - window_width_volume_slider: function() { - if(window.innerWidth <= 600 && slider_type == "horizontal") { - slider_type = "vertical"; - Playercontrols.initSlider(); - } else if(window.innerWidth > 600 && slider_type == "vertical") { - slider_type = "horizontal"; - Playercontrols.initSlider(); - Helper.removeClass(".volume-container", "hide"); + } + }; + var scrollAllListener = function(e) { + if (!programscroll) { + userscroll = true; + if ( + document.getElementById("chatall").scrollTop + + document.getElementById("chatall").offsetHeight >= + document.getElementById("chatall").scrollHeight + ) { + userscroll = false; } - }, + } + }; + if (!client) { + if (on) { + document + .getElementById("chatchannel") + .addEventListener("scroll", scrollListener); + document + .getElementById("chatall") + .addEventListener("scroll", scrollListener); + } else { + document + .getElementById("chatchannel") + .removeEventListener("scroll", scrollListener); + document + .getElementById("chatall") + .removeEventListener("scroll", scrollAllListener); + } + } + }, - listeners: function(on) { - var scrollListener = function(e) { - if(!programscroll) { - userscroll = true; - if(document.getElementById("chatchannel").scrollTop + document.getElementById("chatchannel").offsetHeight >= document.getElementById("chatchannel").scrollHeight) { - userscroll = false; - } - } - } - var scrollAllListener = function(e) { - if(!programscroll) { - userscroll = true; - if(document.getElementById("chatall").scrollTop+ document.getElementById("chatall").offsetHeight >= document.getElementById("chatall").scrollHeight) { - userscroll = false; - } - } - } - if(!client) { - if(on) { - document.getElementById("chatchannel").addEventListener("scroll", scrollListener); - document.getElementById("chatall").addEventListener("scroll", scrollListener); - } else { - document.getElementById("chatchannel").removeEventListener("scroll", scrollListener); - document.getElementById("chatall").removeEventListener("scroll", scrollAllListener); - } - } - }, + onepage_load: function() { + if (changing_to_frontpage) return; + if (user_auth_started) { + clearTimeout(durationTimeout); + Player.stopInterval = true; + user_auth_avoid = true; + if (!Helper.mobilecheck()) { + Helper.tooltip(".castButton", "destroy"); + Helper.tooltip("#viewers", "destroy"); + Helper.tooltip("#addToOtherList", "destroy"); + //$('.castButton-unactive').tooltip("destroy"); + Helper.tooltip("#offline-mode", "destroy"); + Helper.tooltip("#admin-lock", "destroy"); + } + } + var url_split = window.location.href.split("/"); + if ( + url_split[3].substr(0, 1) != "#!" && + url_split[3] !== "" && + !(url_split.length == 5 && url_split[4].substr(0, 1) == "#") + ) { + socket.emit("change_channel", { + channel: channel_before_move + }); + Admin.beginning = true; - onepage_load: function(){ - if(changing_to_frontpage) return; - if(user_auth_started) { - clearTimeout(durationTimeout); - Player.stopInterval = true; - user_auth_avoid = true; - if(!Helper.mobilecheck()) { - Helper.tooltip('.castButton', "destroy"); - Helper.tooltip("#viewers", "destroy"); - Helper.tooltip('#addToOtherList', 'destroy'); - //$('.castButton-unactive').tooltip("destroy"); - Helper.tooltip("#offline-mode", "destroy"); - Helper.tooltip('#admin-lock', "destroy"); - } - } - var url_split = window.location.href.split("/"); - if(url_split[3].substr(0,1) != "#!" && url_split[3] !== "" && !(url_split.length == 5 && url_split[4].substr(0,1) == "#")){ - socket.emit("change_channel", { - channel: channel_before_move - }); - Admin.beginning = true; - - chan = url_split[3].replace("#", ""); - document.getElementById("chan").innerHTML = Helper.upperFirst(chan); - var add = ""; - w_p = true; - //if(private_channel) add = Crypt.getCookie("_uI") + "_"; - - socket.emit("list", {version: parseInt(_VERSION), channel: add + chan.toLowerCase()}); - } else if(url_split[3] === "") { - /*if(client) { + chan = url_split[3].replace("#", ""); + document.getElementById("chan").innerHTML = Helper.upperFirst(chan); + var add = ""; + w_p = true; + //if(private_channel) add = Crypt.getCookie("_uI") + "_"; + socket.emit("list", { + version: parseInt(_VERSION), + channel: add + chan.toLowerCase() + }); + } else if (url_split[3] === "") { + /*if(client) { var host = window.location.hostname.split("."); window.location.hostname = host[host.length -1]; }*/ - Admin.display_logged_out(); - if(hostMode) { - Helper.removeClass("#main-row", "fullscreened"); - document.querySelector(".host_switch_class").checked = false - enable_host_mode(false); - } - var channel_before_move = chan.toLowerCase(); - clearTimeout(timed_remove_check); - changing_to_frontpage = true; - user_change_password = false; - clearTimeout(width_timeout); - if(fireplace_initiated){ - fireplace_initiated = false; - Player.fireplace.destroy(); - Helper.css("#fireplace_player", "display", "none"); - } - Helper.css("#channel-load", "display", "block"); - window.scrollTo(0, 0); + Admin.display_logged_out(); + if (hostMode) { + Helper.removeClass("#main-row", "fullscreened"); + document.querySelector(".host_switch_class").checked = false; + enable_host_mode(false); + } + var channel_before_move = chan.toLowerCase(); + clearTimeout(timed_remove_check); + changing_to_frontpage = true; + user_change_password = false; + clearTimeout(width_timeout); + if (fireplace_initiated) { + fireplace_initiated = false; + Player.fireplace.destroy(); + Helper.css("#fireplace_player", "display", "none"); + } + Helper.css("#channel-load", "display", "block"); + window.scrollTo(0, 0); - //Player.stopInterval = true; - Admin.beginning = true; - began = false; - durationBegun = false; + //Player.stopInterval = true; + Admin.beginning = true; + began = false; + durationBegun = false; - Helper.css("#embed-button", "display", "none"); - if(!Helper.mobilecheck()) { - Helper.tooltip(".castButton", "destroy"); - Helper.tooltip('#addToOtherList', 'destroy'); - Helper.tooltip("#viewers", "destroy"); - Helper.tooltip("#offline-mode", "destroy"); - Helper.tooltip("search-btn", "destroy"); - Helper.tooltip('#fullscreen', "destroy"); - if(M.Tooltip.getInstance(document.getElementById("admin-lock")) != undefined) { - Helper.tooltip('#admin-lock', "destroy"); - } - Helper.tooltip(".search-btn-container", "destroy"); - Helper.tooltip(".shuffle-btn-container", "destroy"); - Helper.tooltip("#settings", "destroy"); - } - Helper.removeElement("#seekToDuration"); - - M.Sidenav.getInstance(document.getElementsByClassName("sidenav")[0]).destroy(); - if(!client) { - if(!Helper.mobilecheck()) { - Helper.tooltip("#chan", "destroy"); - } - var tap_1 = document.querySelectorAll(".tap-target") - if(tap_1.length > 0 && M.TapTarget.getInstance(tap_1[0])) { - M.TapTarget.getInstance(tap_1[0]).close(); - } - } - clearTimeout(tap_target_timeout); - //before_toast(); - if(Helper.mobilecheck() || user_auth_avoid || client) { - Helper.log(["Removing all listeners"]); - //socket.emit("change_channel"); - //removeAllListeners(); - //socket.removeEventListener(id); - socket.emit("left_channel", { - channel: channel_before_move - }); - socket.emit("change_channel", { - channel: channel_before_move - }); - chan = ""; - socket.removeEventListener("np"); - socket.removeEventListener("id"); - socket.removeEventListener(id); - //socket.disconnect(); - } - socket.removeEventListener("chat.all"); - socket.removeEventListener("chat"); - socket.removeEventListener("conf"); - socket.removeEventListener("pw"); - socket.removeEventListener("toast"); - //socket.removeEventListener("id"); - socket.removeEventListener("channel"); - socket.removeEventListener("auth_required"); - socket.removeEventListener("auth_accepted"); - socket.removeEventListener("suggested"); - socket.removeEventListener("color"); - socket.removeEventListener("chat_history"); - Helper.ajax({ - url: "/", - method: "GET", - success: function(e){ - - if(!client) { - document.querySelector("#hide-playlist").remove(); - if(hiddenPlaylist) document.querySelector("main").style.maxWidth = ""; - hiddenPlaylist = false; - document.getElementById("volume-button").removeEventListener("click", Playercontrols.mute_video); - document.getElementById("playpause").removeEventListener("click", Playercontrols.play_pause); - document.getElementById("fullscreen").removeEventListener("click", Playercontrols.fullscreen); - } - Channel.listeners(false); - if(Helper.mobilecheck() || user_auth_avoid) { - video_id = ""; - song_title = ""; - } - - document.querySelectorAll("meta[name=theme-color]")[0].setAttribute("content", "#2D2D2D"); - - if(!Helper.mobilecheck() && !user_auth_avoid){ - Helper.removeElement("#playbar"); - Helper.removeElement("#main_components"); - Helper.addClass("#player_overlay", "player_bottom"); - Helper.addClass("#player", "player_bottom"); - Helper.addClass(".video-container", "frontpage-player"); - Helper.addClass("#main-row", "frontpage_modified_heights"); - Helper.css("#player", "opacity", "1"); - Helper.removeClass("#video-container", "no-opacity"); - document.getElementById("main-row").insertAdjacentHTML("afterbegin", "
"); - document.getElementById("player_bottom_overlay").insertAdjacentHTML("afterbegin", "close"); - document.getElementById("player_bottom_overlay").setAttribute("data-channel", channel_before_move.toLowerCase()); - Helper.removeElement("#playlist"); - } else { - try{ - Player.player.destroy(); - } catch(error){} - try { - Player.soundcloud_dead = true; - Player.soundcloud_player.kill(); - } catch(error){} - Player.player = ""; - document.title = "Zoff"; - } - - var response = document.createElement("div"); - response.innerHTML = e; - - var newList = response.querySelector("#lists-script").innerHTML; - newList = newList.trim().replace("window.lists = ", "").replace("window.lists=", ""); - newList = newList.substring(0, newList.length); - window.lists = JSON.parse(newList); - - response.querySelector("#lists-script").remove(); - Helper.removeElement("#sidenav-overlay"); - document.getElementsByTagName("main")[0].className = "center-align container"; - Helper.removeClass("#main-container", "channelpage"); - document.getElementById("main-container").setAttribute("style", ""); - document.getElementsByTagName("header")[0].innerHTML = response.querySelectorAll("header")[0].outerHTML; - - document.getElementsByTagName("header")[0].insertAdjacentHTML("afterend", response.querySelectorAll(".section.mega")[0].outerHTML); - //document.getElementsByTagName("header")[0].insertAdjacentHTML("afterend", response.querySelectorAll(".section.mobile-search")[0].innerHTML); - if(Helper.mobilecheck() || user_auth_avoid) { - document.getElementsByTagName("main")[0].innerHTML = response.querySelectorAll("main")[0].innerHTML; - } else { - document.getElementsByTagName("main")[0].insertAdjacentHTML("beforeend", response.querySelectorAll("#main_section_frontpage")[0].outerHTML); - } - Helper.removeClass(".page-footer", "padding-bottom-extra"); - Helper.removeClass(".page-footer", "padding-bottom-novideo"); - document.getElementById("favicon").setAttribute("href", "/assets/images/favicon-32x32.png"); - - Helper.log(["Socket", socket]); - if(document.querySelectorAll("#alreadyfp").length == 1){ - Frontpage.init(); - }else { - fromChannel = true; - frontpage = true; - Frontpage.init(); - } - - changing_to_frontpage = false; - - if(document.querySelectorAll("#alreadychannel").length === 0 && !user_auth_avoid){ - document.getElementsByTagName("head")[0].insertAdjacentHTML("beforeend", "
0 && M.TapTarget.getInstance(tap_1[0])) { + M.TapTarget.getInstance(tap_1[0]).close(); + } + } + clearTimeout(tap_target_timeout); + //before_toast(); + if (Helper.mobilecheck() || user_auth_avoid || client) { + Helper.log(["Removing all listeners"]); + //socket.emit("change_channel"); + //removeAllListeners(); + //socket.removeEventListener(id); + socket.emit("left_channel", { + channel: channel_before_move + }); + socket.emit("change_channel", { + channel: channel_before_move + }); + chan = ""; + socket.removeEventListener("np"); + socket.removeEventListener("id"); + socket.removeEventListener(id); + //socket.disconnect(); + } + socket.removeEventListener("chat.all"); + socket.removeEventListener("chat"); + socket.removeEventListener("conf"); + socket.removeEventListener("pw"); + socket.removeEventListener("toast"); + //socket.removeEventListener("id"); + socket.removeEventListener("channel"); + socket.removeEventListener("auth_required"); + socket.removeEventListener("auth_accepted"); + socket.removeEventListener("suggested"); + socket.removeEventListener("color"); + socket.removeEventListener("chat_history"); + Helper.ajax({ + url: "/", + method: "GET", + success: function(e) { + if (!client) { + document.querySelector("#hide-playlist").remove(); + if (hiddenPlaylist) + document.querySelector("main").style.maxWidth = ""; + hiddenPlaylist = false; + document + .getElementById("volume-button") + .removeEventListener("click", Playercontrols.mute_video); + document + .getElementById("playpause") + .removeEventListener("click", Playercontrols.play_pause); + document + .getElementById("fullscreen") + .removeEventListener("click", Playercontrols.fullscreen); + } + Channel.listeners(false); + if (Helper.mobilecheck() || user_auth_avoid) { + video_id = ""; + song_title = ""; + } + + document + .querySelectorAll("meta[name=theme-color]")[0] + .setAttribute("content", "#2D2D2D"); + + if (!Helper.mobilecheck() && !user_auth_avoid) { + Helper.removeElement("#playbar"); + Helper.removeElement("#main_components"); + Helper.addClass("#player_overlay", "player_bottom"); + Helper.addClass("#player", "player_bottom"); + Helper.addClass(".video-container", "frontpage-player"); + Helper.addClass("#main-row", "frontpage_modified_heights"); + Helper.css("#player", "opacity", "1"); + Helper.removeClass("#video-container", "no-opacity"); + document + .getElementById("main-row") + .insertAdjacentHTML( + "afterbegin", + "
" + ); + document + .getElementById("player_bottom_overlay") + .insertAdjacentHTML( + "afterbegin", + "close" + ); + document + .getElementById("player_bottom_overlay") + .setAttribute("data-channel", channel_before_move.toLowerCase()); + Helper.removeElement("#playlist"); + } else { + try { + Player.player.destroy(); + } catch (error) {} + try { + Player.soundcloud_dead = true; + Player.soundcloud_player.kill(); + } catch (error) {} + Player.player = ""; + document.title = "Zoff"; + } + + var response = document.createElement("div"); + response.innerHTML = e; + + var newList = response.querySelector("#lists-script").innerHTML; + newList = newList + .trim() + .replace("window.lists = ", "") + .replace("window.lists=", ""); + newList = newList.substring(0, newList.length); + window.lists = JSON.parse(newList); + + response.querySelector("#lists-script").remove(); + Helper.removeElement("#sidenav-overlay"); + document.getElementsByTagName("main")[0].className = + "center-align container"; + Helper.removeClass("#main-container", "channelpage"); + document.getElementById("main-container").setAttribute("style", ""); + document.getElementsByTagName( + "header" + )[0].innerHTML = response.querySelectorAll("header")[0].outerHTML; + + document + .getElementsByTagName("header")[0] + .insertAdjacentHTML( + "afterend", + response.querySelectorAll(".section.mega")[0].outerHTML + ); + //document.getElementsByTagName("header")[0].insertAdjacentHTML("afterend", response.querySelectorAll(".section.mobile-search")[0].innerHTML); + if (Helper.mobilecheck() || user_auth_avoid) { + document.getElementsByTagName( + "main" + )[0].innerHTML = response.querySelectorAll("main")[0].innerHTML; + } else { + document + .getElementsByTagName("main")[0] + .insertAdjacentHTML( + "beforeend", + response.querySelectorAll("#main_section_frontpage")[0] + .outerHTML + ); + } + Helper.removeClass(".page-footer", "padding-bottom-extra"); + Helper.removeClass(".page-footer", "padding-bottom-novideo"); + document + .getElementById("favicon") + .setAttribute("href", "/assets/images/favicon-32x32.png"); + + Helper.log(["Socket", socket]); + if (document.querySelectorAll("#alreadyfp").length == 1) { + Frontpage.init(); + } else { + fromChannel = true; + frontpage = true; + Frontpage.init(); + } + + changing_to_frontpage = false; + + if ( + document.querySelectorAll("#alreadychannel").length === 0 && + !user_auth_avoid + ) { + document + .getElementsByTagName("head")[0] + .insertAdjacentHTML( + "beforeend", + "
= 10 ? true : false, + pride: function() { + return new Date().getMonth() == 5; + }, - winter: (new Date()).getMonth() >= 10 ? true : false, - pride: function() { - return (new Date()).getMonth() == 5; - }, + times_rotated: 0, - times_rotated: 0, + all_channels: [], - all_channels: [], + frontpage_function: function() { + frontpage = true; - frontpage_function: function() { - frontpage = true; + Helper.log(["Frontpage fetch", msg]); - Helper.log([ - "Frontpage fetch", - msg - ]); + Frontpage.all_channels = window.lists; + var msg = window.lists; + delete window.lists; + window.lists = undefined; + //document.querySelector("#lists-script").remove(); + if (msg.length == 0) { + //Helper.css("#preloader", "display", "none"); + document + .getElementById("channel-list-container") + .insertAdjacentHTML("beforeend", "

No channels yet

"); + } else { + Frontpage.populate_channels(msg, true, false); + } + //Frontpage.set_viewers(msg.viewers); + }, - Frontpage.all_channels = window.lists; - var msg = window.lists; - delete window.lists; - window.lists = undefined; - //document.querySelector("#lists-script").remove(); - if(msg.length == 0) { - //Helper.css("#preloader", "display", "none"); - document.getElementById("channel-list-container").insertAdjacentHTML("beforeend", "

No channels yet

"); - } else { - Frontpage.populate_channels(msg, true, false); - } - //Frontpage.set_viewers(msg.viewers); - }, + populate_channels: function(lists, popular, set) { + //document.getElementById("channels").innerHTML = ""; - populate_channels: function(lists, popular, set) { - //document.getElementById("channels").innerHTML = ""; + var num = 0; + if (!set) Frontpage.add_backdrop(lists, 0); + else if (set) { + document.getElementById("channels").innerHTML = ""; + if (popular) { + lists = lists.sort( + Helper.predicate( + { + name: "pinned", + reverse: true + }, + { + name: "viewers", + reverse: true + }, + { + name: "accessed", + reverse: true + }, + { + name: "count", + reverse: true + } + ) + ); + } else { + lists = lists.sort( + Helper.predicate( + { + name: "viewers", + reverse: true + }, + { + name: "count", + reverse: true + } + ) + ); + } - var num = 0; - if(!set) Frontpage.add_backdrop(lists, 0); - else if(set) { - document.getElementById("channels").innerHTML = ""; - if(popular) { - lists = lists.sort(Helper.predicate({ - name: 'pinned', - reverse: true - }, { - name: 'viewers', - reverse: true - }, { - name: 'accessed', - reverse: true - }, { - name: 'count', - reverse: true - })); + if (!Helper.mobilecheck()) { + clearTimeout(rotation_timeout); + Frontpage.add_backdrop(lists, 0); + } + + pre_card = channel_list; + + Helper.log(["Pre_card: ", pre_card]); + + for (var x in lists) { + var chan = Helper.decodeChannelName(lists[x]._id); + if (num < 12 || !popular) { + var id = lists[x].id; + var viewers = lists[x].viewers; + var description = lists[x].description; + var img; + img = + "background-image:url('https://img.youtube.com/vi/" + + id + + "/hqdefault.jpg');"; + if (lists[x].thumbnail && lists[x].thumbnail != "") { + img = "background-image:url('" + lists[x].thumbnail + "');"; + } + + var song_count = lists[x].count; + var card = document.createElement("div"); + card.innerHTML += pre_card; + //card.innerHTML = card.children[0]; + if (song_count > 3) { + if (lists[x].pinned == 1) { + card + .querySelector(".pin") + .setAttribute("style", "display:block;"); + //card.find(".card").attr("title", "Featured list"); } else { - lists = lists.sort(Helper.predicate({ - name: 'viewers', - reverse: true - }, { - name: 'count', - reverse: true - })); - } - - if(!Helper.mobilecheck()) { - clearTimeout(rotation_timeout); - Frontpage.add_backdrop(lists, 0); - } - - pre_card = channel_list; - - Helper.log([ - "Pre_card: ", - pre_card - ]); - - for(var x in lists) { - var chan = Helper.decodeChannelName(lists[x]._id); - if(num<12 || !popular) { - var id = lists[x].id; - var viewers = lists[x].viewers; - var description = lists[x].description; - var img; - img = "background-image:url('https://img.youtube.com/vi/"+id+"/hqdefault.jpg');"; - if(lists[x].thumbnail && lists[x].thumbnail != "") { - img = "background-image:url('" + lists[x].thumbnail + "');"; - } - - var song_count = lists[x].count; - var card = document.createElement("div"); - card.innerHTML += pre_card; - //card.innerHTML = card.children[0]; - if(song_count > 3) { - if(lists[x].pinned == 1) { - card.querySelector(".pin").setAttribute("style", "display:block;"); - //card.find(".card").attr("title", "Featured list"); - } else { - /*card.find(".pin").attr("style", "display:none;"); + /*card.find(".pin").attr("style", "display:none;"); card.find(".card").attr("title", ""); card.querySelector(".pin").remove();*/ - } - card.querySelector(".chan-name").innerText = chan; - card.querySelector(".chan-name").setAttribute("title", chan); - card.querySelector(".chan-views").innerText = viewers; - card.querySelector(".chan-songs").innerText = song_count; - card.querySelector(".chan-bg").setAttribute("style", img); - card.querySelector(".chan-link").setAttribute("href", chan + "/"); - - if(description != "" && description != undefined && !Helper.mobilecheck() && description != "This list has no description") { - card.querySelector(".card-title").innerText = chan; - card.querySelector(".description_text").innerText = description; - description = ""; - } else { - card.querySelector(".card-reveal").remove(); - Helper.removeClass(card.querySelector(".card"), "sticky-action") - } - - document.getElementById("channels").insertAdjacentHTML("beforeend", card.children[0].innerHTML); - } else { - num--; - } - - } - num++; } - } + card.querySelector(".chan-name").innerText = chan; + card.querySelector(".chan-name").setAttribute("title", chan); + card.querySelector(".chan-views").innerText = viewers; + card.querySelector(".chan-songs").innerText = song_count; + card.querySelector(".chan-bg").setAttribute("style", img); + card.querySelector(".chan-link").setAttribute("href", chan + "/"); - var options_list = lists.slice(); - - options_list = options_list.sort(Frontpage.sortFunction_active); - var data = {}; - for(var x in options_list) { - data[Helper.decodeChannelName(options_list[x]._id)] = null; - } - if(document.querySelectorAll(".pin").length == 1 && !Helper.mobilecheck()) { - Helper.tooltip(document.querySelectorAll(".pin")[0].parentElement.parentElement.parentElement, { - delay: 5, - position: "top", - html: "Featured playlist" - }); - } - - var to_autocomplete = document.querySelectorAll("input.autocomplete")[0]; - //if(Helper.mobilecheck()) to_autocomplete = "input.mobile-search"; - - M.Autocomplete.init(to_autocomplete, { - data: data, - limit: 5, // The max amount of results that can be shown at once. Default: Infinity. - onAutocomplete: function(val) { - Frontpage.to_channel(Helper.encodeChannelName(val), false); - }, - }); - - //document.getElementById("preloader").style.display = "none"; - document.getElementById("channels").style.display = "block"; - //Materialize.fadeInImage('#channels'); - //$("#channels").fadeIn(800); - //document.getElementById("autocomplete-input").focus(); - num = 0; - }, - - sortFunction: function(a, b) { - var o1 = a.viewers; - var o2 = b.viewers; - - var p1 = a.count; - var p2 = b.count; - - if (o1 < o2) return 1; - if (o1 > o2) return -1; - if (p1 < p2) return 1; - if (p1 > p2) return -1; - return 0; - }, - - sortFunction_active: function(a, b){ - var o1 = a.accessed; - var o2 = b.accessed; - - var p1 = a.count; - var p2 = b.count; - - if (o1 < o2) return 1; - if (o1 > o2) return -1; - if (p1 < p2) return 1; - if (p1 > p2) return -1; - return 0; - }, - - getCookie: function(cname) { - var name = cname + "="; - var ca = document.cookie.split(';'); - for(var i=0; i= list.length || i >= 20) i = 0; - if(list[i] == undefined) return; - var id = list[i].id; - if(Frontpage.blob_list[i] !== undefined){ - //$(".room-namer").css("opacity", 0); - setTimeout(function(){ - if(frontpage){ - Helper.css("#mega-background","background", "url(data:image/png;base64,"+Frontpage.blob_list[i]+")"); - Helper.css("#mega-background","background-size" , "cover"); - Helper.css("#mega-background","background-repeat" , "no-repeat"); - Helper.css("#mega-background","opacity", 1); - document.querySelector(".autocomplete").setAttribute("placeholder", Helper.decodeChannelName(list[i]._id)); - //$(".room-namer").css("opacity", 1); - } - },500); - } else { - var img = new Image(); - img.src = "/assets/images/thumbnails/"+id+".jpg"; - - img.onerror = function(e){ // Failed to load - var add = ""; - if(window.location.hostname == "fb.zoff.me") { - add = "https://zoff.me"; - } - Helper.ajax({ - type: "POST", - data: {id:id}, - url: add + "/api/imageblob", - headers: {"Content-Type": "application/json;charset=UTF-8"}, - success: function(data){ - setTimeout(function(){ - try { - Helper.css("#mega-background", "background", "url(/assets/images/thumbnails/"+data+")"); - Helper.css("#mega-background", "background-size" , "cover"); - Helper.css("#mega-background", "background-repeat" , "no-repeat"); - Helper.css("#mega-background", "opacity", 1); - document.querySelector(".autocomplete").setAttribute("placeholder", Helper.decodeChannelName(list[i]._id)); - } catch(e) {} - },500); - }, - error: function() { - try { - document.querySelector(".autocomplete").setAttribute("placeholder", Helper.decodeChannelName(list[i]._id)); - } catch(e) { - console.log("This is a weird error...", e); - } - } - }); - }; - img.onload = function(){ // Loaded successfully - try { - Helper.css("#mega-background", "background", "url("+img.src+")"); - Helper.css("#mega-background", "background-size" , "cover"); - Helper.css("#mega-background", "background-repeat" , "no-repeat"); - Helper.css("#mega-background", "opacity", 1); - document.querySelector(".autocomplete").setAttribute("placeholder", Helper.decodeChannelName(list[i]._id)); - } catch(e) {} - }; - - } - rotation_timeout = setTimeout(function(){ - if(Frontpage.times_rotated == 50 && frontpage){ - Frontpage.times_rotated = 0; - i = 0; - //Frontpage.get_frontpage_lists(); - }else if(frontpage){ - Frontpage.times_rotated += 1; - Frontpage.add_backdrop(list, i+1); + if ( + description != "" && + description != undefined && + !Helper.mobilecheck() && + description != "This list has no description" + ) { + card.querySelector(".card-title").innerText = chan; + card.querySelector(".description_text").innerText = description; + description = ""; + } else { + card.querySelector(".card-reveal").remove(); + Helper.removeClass(card.querySelector(".card"), "sticky-action"); } - },6000); - }, - get_frontpage_lists: function() { + document + .getElementById("channels") + .insertAdjacentHTML("beforeend", card.children[0].innerHTML); + } else { + num--; + } + } + num++; + } + } + + var options_list = lists.slice(); + + options_list = options_list.sort(Frontpage.sortFunction_active); + var data = {}; + for (var x in options_list) { + data[Helper.decodeChannelName(options_list[x]._id)] = null; + } + if ( + document.querySelectorAll(".pin").length == 1 && + !Helper.mobilecheck() + ) { + Helper.tooltip( + document.querySelectorAll(".pin")[0].parentElement.parentElement + .parentElement, + { + delay: 5, + position: "top", + html: "Featured playlist" + } + ); + } + + var to_autocomplete = document.querySelectorAll("input.autocomplete")[0]; + //if(Helper.mobilecheck()) to_autocomplete = "input.mobile-search"; + + M.Autocomplete.init(to_autocomplete, { + data: data, + limit: 5, // The max amount of results that can be shown at once. Default: Infinity. + onAutocomplete: function(val) { + Frontpage.to_channel(Helper.encodeChannelName(val), false); + } + }); + + //document.getElementById("preloader").style.display = "none"; + document.getElementById("channels").style.display = "block"; + //Materialize.fadeInImage('#channels'); + //$("#channels").fadeIn(800); + //document.getElementById("autocomplete-input").focus(); + num = 0; + }, + + sortFunction: function(a, b) { + var o1 = a.viewers; + var o2 = b.viewers; + + var p1 = a.count; + var p2 = b.count; + + if (o1 < o2) return 1; + if (o1 > o2) return -1; + if (p1 < p2) return 1; + if (p1 > p2) return -1; + return 0; + }, + + sortFunction_active: function(a, b) { + var o1 = a.accessed; + var o2 = b.accessed; + + var p1 = a.count; + var p2 = b.count; + + if (o1 < o2) return 1; + if (o1 > o2) return -1; + if (p1 < p2) return 1; + if (p1 > p2) return -1; + return 0; + }, + + getCookie: function(cname) { + var name = cname + "="; + var ca = document.cookie.split(";"); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) == " ") c = c.substring(1); + if (c.indexOf(name) === 0) return c.substring(name.length, c.length); + } + return ""; + }, + + add_backdrop: function(list, i) { + if (i >= list.length || i >= 20) i = 0; + if (list[i] == undefined) return; + var id = list[i].id; + if (Frontpage.blob_list[i] !== undefined) { + //$(".room-namer").css("opacity", 0); + setTimeout(function() { + if (frontpage) { + Helper.css( + "#mega-background", + "background", + "url(data:image/png;base64," + Frontpage.blob_list[i] + ")" + ); + Helper.css("#mega-background", "background-size", "cover"); + Helper.css("#mega-background", "background-repeat", "no-repeat"); + Helper.css("#mega-background", "opacity", 1); + document + .querySelector(".autocomplete") + .setAttribute("placeholder", Helper.decodeChannelName(list[i]._id)); + //$(".room-namer").css("opacity", 1); + } + }, 500); + } else { + var img = new Image(); + img.src = "/assets/images/thumbnails/" + id + ".jpg"; + + img.onerror = function(e) { + // Failed to load var add = ""; - if(window.location.hostname == "fb.zoff.me") { - add = "https://zoff.me"; + if (window.location.hostname == "fb.zoff.me") { + add = "https://zoff.me"; } - Frontpage.frontpage_function(); - /*Helper.ajax({ + Helper.ajax({ + type: "POST", + data: { id: id }, + url: add + "/api/imageblob", + headers: { "Content-Type": "application/json;charset=UTF-8" }, + success: function(data) { + setTimeout(function() { + try { + Helper.css( + "#mega-background", + "background", + "url(/assets/images/thumbnails/" + data + ")" + ); + Helper.css("#mega-background", "background-size", "cover"); + Helper.css( + "#mega-background", + "background-repeat", + "no-repeat" + ); + Helper.css("#mega-background", "opacity", 1); + document + .querySelector(".autocomplete") + .setAttribute( + "placeholder", + Helper.decodeChannelName(list[i]._id) + ); + } catch (e) {} + }, 500); + }, + error: function() { + try { + document + .querySelector(".autocomplete") + .setAttribute( + "placeholder", + Helper.decodeChannelName(list[i]._id) + ); + } catch (e) { + console.log("This is a weird error...", e); + } + } + }); + }; + img.onload = function() { + // Loaded successfully + try { + Helper.css("#mega-background", "background", "url(" + img.src + ")"); + Helper.css("#mega-background", "background-size", "cover"); + Helper.css("#mega-background", "background-repeat", "no-repeat"); + Helper.css("#mega-background", "opacity", 1); + document + .querySelector(".autocomplete") + .setAttribute("placeholder", Helper.decodeChannelName(list[i]._id)); + } catch (e) {} + }; + } + rotation_timeout = setTimeout(function() { + if (Frontpage.times_rotated == 50 && frontpage) { + Frontpage.times_rotated = 0; + i = 0; + //Frontpage.get_frontpage_lists(); + } else if (frontpage) { + Frontpage.times_rotated += 1; + Frontpage.add_backdrop(list, i + 1); + } + }, 6000); + }, + + get_frontpage_lists: function() { + var add = ""; + if (window.location.hostname == "fb.zoff.me") { + add = "https://zoff.me"; + } + Frontpage.frontpage_function(); + /*Helper.ajax({ url: add + "/api/frontpages", method: "POST", data: { @@ -301,237 +353,289 @@ var Frontpage = { }, 3000); }, });*/ - }, + }, - start_snowfall: function() { - setTimeout(function(){ - var x = Math.floor((Math.random() * window.innerWidth) + 1); - var snow = document.createElement("div"); - var parent = document.getElementsByClassName("mega")[0]; + start_snowfall: function() { + setTimeout(function() { + var x = Math.floor(Math.random() * window.innerWidth + 1); + var snow = document.createElement("div"); + var parent = document.getElementsByClassName("mega")[0]; - snow.className = "snow"; - //snow.attr("left", x); - snow.style.left = x+"px"; - snow.style.top = "0px"; - parent.appendChild(snow); - Frontpage.fall_snow(snow); - Frontpage.start_snowfall(); - }, 800); - }, + snow.className = "snow"; + //snow.attr("left", x); + snow.style.left = x + "px"; + snow.style.top = "0px"; + parent.appendChild(snow); + Frontpage.fall_snow(snow); + Frontpage.start_snowfall(); + }, 800); + }, - fall_snow: function(corn) { - corn.style.top = (parseInt(corn.style.top.replace("px", ""))+2)+"px"; - if(parseInt(corn.style.top.replace("px", "")) < document.getElementById("mega-background").offsetHeight-2.5){ - setTimeout(function(){ - Frontpage.fall_snow(corn); - },50); - }else{ - corn.remove(); + fall_snow: function(corn) { + corn.style.top = parseInt(corn.style.top.replace("px", "")) + 2 + "px"; + if ( + parseInt(corn.style.top.replace("px", "")) < + document.getElementById("mega-background").offsetHeight - 2.5 + ) { + setTimeout(function() { + Frontpage.fall_snow(corn); + }, 50); + } else { + corn.remove(); + } + }, + + set_viewers: function(viewers) { + document.querySelector("#frontpage-viewer-counter").innerHTML = + "visibility" + viewers; + }, + + to_channel: function(new_channel, popstate) { + Helper.css("#channel-load", "display", "block"); + window.scrollTo(0, 0); + frontpage = false; + new_channel = new_channel.toLowerCase(); + clearTimeout(rotation_timeout); + if (Helper.mobilecheck()) { + Helper.log(["removing all listeners"]); + removeAllListeners(); + } + Helper.css("#main-container", "background-color", "#2d2d2d"); + if (!Helper.mobilecheck()) { + Helper.tooltip("#frontpage-viewer-counter", "destroy"); + Helper.tooltip(".generate-channel-name", "destroy"); + Helper.tooltip("#offline-mode", "destroy"); + Helper.tooltip("#client-mode-button", "destroy"); + if (document.querySelectorAll(".pin").length == 1) { + Helper.tooltip( + document.querySelectorAll(".pin")[0].parentElement.parentElement + .parentElement, + "destroy" + ); + } + } + + currently_showing_channels = 1; + clearTimeout(retry_frontpage); + Helper.ajax({ + url: "/" + new_channel, + method: "get", + data: { channel: new_channel }, + success: function(e) { + if (Player.player !== "") { + //Player.player.destroy(); + socket.emit("change_channel", { channel: chan.toLowerCase() }); } - }, - - set_viewers: function(viewers) { - document.querySelector("#frontpage-viewer-counter").innerHTML = "visibility" + viewers; - }, - - to_channel: function(new_channel, popstate) { - Helper.css("#channel-load", "display", "block"); - window.scrollTo(0, 0); - frontpage = false; - new_channel = new_channel.toLowerCase(); - clearTimeout(rotation_timeout); - if(Helper.mobilecheck()){ - Helper.log(["removing all listeners"]); - removeAllListeners(); + var _player = document.querySelectorAll("#frontpage_player"); + if (_player.length > 0) _player[0].innerHTML = ""; + if (Helper.mobilecheck()) { + //Helper.log("disconnecting"); + //socket.disconnect(); + socket.removeAllListeners(); } - Helper.css("#main-container", "background-color", "#2d2d2d"); - if(!Helper.mobilecheck()) { - Helper.tooltip("#frontpage-viewer-counter", "destroy"); - Helper.tooltip(".generate-channel-name", "destroy"); - Helper.tooltip("#offline-mode", "destroy"); - Helper.tooltip("#client-mode-button", "destroy"); - if(document.querySelectorAll(".pin").length == 1) { - Helper.tooltip(document.querySelectorAll(".pin")[0].parentElement.parentElement.parentElement, "destroy"); - } + var old_chan = chan; + if (!popstate) { + window.history.pushState( + "to the channel!", + "Title", + "/" + new_channel + ); + if (prev_chan_list == "") prev_chan_list = new_channel; + if (prev_chan_player == "") prev_chan_player = new_channel; + chan = new_channel; } - currently_showing_channels = 1; - clearTimeout(retry_frontpage); - Helper.ajax({ - url: "/" + new_channel, - method: "get", - data: {channel: new_channel}, - success: function(e){ + var response = document.createElement("div"); + response.innerHTML = e; - if(Player.player !== ""){ - //Player.player.destroy(); - socket.emit("change_channel", {channel: chan.toLowerCase()}); - } - var _player = document.querySelectorAll("#frontpage_player"); - if(_player.length > 0) _player[0].innerHTML = ""; - if(Helper.mobilecheck()) { - //Helper.log("disconnecting"); - //socket.disconnect(); - socket.removeAllListeners(); - } - var old_chan = chan; - if(!popstate){ - window.history.pushState("to the channel!", "Title", "/" + new_channel); - if(prev_chan_list == "") prev_chan_list = new_channel; - if(prev_chan_player == "") prev_chan_player = new_channel; - chan = new_channel; - } + M.FormSelect.getInstance( + document.querySelector("#view_channels_select") + ).destroy(); + //$('select').formSelect('destroy'); + Helper.removeElement(".mega"); + Helper.removeElement(".mobile-search"); + document.getElementsByTagName("main")[0].className = + "container center-align main"; + Helper.addClass("#main-container", "channelpage"); - var response = document.createElement("div"); - response.innerHTML = e; + document.getElementsByTagName( + "header" + )[0].innerHTML = response.querySelectorAll("header")[0].innerHTML; - M.FormSelect.getInstance(document.querySelector("#view_channels_select")).destroy(); - //$('select').formSelect('destroy'); - Helper.removeElement(".mega"); - Helper.removeElement(".mobile-search"); - document.getElementsByTagName("main")[0].className = "container center-align main"; - Helper.addClass("#main-container", "channelpage"); - - document.getElementsByTagName("header")[0].innerHTML = response.querySelectorAll("header")[0].innerHTML; - - if(document.querySelectorAll("#alreadychannel").length === 0 || Helper.mobilecheck() || Player.player === undefined){ - document.getElementsByTagName("main")[0].innerHTML = response.querySelectorAll("main")[0].innerHTML; - } else { - document.getElementById("main-row").insertAdjacentHTML("beforeend", response.querySelectorAll("#playlist")[0].outerHTML); - if(!client) document.getElementById("video-container").insertAdjacentHTML("beforeend", response.querySelectorAll("#main_components")[0].outerHTML); - document.getElementById("main-row").insertAdjacentHTML("beforeend", "
"); - Helper.removeClass("#player", "player_bottom"); - Helper.removeClass("#player_overlay", "player_bottom"); - Helper.removeClass(".video-container", "frontpage-player"); - Helper.removeClass("#main-row", "frontpage_modified_heights"); - Helper.removeElement("#main_section_frontpage"); - Helper.removeElement("#closePlayer"); - Helper.removeElement("#player_bottom_overlay"); - } - document.getElementById("search").setAttribute("placeholder", "Search..."); - Helper.addClass(".page-footer", "padding-bottom-novideo"); - from_frontpage = true; - //Player.stopInterval =true; - //clearTimeout(durationTimeout); - if(document.querySelectorAll("#alreadychannel").length == 1){ - if(old_chan != new_channel) local_new_channel = true; - Channel.init(); - }else{ - fromFront = true; - Channel.init(); - } - if(document.querySelectorAll("#alreadyfp").length === 0) document.getElementsByTagName("head")[0].insertAdjacentHTML("beforeend", "
"); - - } - }); - }, - - init: function() { - - var date = new Date(); - Frontpage.blob_list = []; - if(date.getMonth() == 3 && date.getDate() == 1){ - Helper.css(".mega", "-webkit-transform", "rotate(180deg)"); - Helper.css(".mega", "-moz-transform", "rotate(180deg)"); - //Materialize.toast('

We suck at pranks..Agreed

', 100000); + if ( + document.querySelectorAll("#alreadychannel").length === 0 || + Helper.mobilecheck() || + Player.player === undefined + ) { + document.getElementsByTagName( + "main" + )[0].innerHTML = response.querySelectorAll("main")[0].innerHTML; + } else { + document + .getElementById("main-row") + .insertAdjacentHTML( + "beforeend", + response.querySelectorAll("#playlist")[0].outerHTML + ); + if (!client) + document + .getElementById("video-container") + .insertAdjacentHTML( + "beforeend", + response.querySelectorAll("#main_components")[0].outerHTML + ); + document + .getElementById("main-row") + .insertAdjacentHTML("beforeend", "
"); + Helper.removeClass("#player", "player_bottom"); + Helper.removeClass("#player_overlay", "player_bottom"); + Helper.removeClass(".video-container", "frontpage-player"); + Helper.removeClass("#main-row", "frontpage_modified_heights"); + Helper.removeElement("#main_section_frontpage"); + Helper.removeElement("#closePlayer"); + Helper.removeElement("#player_bottom_overlay"); } - - if(window.location.hostname != "localhost") { - var page = window.location.pathname; - if(page.substring(page.length - 1) != "/") page += "/"; - ga('send', 'pageview', page); + document + .getElementById("search") + .setAttribute("placeholder", "Search..."); + Helper.addClass(".page-footer", "padding-bottom-novideo"); + from_frontpage = true; + //Player.stopInterval =true; + //clearTimeout(durationTimeout); + if (document.querySelectorAll("#alreadychannel").length == 1) { + if (old_chan != new_channel) local_new_channel = true; + Channel.init(); + } else { + fromFront = true; + Channel.init(); } + if (document.querySelectorAll("#alreadyfp").length === 0) + document + .getElementsByTagName("head")[0] + .insertAdjacentHTML("beforeend", "
"); + } + }); + }, - window.onpopstate = function(e){ - var url_split = window.location.href.split("/"); + init: function() { + var date = new Date(); + Frontpage.blob_list = []; + if (date.getMonth() == 3 && date.getDate() == 1) { + Helper.css(".mega", "-webkit-transform", "rotate(180deg)"); + Helper.css(".mega", "-moz-transform", "rotate(180deg)"); + //Materialize.toast('

We suck at pranks..Agreed

', 100000); + } - if(url_split[3] !== "" && url_split[3].substring(0,1) != "#"){ - Frontpage.to_channel(url_split[3], true); - } - }; + if (window.location.hostname != "localhost") { + var page = window.location.pathname; + if (page.substring(page.length - 1) != "/") page += "/"; + ga("send", "pageview", page); + } - if(window.location.hostname == "fb.zoff.me") { - Helper.addClass("footer", "hide"); + window.onpopstate = function(e) { + var url_split = window.location.href.split("/"); + console.log(url_split); + if (url_split[3] !== "" && url_split[3].substring(0, 1) != "#") { + Frontpage.to_channel(url_split[3], true); + } + }; + + if (window.location.hostname == "fb.zoff.me") { + Helper.addClass("footer", "hide"); + } + + channel_list = document + .querySelector(".hidden-channel-list") + .cloneNode(true).innerHTML; + try { + document.querySelector(".hidden-channel-list").remove(); + } catch (e) {} + + Frontpage.share_link_modifier(); + + if ( + window.location.hostname == "zoff.me" || + window.location.hostname == "fb.zoff.me" + ) + add = "https://zoff.me"; + else add = window.location.hostname; + if (socket === undefined) { + no_socket = false; + if (window.location.port != "") { + add = add + ":" + window.location.port + "/"; + } + socket = io.connect( + "" + add, + connection_options + ); + socket.on("update_required", function(msg) { + if (window.location.hostname == "localhost") { + console.log(msg); + return; } + window.location.reload(true); + }); + } + if ( + document.querySelectorAll("#alreadyfp").length === 0 || + Helper.mobilecheck() || + !socket._callbacks.$playlists || + user_auth_avoid + ) { + setup_playlist_listener(); + } - channel_list = document.querySelector(".hidden-channel-list").cloneNode(true).innerHTML; - try { - document.querySelector(".hidden-channel-list").remove(); - }catch(e){} - - Frontpage.share_link_modifier(); - - if(window.location.hostname == "zoff.me" || window.location.hostname == "fb.zoff.me") add = "https://zoff.me"; - else add = window.location.hostname; - if(socket === undefined) { - no_socket = false; - socket = io.connect(''+add, connection_options); - socket.on('update_required', function(msg) { - if(window.location.hostname == "localhost") { - console.log(msg); - return; - } - window.location.reload(true); - }); - } - if(document.querySelectorAll("#alreadyfp").length === 0 || Helper.mobilecheck() || !socket._callbacks.$playlists || user_auth_avoid){ - setup_playlist_listener(); - } - - /*M.Modal.init(document.getElementById("about")); + /*M.Modal.init(document.getElementById("about")); M.Modal.init(document.getElementById("help")); M.Modal.init(document.getElementById("contact"));*/ - var elem = document.querySelector('select'); - document.querySelector(".no-jump-select").remove(); - M.FormSelect.init(elem); + var elem = document.querySelector("select"); + document.querySelector(".no-jump-select").remove(); + M.FormSelect.init(elem); - Helper.log([ - "Sending frontpage_lists", - "Socket" - ]); + Helper.log(["Sending frontpage_lists", "Socket"]); - Crypt.init(); - if(Crypt.get_offline()){ - change_offline(true, offline); - } else { - if(!Helper.mobilecheck()) { - Helper.tooltip("#offline-mode", { - delay: 5, - position: "bottom", - html: "Enable local mode" - }); - } - } - if(!Helper.mobilecheck()) { - Helper.tooltip("#frontpage-viewer-counter", { - delay: 5, - position: "bottom", - html: "Total Viewers" - }); - Helper.tooltip("#client-mode-button", { - delay: 5, - position: "bottom", - html: "Client mode" - }); - Helper.tooltip(".generate-channel-name", { - delay: 5, - position: "bottom", - html: "Generate name" - }); - } - Frontpage.get_frontpage_lists(); + Crypt.init(); + if (Crypt.get_offline()) { + change_offline(true, offline); + } else { + if (!Helper.mobilecheck()) { + Helper.tooltip("#offline-mode", { + delay: 5, + position: "bottom", + html: "Enable local mode" + }); + } + } + if (!Helper.mobilecheck()) { + Helper.tooltip("#frontpage-viewer-counter", { + delay: 5, + position: "bottom", + html: "Total Viewers" + }); + Helper.tooltip("#client-mode-button", { + delay: 5, + position: "bottom", + html: "Client mode" + }); + Helper.tooltip(".generate-channel-name", { + delay: 5, + position: "bottom", + html: "Generate name" + }); + } + Frontpage.get_frontpage_lists(); - Helper.css("#channel-load", "display", "none"); - //Materialize.toast("Try out our new feature, remote!", 8000) - if(window.location.hash == "#donation") { - window.location.hash = "#"; - M.Modal.init(document.getElementById("donation"));; - M.Modal.getInstance(document.getElementById("donation")).open(); - } + Helper.css("#channel-load", "display", "none"); + //Materialize.toast("Try out our new feature, remote!", 8000) + if (window.location.hash == "#donation") { + window.location.hash = "#"; + M.Modal.init(document.getElementById("donation")); + M.Modal.getInstance(document.getElementById("donation")).open(); + } - //var pad = 0; + //var pad = 0; - /*$(".zicon").on("click", function(e) { + /*$(".zicon").on("click", function(e) { e.preventDefault(); pad += 10; @@ -540,35 +644,57 @@ var Frontpage = { window.location.href = 'http://etys.no'; });*/ - if(!Helper.mobilecheck() && Frontpage.winter) { - document.getElementsByClassName("mega")[0].insertAdjacentHTML("afterbegin", '
'); - } - if(Frontpage.pride()) { - Helper.addClass("#fp-nav", "pride-background"); - } - - if(Helper.mobilecheck()){ - //$('input#autocomplete-input').characterCounter(); - } - - window['__onGCastApiAvailable'] = function(loaded, errorInfo) { - if (loaded) { - chromecastReady = true; - } else { - } - } - }, - - share_link_modifier: function() { - document.getElementById("facebook-code-link").setAttribute("href", "https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/"); - document.getElementById("facebook-code-link").setAttribute("onclick", "window.open('https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/', 'Share Zoff','width=600,height=300'); return false;"); - document.getElementById("twitter-code-link").setAttribute("href", "https://twitter.com/intent/tweet?url=https://zoff.me/&text=Check%20out%20Zoff!&via=zoffmusic"); - document.getElementById("twitter-code-link").setAttribute("onclick", "window.open('https://twitter.com/intent/tweet?url=https://zoff.me/&text=Check%20out%20Zoff!&via=zoffmusic','Share Playlist','width=600,height=300'); return false;"); - //$("#qr-code-link").attr("href", "//chart.googleapis.com/chart?chs=500x500&cht=qr&chl=https://zoff.me/&choe=UTF-8&chld=L%7C1"); - //$("#qr-code-image-link").attr("src", "//chart.googleapis.com/chart?chs=150x150&cht=qr&chl=https://zoff.me/&choe=UTF-8&chld=L%7C1"); + if (!Helper.mobilecheck() && Frontpage.winter) { + document + .getElementsByClassName("mega")[0] + .insertAdjacentHTML("afterbegin", '
'); } + if (Frontpage.pride()) { + Helper.addClass("#fp-nav", "pride-background"); + } + + if (Helper.mobilecheck()) { + //$('input#autocomplete-input').characterCounter(); + } + + window["__onGCastApiAvailable"] = function(loaded, errorInfo) { + if (loaded) { + chromecastReady = true; + } else { + } + }; + }, + + share_link_modifier: function() { + document + .getElementById("facebook-code-link") + .setAttribute( + "href", + "https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/" + ); + document + .getElementById("facebook-code-link") + .setAttribute( + "onclick", + "window.open('https://www.facebook.com/sharer/sharer.php?u=https://zoff.me/', 'Share Zoff','width=600,height=300'); return false;" + ); + document + .getElementById("twitter-code-link") + .setAttribute( + "href", + "https://twitter.com/intent/tweet?url=https://zoff.me/&text=Check%20out%20Zoff!&via=zoffmusic" + ); + document + .getElementById("twitter-code-link") + .setAttribute( + "onclick", + "window.open('https://twitter.com/intent/tweet?url=https://zoff.me/&text=Check%20out%20Zoff!&via=zoffmusic','Share Playlist','width=600,height=300'); return false;" + ); + //$("#qr-code-link").attr("href", "//chart.googleapis.com/chart?chs=500x500&cht=qr&chl=https://zoff.me/&choe=UTF-8&chld=L%7C1"); + //$("#qr-code-image-link").attr("src", "//chart.googleapis.com/chart?chs=150x150&cht=qr&chl=https://zoff.me/&choe=UTF-8&chld=L%7C1"); + } }; String.prototype.capitalizeFirstLetter = function() { - return this.charAt(0).toUpperCase() + this.slice(1); + return this.charAt(0).toUpperCase() + this.slice(1); }; diff --git a/server/public/assets/js/functions.js b/server/public/assets/js/functions.js index 1cf5e38a..b1b15894 100644 --- a/server/public/assets/js/functions.js +++ b/server/public/assets/js/functions.js @@ -1,1430 +1,1961 @@ - function removeAllListeners() { - Helper.log(["Removing all listeners"]); - socket.removeEventListener("chat.all"); - socket.removeEventListener("chat"); - socket.removeEventListener("conf"); - socket.removeEventListener("pw"); - socket.removeEventListener("toast"); - socket.removeEventListener("id"); - socket.removeEventListener("channel"); - socket.removeEventListener("np"); - socket.removeEventListener("get_list"); - //socket.removeEventListener("self_ping"); - socket.removeEventListener("viewers"); - socket.removeEventListener("auth_required"); - socket.removeEventListener("auth_accepted"); - socket.removeEventListener("suggested"); - socket.removeEventListener("color"); - socket.removeEventListener("chat_history"); - //socket.removeEventListener("name"); - socket.removeEventListener(id); + Helper.log(["Removing all listeners"]); + socket.removeEventListener("chat.all"); + socket.removeEventListener("chat"); + socket.removeEventListener("conf"); + socket.removeEventListener("pw"); + socket.removeEventListener("toast"); + socket.removeEventListener("id"); + socket.removeEventListener("channel"); + socket.removeEventListener("np"); + socket.removeEventListener("get_list"); + //socket.removeEventListener("self_ping"); + socket.removeEventListener("viewers"); + socket.removeEventListener("auth_required"); + socket.removeEventListener("auth_accepted"); + socket.removeEventListener("suggested"); + socket.removeEventListener("color"); + socket.removeEventListener("chat_history"); + //socket.removeEventListener("name"); + socket.removeEventListener(id); } function list_last_logs() { - console.log(JSON.stringify(Helper.logs)); + console.log(JSON.stringify(Helper.logs)); } function filterPlaylistElements(page) { - var value = document.getElementById("filtersearch_input").value; - var search_type = document.querySelector(".category-advanced-select").value; - if(search_type != "category" && search_type != "title") { - document.querySelector(".filter-results").innerHTML = "Something went wrong with fetching data.."; - return; - } - if(value == "") return; - Helper.ajax({ - type: "POST", - headers: { - "Content-Type": "application/json" - }, - url: "/api/search/" + chan.toLowerCase(), - data: { - searchQuery: value, - page: page, - type: search_type - }, - success: function(data){ - var json = JSON.parse(data); - document.querySelector(".filter-results").innerHTML = ""; - if(json.results.search_results.length > 0) { - addFilterButtons("top", json); - for(var i = 0; i < json.results.search_results.length; i++) { - document.querySelector(".filter-results").innerHTML += List.generateSong(json.results.search_results[i], false, false, true, false, "block", false, true);; - } - addFilterButtons("bottom", json); - } else { - toast("Couldn't find any items with those tags..", "red"); - document.querySelector(".filter-results").innerHTML = "Couldn't find any items with those tags.."; - } - }, - error: function(e) { - if(e.status != 429) { - toast("Couldn't find any items with those tags..", "red"); - - document.querySelector(".filter-results").innerHTML = "Couldn't find any items with those tags.."; - } else { - toast("You are doing that too much..", "red"); - } + var value = document.getElementById("filtersearch_input").value; + var search_type = document.querySelector(".category-advanced-select").value; + if (search_type != "category" && search_type != "title") { + document.querySelector(".filter-results").innerHTML = + "Something went wrong with fetching data.."; + return; + } + if (value == "") return; + Helper.ajax({ + type: "POST", + headers: { + "Content-Type": "application/json" + }, + url: "/api/search/" + chan.toLowerCase(), + data: { + searchQuery: value, + page: page, + type: search_type + }, + success: function(data) { + var json = JSON.parse(data); + document.querySelector(".filter-results").innerHTML = ""; + if (json.results.search_results.length > 0) { + addFilterButtons("top", json); + for (var i = 0; i < json.results.search_results.length; i++) { + document.querySelector( + ".filter-results" + ).innerHTML += List.generateSong( + json.results.search_results[i], + false, + false, + true, + false, + "block", + false, + true + ); } - }); + addFilterButtons("bottom", json); + } else { + toast("Couldn't find any items with those tags..", "red"); + document.querySelector(".filter-results").innerHTML = + "Couldn't find any items with those tags.."; + } + }, + error: function(e) { + if (e.status != 429) { + toast("Couldn't find any items with those tags..", "red"); + + document.querySelector(".filter-results").innerHTML = + "Couldn't find any items with those tags.."; + } else { + toast("You are doing that too much..", "red"); + } + } + }); } function addFilterButtons(position, json) { - if(json.results.next != undefined || json.results.prev != undefined) { - document.querySelector(".filter-results").innerHTML += "
" - if(json.results.prev != undefined) { - document.querySelector("." + position + "-filter-container").innerHTML += "Prev"; - } else { - document.querySelector("." + position + "-filter-container").innerHTML += "Prev"; - } - if(json.results.next != undefined) { - document.querySelector("." + position + "-filter-container").innerHTML += "Next"; - } else { - document.querySelector("." + position + "-filter-container").innerHTML += "Next"; - } + if (json.results.next != undefined || json.results.prev != undefined) { + document.querySelector(".filter-results").innerHTML += + "
"; + if (json.results.prev != undefined) { + document.querySelector("." + position + "-filter-container").innerHTML += + "Prev"; + } else { + document.querySelector("." + position + "-filter-container").innerHTML += + "Prev"; } + if (json.results.next != undefined) { + document.querySelector("." + position + "-filter-container").innerHTML += + "Next"; + } else { + document.querySelector("." + position + "-filter-container").innerHTML += + "Next"; + } + } } function say_updated() { - setTimeout(function() { - before_toast(); - M.toast({html: "The list was updated, want to refresh? yesno", displayLength: 10000000}); - }, 500); + setTimeout(function() { + before_toast(); + M.toast({ + html: + "The list was updated, want to refresh? yesno", + displayLength: 10000000 + }); + }, 500); } function sendDescription() { - emit("suggest_description", {channel: chan, description: document.getElementById("description_input").value}); - document.getElementById("description_input").value = ""; + emit("suggest_description", { + channel: chan, + description: document.getElementById("description_input").value + }); + document.getElementById("description_input").value = ""; } function sendThumbnail() { - emit("suggest_thumbnail", {channel: chan, thumbnail: document.getElementById("thumbnail_input").value}); - document.getElementById("thumbnail_input").value = ""; + emit("suggest_thumbnail", { + channel: chan, + thumbnail: document.getElementById("thumbnail_input").value + }); + document.getElementById("thumbnail_input").value = ""; } function sendRules() { - emit("suggest_rules", {channel: chan, rules: document.getElementById("rules_input").value}); - document.getElementById("rules_input").value = ""; + emit("suggest_rules", { + channel: chan, + rules: document.getElementById("rules_input").value + }); + document.getElementById("rules_input").value = ""; } function resizeFunction() { - if(chan && !Helper.mobilecheck()){ - if(document.querySelector("#wrapper") == null) return; - if(!client && !embed) document.querySelector("#hide-playlist").style.left = (document.querySelector("#video-container").offsetWidth - document.querySelector("#hide-playlist").offsetWidth) + "px"; - if(((window.innerWidth > 600 && !embed) || (window.innerWidth > 500 && embed)) && document.querySelector("#wrapper").style.height != "") { - document.querySelector("#wrapper").style.height = ""; - document.querySelector("#chat-bar").style.height = ""; - document.querySelector("#channelchat").style.height = ""; - document.querySelector("#all_chat").style.height = ""; - document.querySelector("#chat-container").style.height = ""; - } else if(((window.innerWidth < 601 && !embed) || (window.innerWidth < 501 && embed))) { - if(!client && !embed) { - var scPlaying = false; - var ytPlaying = false; - if(scUsingWidget) { - Player.soundcloud_player.isPaused(function(paused) { - try { - ytPlaying = Player.player.getPlayerState() == YT.PlayerState.PLAYING || Player.player.getPlayerState() == YT.PlayerState.BUFFERING; - } catch(e) {} - scPlaying = !paused; - resizePlaylistPlaying(ytPlaying || scPlaying, true); - return; - }) - } else { - try { - ytPlaying = Player.player.getPlayerState() == YT.PlayerState.PLAYING || Player.player.getPlayerState() == YT.PlayerState.BUFFERING; - } catch(e) {} - try { - scPlaying = Player.soundcloud_player.isPlaying(); - } catch(e){} - resizePlaylistPlaying(ytPlaying || scPlaying, true); - } - return; - } - } - var temp_fit; - - if(!embed && !client){ - temp_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71); - List.element_height = (Helper.computedStyle("#wrapper", "height") / temp_fit)-5.3; - } else if(embed) { - temp_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 91) + 1; - List.element_height = (Helper.computedStyle("#wrapper", "height") / temp_fit)-4; - } else if(!client){ - temp_fit = Math.round((Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / 71)+1; - List.element_height = ((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / temp_fit)-5; + if (chan && !Helper.mobilecheck()) { + if (document.querySelector("#wrapper") == null) return; + if (!client && !embed) + document.querySelector("#hide-playlist").style.left = + document.querySelector("#video-container").offsetWidth - + document.querySelector("#hide-playlist").offsetWidth + + "px"; + if ( + ((window.innerWidth > 600 && !embed) || + (window.innerWidth > 500 && embed)) && + document.querySelector("#wrapper").style.height != "" + ) { + document.querySelector("#wrapper").style.height = ""; + document.querySelector("#chat-bar").style.height = ""; + document.querySelector("#channelchat").style.height = ""; + document.querySelector("#all_chat").style.height = ""; + document.querySelector("#chat-container").style.height = ""; + } else if ( + (window.innerWidth < 601 && !embed) || + (window.innerWidth < 501 && embed) + ) { + if (!client && !embed) { + var scPlaying = false; + var ytPlaying = false; + if (scUsingWidget) { + Player.soundcloud_player.isPaused(function(paused) { + try { + ytPlaying = + Player.player.getPlayerState() == YT.PlayerState.PLAYING || + Player.player.getPlayerState() == YT.PlayerState.BUFFERING; + } catch (e) {} + scPlaying = !paused; + resizePlaylistPlaying(ytPlaying || scPlaying, true); + return; + }); } else { - temp_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71)+1; - List.element_height = (Helper.computedStyle("#wrapper", "height") / temp_fit)-5.3; - } - if(List.element_height < 55.2 && !client && !embed){ - temp_fit = temp_fit - 1; - List.element_height = 55.2; - temp_fit = Math.round((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / 71); - List.element_height = ((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / temp_fit)-5; - } else if(List.element_height < 55.2 && embed) { - //List.can_fit = List.can_fit - 1; - temp_fit = Math.round((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / 71); - List.element_height = ((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / temp_fit)-5; - temp_fit = temp_fit - 2; - } - if(temp_fit > List.can_fit || temp_fit < List.can_fit){ - List.dynamicContentPage(-10); - } - if(List.can_fit < temp_fit){ - for(var i = 0; i < List.page + temp_fit; i++) { - Helper.css(document.querySelector("#wrapper").children[i], "display", "inline-flex"); - } - } else if(List.can_fit > temp_fit){ - Helper.css(document.querySelector("#wrapper").children[List.page + temp_fit], "display", "none"); - var elements = document.querySelector("#wrapper").children; - for(var i = List.page + temp_fit; i < elements.length; i++) { - Helper.css(document.querySelector("#wrapper").children[i], "display", "none"); - } - } - List.can_fit = temp_fit; - //List.element_height = (Helper.computedStyle("#wrapper", "height") / List.can_fit)-5.3; - Helper.css(".list-song", "height", List.element_height + "px"); - Channel.set_title_width(); - if(!client) { - var controlsPosition = document.querySelector("#controls").offsetHeight - Helper.computedStyle("#controls", "height"); - if(document.querySelectorAll("#controls").length > 0 && !Helper.mobilecheck()) { - Helper.css(document.querySelector("#seekToDuration"), "top", controlsPosition - 55); - } else if(document.querySelectorAll("#controls").length > 0) { - Helper.css(document.querySelector("#seekToDuration"), "top", controlsPosition - 20); - } - Channel.window_width_volume_slider(); + try { + ytPlaying = + Player.player.getPlayerState() == YT.PlayerState.PLAYING || + Player.player.getPlayerState() == YT.PlayerState.BUFFERING; + } catch (e) {} + try { + scPlaying = Player.soundcloud_player.isPlaying(); + } catch (e) {} + resizePlaylistPlaying(ytPlaying || scPlaying, true); } + return; + } } + var temp_fit; + + if (!embed && !client) { + temp_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71); + List.element_height = + Helper.computedStyle("#wrapper", "height") / temp_fit - 5.3; + } else if (embed) { + temp_fit = + Math.round(Helper.computedStyle("#wrapper", "height") / 91) + 1; + List.element_height = + Helper.computedStyle("#wrapper", "height") / temp_fit - 4; + } else if (!client) { + temp_fit = + Math.round( + (Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + 71 + ) + 1; + List.element_height = + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + temp_fit - + 5; + } else { + temp_fit = + Math.round(Helper.computedStyle("#wrapper", "height") / 71) + 1; + List.element_height = + Helper.computedStyle("#wrapper", "height") / temp_fit - 5.3; + } + if (List.element_height < 55.2 && !client && !embed) { + temp_fit = temp_fit - 1; + List.element_height = 55.2; + temp_fit = Math.round( + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + 71 + ); + List.element_height = + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + temp_fit - + 5; + } else if (List.element_height < 55.2 && embed) { + //List.can_fit = List.can_fit - 1; + temp_fit = Math.round( + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + 71 + ); + List.element_height = + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + temp_fit - + 5; + temp_fit = temp_fit - 2; + } + if (temp_fit > List.can_fit || temp_fit < List.can_fit) { + List.dynamicContentPage(-10); + } + if (List.can_fit < temp_fit) { + for (var i = 0; i < List.page + temp_fit; i++) { + Helper.css( + document.querySelector("#wrapper").children[i], + "display", + "inline-flex" + ); + } + } else if (List.can_fit > temp_fit) { + Helper.css( + document.querySelector("#wrapper").children[List.page + temp_fit], + "display", + "none" + ); + var elements = document.querySelector("#wrapper").children; + for (var i = List.page + temp_fit; i < elements.length; i++) { + Helper.css( + document.querySelector("#wrapper").children[i], + "display", + "none" + ); + } + } + List.can_fit = temp_fit; + //List.element_height = (Helper.computedStyle("#wrapper", "height") / List.can_fit)-5.3; + Helper.css(".list-song", "height", List.element_height + "px"); + Channel.set_title_width(); + if (!client) { + var controlsPosition = + document.querySelector("#controls").offsetHeight - + Helper.computedStyle("#controls", "height"); + if ( + document.querySelectorAll("#controls").length > 0 && + !Helper.mobilecheck() + ) { + Helper.css( + document.querySelector("#seekToDuration"), + "top", + controlsPosition - 55 + ); + } else if (document.querySelectorAll("#controls").length > 0) { + Helper.css( + document.querySelector("#seekToDuration"), + "top", + controlsPosition - 20 + ); + } + Channel.window_width_volume_slider(); + } + } } function fullVideo(hide) { - if(hide) { - document.querySelector("#playlist").className += " show-only-mobile"; - document.querySelector("#video-container").classList.remove("m9"); - document.querySelector("#video-container").className += " m12"; - document.querySelector("main").style.maxWidth = "100%"; - document.querySelector("#hide-playlist").style.left = (document.querySelector("#video-container").offsetWidth - document.querySelector("#hide-playlist").offsetWidth) + "px"; - document.querySelector("#hide-playlist .material-icons").innerText = "keyboard_arrow_left"; - } else { - document.querySelector("#playlist").classList.remove("show-only-mobile"); - document.querySelector("#video-container").classList.remove("m12"); - document.querySelector("#video-container").className += " m9"; - document.querySelector("main").style.maxWidth = ""; - document.querySelector("#hide-playlist").style.left = (document.querySelector("#video-container").offsetWidth - document.querySelector("#hide-playlist").offsetWidth) + "px"; - document.querySelector("#hide-playlist .material-icons").innerText = "keyboard_arrow_right"; - } - hiddenPlaylist = hide; + if (hide) { + document.querySelector("#playlist").className += " show-only-mobile"; + document.querySelector("#video-container").classList.remove("m9"); + document.querySelector("#video-container").className += " m12"; + document.querySelector("main").style.maxWidth = "100%"; + document.querySelector("#hide-playlist").style.left = + document.querySelector("#video-container").offsetWidth - + document.querySelector("#hide-playlist").offsetWidth + + "px"; + document.querySelector("#hide-playlist .material-icons").innerText = + "keyboard_arrow_left"; + } else { + document.querySelector("#playlist").classList.remove("show-only-mobile"); + document.querySelector("#video-container").classList.remove("m12"); + document.querySelector("#video-container").className += " m9"; + document.querySelector("main").style.maxWidth = ""; + document.querySelector("#hide-playlist").style.left = + document.querySelector("#video-container").offsetWidth - + document.querySelector("#hide-playlist").offsetWidth + + "px"; + document.querySelector("#hide-playlist .material-icons").innerText = + "keyboard_arrow_right"; + } + hiddenPlaylist = hide; } function getColor(id) { - Helper.ajax({ - method: "POST", - url: "/api/color", - headers: {"Content-Type": "application/json;charset=UTF-8"}, - data: JSON.stringify({ - id: id - }), - success: function(c) { - c = JSON.parse(c); - if(typeof(c) == "object") { - Player.setBGimage({color:c, only:true}); - } - }, - }); + Helper.ajax({ + method: "POST", + url: "/api/color", + headers: { "Content-Type": "application/json;charset=UTF-8" }, + data: JSON.stringify({ + id: id + }), + success: function(c) { + c = JSON.parse(c); + if (typeof c == "object") { + Player.setBGimage({ color: c, only: true }); + } + } + }); } function hide_native(way) { - if(way == 1){ - Helper.addClass('.castButton', 'castButton-white-active'); - if(!Helper.mobilecheck()) { - if(M.Tooltip.getInstance(document.getElementsByClassName("castButton")[0])) { - Helper.tooltip('.castButton', 'destroy'); - } - Helper.tooltip('.castButton', { - delay: 5, - position: "top", - html: "Stop casting" - }); - } - Helper.toggleClass("#duration", "hide"); - Helper.toggleClass("#fullscreen", "hide"); - try{ - if(videoSource == "youtube") { - Player.player.stopVideo(); - } else if(videoSource == "soundcloud") { - Player.soundcloud_player.pause(); - } - } catch(e){} - //clearTimeout(durationTimeout); - Player.stopInterval = true; - if(Helper.mobilecheck()){ - if(document.querySelector("#pause").classList.contains("hide")){ - Helper.toggleClass("#play", "hide"); - Helper.toggleClass("#pause", "hide"); - } else if(document.querySelector("#play").classList.contains("hide")){ - Helper.toggleClass("#play", "hide"); - Helper.toggleClass("#pause", "hide"); - } - } else { - Playercontrols.visualVolume(100); - } - if(Helper.mobilecheck()) { - Helper.addClass("#player_overlay", "hide") - Helper.css("#player_overlay", "display", "none"); - Helper.css("#playing_on", "display", "none"); - } else { - var thisThumbnail; - if(Player.np.thumbnail == undefined) thisThumbnail = "https://img.youtube.com/vi/" + video_id + "/hqdefault.jpg"; - else thisThumbnail = Player.np.thumbnail; - Helper.removeClass("#player_overlay", "hide"); - Helper.css("#player_overlay", "display", "block"); - Helper.css("#player_overlay", "background", "url(" + thisThumbnail + ")"); - Helper.css("#player_overlay", "background-position", "center"); - Helper.css("#player_overlay", "background-size", "100%"); - Helper.css("#player_overlay", "background-color", "black"); - Helper.css("#player_overlay", "background-repeat", "no-repeat"); - Helper.css("#playing_on", "display", "flex"); - Helper.setHtml("#chromecast_text", "Playing on
" + castSession.getCastDevice().friendlyName); - } - Player.player.setVolume(100); - if(scUsingWidget) Player.soundcloud_player.setVolume(100); - else Player.soundcloud_player.setVolume(1); - - Helper.addClass("#player_overlay_text", "hide"); - } else if(way == 0){ - if(!Helper.mobilecheck()) { - if(M.Tooltip.getInstance(document.getElementsByClassName("castButton")[0])) { - Helper.tooltip('.castButton', 'destroy'); - } - Helper.tooltip('.castButton', { - delay: 5, - position: "top", - html: "Cast Zoff to TV" - }); - } - Helper.removeClass('.castButton', 'castButton-white-active'); - - Helper.toggleClass("#duration", "hide"); - Helper.toggleClass("#fullscreen", "hide"); - if(videoSource == "youtube") { - Player.player.playVideo(); - } else if(videoSource == "soundcloud") { - Player.soundcloud_player.play(); - } - Player.stopInterval = false; - duration = Player.player.getDuration(); - Player.durationSetter(); - if(!Helper.mobilecheck()){ - Player.player.setVolume(Crypt.get_volume()); - Playercontrols.visualVolume(Crypt.get_volume()); - if(scUsingWidget) Player.soundcloud_player.setVolume(embed ? 1 : Crypt.get_volume()); - else Player.soundcloud_player.setVolume(embed ? 1 : Crypt.get_volume() / 100); - } - Helper.addClass("#player_overlay", "hide"); - Helper.removeClass("#player_overlay_text", "hide"); - Helper.setHtml("#chromecast_text", ""); - Helper.css("#playing_on", "display", "none"); - if(!offline){ - socket.emit('pos', {channel: chan.toLowerCase()}); - } else { - Player.loadVideoById(video_id); - } + if (way == 1) { + Helper.addClass(".castButton", "castButton-white-active"); + if (!Helper.mobilecheck()) { + if ( + M.Tooltip.getInstance(document.getElementsByClassName("castButton")[0]) + ) { + Helper.tooltip(".castButton", "destroy"); + } + Helper.tooltip(".castButton", { + delay: 5, + position: "top", + html: "Stop casting" + }); } + Helper.toggleClass("#duration", "hide"); + Helper.toggleClass("#fullscreen", "hide"); + try { + if (videoSource == "youtube") { + Player.player.stopVideo(); + } else if (videoSource == "soundcloud") { + Player.soundcloud_player.pause(); + } + } catch (e) {} + //clearTimeout(durationTimeout); + Player.stopInterval = true; + if (Helper.mobilecheck()) { + if (document.querySelector("#pause").classList.contains("hide")) { + Helper.toggleClass("#play", "hide"); + Helper.toggleClass("#pause", "hide"); + } else if (document.querySelector("#play").classList.contains("hide")) { + Helper.toggleClass("#play", "hide"); + Helper.toggleClass("#pause", "hide"); + } + } else { + Playercontrols.visualVolume(100); + } + if (Helper.mobilecheck()) { + Helper.addClass("#player_overlay", "hide"); + Helper.css("#player_overlay", "display", "none"); + Helper.css("#playing_on", "display", "none"); + } else { + var thisThumbnail; + if (Player.np.thumbnail == undefined) + thisThumbnail = + "https://img.youtube.com/vi/" + video_id + "/hqdefault.jpg"; + else thisThumbnail = Player.np.thumbnail; + Helper.removeClass("#player_overlay", "hide"); + Helper.css("#player_overlay", "display", "block"); + Helper.css("#player_overlay", "background", "url(" + thisThumbnail + ")"); + Helper.css("#player_overlay", "background-position", "center"); + Helper.css("#player_overlay", "background-size", "100%"); + Helper.css("#player_overlay", "background-color", "black"); + Helper.css("#player_overlay", "background-repeat", "no-repeat"); + Helper.css("#playing_on", "display", "flex"); + Helper.setHtml( + "#chromecast_text", + "Playing on
" + castSession.getCastDevice().friendlyName + ); + } + Player.player.setVolume(100); + if (scUsingWidget) Player.soundcloud_player.setVolume(100); + else Player.soundcloud_player.setVolume(1); + + Helper.addClass("#player_overlay_text", "hide"); + } else if (way == 0) { + if (!Helper.mobilecheck()) { + if ( + M.Tooltip.getInstance(document.getElementsByClassName("castButton")[0]) + ) { + Helper.tooltip(".castButton", "destroy"); + } + Helper.tooltip(".castButton", { + delay: 5, + position: "top", + html: "Cast Zoff to TV" + }); + } + Helper.removeClass(".castButton", "castButton-white-active"); + + Helper.toggleClass("#duration", "hide"); + Helper.toggleClass("#fullscreen", "hide"); + if (videoSource == "youtube") { + Player.player.playVideo(); + } else if (videoSource == "soundcloud") { + Player.soundcloud_player.play(); + } + Player.stopInterval = false; + duration = Player.player.getDuration(); + Player.durationSetter(); + if (!Helper.mobilecheck()) { + Player.player.setVolume(Crypt.get_volume()); + Playercontrols.visualVolume(Crypt.get_volume()); + if (scUsingWidget) + Player.soundcloud_player.setVolume(embed ? 1 : Crypt.get_volume()); + else + Player.soundcloud_player.setVolume( + embed ? 1 : Crypt.get_volume() / 100 + ); + } + Helper.addClass("#player_overlay", "hide"); + Helper.removeClass("#player_overlay_text", "hide"); + Helper.setHtml("#chromecast_text", ""); + Helper.css("#playing_on", "display", "none"); + if (!offline) { + socket.emit("pos", { channel: chan.toLowerCase() }); + } else { + Player.loadVideoById(video_id); + } + } } function chromecastListener(evt, data) { - var json_parsed = JSON.parse(data); - switch(json_parsed.type){ - case -1: - if(offline){ - Player.playNext(); - } else { - socket.emit("end", {id: json_parsed.videoId, channel: chan.toLowerCase()}); - } - break; - case 0: - if(offline){ - Player.playNext(); - } else { - emit("skip", {error: json_parsed.data_code, id: json_parsed.videoId, channel: chan.toLowerCase()}); - } - break; - case 1: - Helper.addClass("#play", "hide"); - Helper.removeClass("#pause", "hide"); - break; - case 2: - Helper.addClass("#pause", "hide"); - Helper.removeClass("#play", "hide"); - break; - } + var json_parsed = JSON.parse(data); + switch (json_parsed.type) { + case -1: + if (offline) { + Player.playNext(); + } else { + socket.emit("end", { + id: json_parsed.videoId, + channel: chan.toLowerCase() + }); + } + break; + case 0: + if (offline) { + Player.playNext(); + } else { + emit("skip", { + error: json_parsed.data_code, + id: json_parsed.videoId, + channel: chan.toLowerCase() + }); + } + break; + case 1: + Helper.addClass("#play", "hide"); + Helper.removeClass("#pause", "hide"); + break; + case 2: + Helper.addClass("#pause", "hide"); + Helper.removeClass("#play", "hide"); + break; + } } function start_auth() { - if(!user_auth_started) { - user_auth_started = true; - Helper.removeClass("#player_overlay", "hide"); - Helper.css("#player_overlay", "display", "block"); - M.Modal.getInstance(document.getElementById("user_password")).open(); - document.querySelector("#user-pass-input").focus(); - //Crypt.remove_userpass(chan.toLowerCase()); - before_toast(); - M.toast({html: "That is not the correct password, try again..", displayLength: 4000}); - } + if (!user_auth_started) { + user_auth_started = true; + Helper.removeClass("#player_overlay", "hide"); + Helper.css("#player_overlay", "display", "block"); + M.Modal.getInstance(document.getElementById("user_password")).open(); + document.querySelector("#user-pass-input").focus(); + //Crypt.remove_userpass(chan.toLowerCase()); + before_toast(); + M.toast({ + html: "That is not the correct password, try again..", + displayLength: 4000 + }); + } } function emit_list() { - var add = ""; - //if(private_channel) add = Crypt.getCookie("_uI") + "_"; - /*var p = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); + var add = ""; + //if(private_channel) add = Crypt.getCookie("_uI") + "_"; + /*var p = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); if(p == undefined) p = "";*/ - if(socket.id) { - socket.emit("list", {version: parseInt(_VERSION), channel: add + chan.toLowerCase()}); - } else { - setTimeout(function(){ - emit_list(); - }, 50); - } + if (socket.id) { + socket.emit("list", { + version: parseInt(_VERSION), + channel: add + chan.toLowerCase() + }); + } else { + setTimeout(function() { + emit_list(); + }, 50); + } } function get_list_ajax() { - //var c = Crypt.get_userpass(chan.toLowerCase()); - Helper.ajax({ - type: "POST", - data: { - userpass: "", - token: zoff_api_token, - }, - headers: {"Content-Type": "application/json;charset=UTF-8"}, - url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()), - success: function(response) { - response = JSON.parse(response); - if(response.results.length > 0) { - if(response.status == 403) { - start_auth(); - } else if(response.status == 404) return; - if(client) { - Helper.removeElement("#channel-load"); - } - List.populate_list(response.results); - } - }, - error: function(response) { - //response = JSON.parse(response); - if(response.status == 403) { - start_auth(); - } else if(response.status == 429) { - setTimeout(function() { - get_list_ajax(); - }, xmlhttp.getResponseHeader("Retry-After") * 1000) - } else if(response.status == 404) return; - if(client) { - Helper.removeElement("#channel-load"); - } - //List.populate_list(response.responseJSON.results); + //var c = Crypt.get_userpass(chan.toLowerCase()); + Helper.ajax({ + type: "POST", + data: { + userpass: "", + token: zoff_api_token + }, + headers: { "Content-Type": "application/json;charset=UTF-8" }, + url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()), + success: function(response) { + response = JSON.parse(response); + if (response.results.length > 0) { + if (response.status == 403) { + start_auth(); + } else if (response.status == 404) return; + if (client) { + Helper.removeElement("#channel-load"); } - }); + List.populate_list(response.results); + } + }, + error: function(response) { + //response = JSON.parse(response); + if (response.status == 403) { + start_auth(); + } else if (response.status == 429) { + setTimeout(function() { + get_list_ajax(); + }, xmlhttp.getResponseHeader("Retry-After") * 1000); + } else if (response.status == 404) return; + if (client) { + Helper.removeElement("#channel-load"); + } + //List.populate_list(response.responseJSON.results); + } + }); } function contextListener(that, event) { - var parent = that.parentElement; - var suggested = false; - if(parent.id.indexOf("suggested-") > -1) suggested = true; - document.getElementsByClassName("context-menu-root")[0].setAttribute("data-suggested", suggested); - document.getElementsByClassName("context-menu-root")[0].setAttribute("data-id", parent.getAttribute("id").replace("suggested-", "")); - document.getElementsByClassName("context-menu-root")[0].setAttribute("data-source", parent.getAttribute("data-video-source")); - Helper.removeClass("#context-menu-overlay", "hide"); - var left = event.pageX - document.querySelector(".context-menu-root").offsetWidth / 2; - var top = event.pageY; - if(left + 200 > window.innerWidth) { - left = window.innerWidth - 200 - 15; - } else if (left < 0) { - left = 11; - } - if(top + 96 > window.innerHeight) { - top = window.innerHeight - 96 - 15; - } else if(top < 0) { - top = 15; - } - if(parent.getAttribute("data-video-source") == "soundcloud") { - Helper.addClass(".find-context-menu", "context-menu-disabled"); - } else { - Helper.removeClass(".find-context-menu", "context-menu-disabled"); - } - Helper.css(".context-menu-root", "left", left + "px"); - Helper.css(".context-menu-root", "top", top + "px"); - Helper.removeClass(".context-menu-root","hide"); - if(!Helper.mobilecheck()) { - mouseContext(left, top); - } + var parent = that.parentElement; + var suggested = false; + if (parent.id.indexOf("suggested-") > -1) suggested = true; + document + .getElementsByClassName("context-menu-root")[0] + .setAttribute("data-suggested", suggested); + document + .getElementsByClassName("context-menu-root")[0] + .setAttribute( + "data-id", + parent.getAttribute("id").replace("suggested-", "") + ); + document + .getElementsByClassName("context-menu-root")[0] + .setAttribute("data-source", parent.getAttribute("data-video-source")); + Helper.removeClass("#context-menu-overlay", "hide"); + var left = + event.pageX - document.querySelector(".context-menu-root").offsetWidth / 2; + var top = event.pageY; + if (left + 200 > window.innerWidth) { + left = window.innerWidth - 200 - 15; + } else if (left < 0) { + left = 11; + } + if (top + 96 > window.innerHeight) { + top = window.innerHeight - 96 - 15; + } else if (top < 0) { + top = 15; + } + if (parent.getAttribute("data-video-source") == "soundcloud") { + Helper.addClass(".find-context-menu", "context-menu-disabled"); + } else { + Helper.removeClass(".find-context-menu", "context-menu-disabled"); + } + Helper.css(".context-menu-root", "left", left + "px"); + Helper.css(".context-menu-root", "top", top + "px"); + Helper.removeClass(".context-menu-root", "hide"); + if (!Helper.mobilecheck()) { + mouseContext(left, top); + } } -function inIframe () { - try { - return window.self !== window.top; - } catch (e) { - return true; - } +function inIframe() { + try { + return window.self !== window.top; + } catch (e) { + return true; + } } function mouseContext(left, top) { - var moveFunction = function( event ) { - if(event.pageX < left - 60 || event.pageX > left + document.querySelector(".context-menu-root").offsetWidth + 60 || - event.pageY < top - 60 || event.pageY > top + document.querySelector(".context-menu-root").offsetHeight + 60) { - Helper.addClass(".context-menu-root", "hide"); - Helper.addClass("#context-menu-overlay", "hide"); - document.removeEventListener("mousemove", moveFunction); - } - }; - try { - document.removeEventListener("mousemove", moveFunction); - } catch(e) {} - document.addEventListener("mousemove", moveFunction, false); + var moveFunction = function(event) { + if ( + event.pageX < left - 60 || + event.pageX > + left + document.querySelector(".context-menu-root").offsetWidth + 60 || + event.pageY < top - 60 || + event.pageY > + top + document.querySelector(".context-menu-root").offsetHeight + 60 + ) { + Helper.addClass(".context-menu-root", "hide"); + Helper.addClass("#context-menu-overlay", "hide"); + document.removeEventListener("mousemove", moveFunction); + } + }; + try { + document.removeEventListener("mousemove", moveFunction); + } catch (e) {} + document.addEventListener("mousemove", moveFunction, false); } function get_np_ajax() { - /*var c = Crypt.get_userpass(chan.toLowerCase()); + /*var c = Crypt.get_userpass(chan.toLowerCase()); if(c == undefined) c = "";*/ - Helper.ajax({ - type: "POST", - data: { - userpass: "", - fetch_song: true, - token: zoff_api_token - }, - headers: {"Content-Type": "application/json;charset=UTF-8"}, - url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/__np__", - success: function(response) { - response = JSON.parse(response); - Player.getTitle(response.results[0].title, 1); - }, - error: function(response, xmlhttp) { - //response = JSON.parse(response); - if(response.status == 403) { - start_auth(); - } else if(response.status == 429) { - setTimeout(function() { - get_np_ajax(); - }, xmlhttp.getResponseHeader("Retry-After") * 1000) - } - } - }) + Helper.ajax({ + type: "POST", + data: { + userpass: "", + fetch_song: true, + token: zoff_api_token + }, + headers: { "Content-Type": "application/json;charset=UTF-8" }, + url: + "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/__np__", + success: function(response) { + response = JSON.parse(response); + Player.getTitle(response.results[0].title, 1); + }, + error: function(response, xmlhttp) { + //response = JSON.parse(response); + if (response.status == 403) { + start_auth(); + } else if (response.status == 429) { + setTimeout(function() { + get_np_ajax(); + }, xmlhttp.getResponseHeader("Retry-After") * 1000); + } + } + }); } function del_ajax(id) { - /*var a = Crypt.get_pass(chan.toLowerCase()); + /*var a = Crypt.get_pass(chan.toLowerCase()); var u = Crypt.get_userpass(chan.toLowerCase()); if(a == undefined) a = ""; if(u == undefined) u = "";*/ - Helper.ajax({ - type: "DELETE", - data: { - adminpass: "", - userpass: "", - token: zoff_api_token - }, - headers: {"Content-Type": "application/json;charset=UTF-8"}, - url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/" + id, - success: function(response) { - toast("deletesong"); - get_list_ajax(); - }, - error: function(response, xmlhttp) { - //response = JSON.parse(response); - if(response.status == 403) { - toast("listhaspass"); - } else if(response.status == 429) { - setTimeout(function() { - del_ajax(id); - }, xmlhttp.getResponseHeader("Retry-After") * 1000); - } - } - }) + Helper.ajax({ + type: "DELETE", + data: { + adminpass: "", + userpass: "", + token: zoff_api_token + }, + headers: { "Content-Type": "application/json;charset=UTF-8" }, + url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/" + id, + success: function(response) { + toast("deletesong"); + get_list_ajax(); + }, + error: function(response, xmlhttp) { + //response = JSON.parse(response); + if (response.status == 403) { + toast("listhaspass"); + } else if (response.status == 429) { + setTimeout(function() { + del_ajax(id); + }, xmlhttp.getResponseHeader("Retry-After") * 1000); + } + } + }); } -function add_ajax(id, title, duration, playlist, num, full_num, start, end, source, thumbnail) { - /*var a = Crypt.get_pass(chan.toLowerCase()); +function add_ajax( + id, + title, + duration, + playlist, + num, + full_num, + start, + end, + source, + thumbnail +) { + /*var a = Crypt.get_pass(chan.toLowerCase()); var u = Crypt.get_userpass(chan.toLowerCase()); if(a == undefined) a = ""; if(u == undefined) u = "";*/ - Helper.ajax({ - type: "POST", - data: { - adminpass: "", - userpass: "", - title: title, - duration: duration, - end_time: end, - start_time: start, - thumbnail: thumbnail, - source: source, - token: zoff_api_token - }, - headers: {"Content-Type": "application/json;charset=UTF-8"}, - url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/" + id, - success: function(response) { - toast("addedsong"); - get_list_ajax(); - }, - error: function(response, xmlhttp) { - //response = JSON.parse(response); - if(response.status == 403) { - toast("listhaspass"); - } else if(response.status == 409) { - vote_ajax(id); - } else if(response.status == 429) { - setTimeout(function() { - add_ajax(id, title, duration, playlist, num, full_num, start, end); - }, xmlhttp.getResponseHeader("Retry-After") * 1000); - } - } - }); + Helper.ajax({ + type: "POST", + data: { + adminpass: "", + userpass: "", + title: title, + duration: duration, + end_time: end, + start_time: start, + thumbnail: thumbnail, + source: source, + token: zoff_api_token + }, + headers: { "Content-Type": "application/json;charset=UTF-8" }, + url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/" + id, + success: function(response) { + toast("addedsong"); + get_list_ajax(); + }, + error: function(response, xmlhttp) { + //response = JSON.parse(response); + if (response.status == 403) { + toast("listhaspass"); + } else if (response.status == 409) { + vote_ajax(id); + } else if (response.status == 429) { + setTimeout(function() { + add_ajax(id, title, duration, playlist, num, full_num, start, end); + }, xmlhttp.getResponseHeader("Retry-After") * 1000); + } + } + }); } function vote_ajax(id) { - /*var a = Crypt.get_pass(chan.toLowerCase()); + /*var a = Crypt.get_pass(chan.toLowerCase()); var u = Crypt.get_userpass(chan.toLowerCase()); if(a == undefined) a = ""; if(u == undefined) u = "";*/ - Helper.ajax({ - type: "PUT", - data: { - adminpass: "", - userpass: "", - token: zoff_api_token - }, - headers: {"Content-Type": "application/json;charset=UTF-8"}, - url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/" + id, - success: function(response) { - toast("voted"); - get_list_ajax(); - }, - error: function(response, xmlhttp) { - //response = JSON.parse(response); - if(response.status == 403) { - toast("listhaspass"); - } else if(response.status == 429) { - setTimeout(function() { - vote_ajax(id); - }, xmlhttp.getResponseHeader("Retry-After") * 1000); - } - } - }) + Helper.ajax({ + type: "PUT", + data: { + adminpass: "", + userpass: "", + token: zoff_api_token + }, + headers: { "Content-Type": "application/json;charset=UTF-8" }, + url: "/api/list/" + Helper.encodeChannelName(chan.toLowerCase()) + "/" + id, + success: function(response) { + toast("voted"); + get_list_ajax(); + }, + error: function(response, xmlhttp) { + //response = JSON.parse(response); + if (response.status == 403) { + toast("listhaspass"); + } else if (response.status == 429) { + setTimeout(function() { + vote_ajax(id); + }, xmlhttp.getResponseHeader("Retry-After") * 1000); + } + } + }); } function setup_auth_listener() { - socket.on('auth_required', function() { - start_auth(); - }); + socket.on("auth_required", function() { + start_auth(); + }); - socket.on('auth_accepted', function(msg) { - if(msg.hasOwnProperty("value") && msg.value) { - if(temp_user_pass != "") { - userpass = temp_user_pass; - //Crypt.set_userpass(chan.toLowerCase(), userpass); - } - } - }); + socket.on("auth_accepted", function(msg) { + if (msg.hasOwnProperty("value") && msg.value) { + if (temp_user_pass != "") { + userpass = temp_user_pass; + //Crypt.set_userpass(chan.toLowerCase(), userpass); + } + } + }); } -function setup_no_connection_listener(){ - socket.on('connect_failed', function(){ - Helper.log(['Connection Failed']); - if(!connect_error){ - connect_error = true; - M.toast({html: "Error connecting to server, please wait..", displayLength: 100000000, classes: "red lighten connect_error"}); - } - }); +function setup_no_connection_listener() { + socket.on("connect_failed", function() { + Helper.log(["Connection Failed"]); + if (!connect_error) { + connect_error = true; + M.toast({ + html: "Error connecting to server, please wait..", + displayLength: 100000000, + classes: "red lighten connect_error" + }); + } + }); - socket.on("connect_error", function(){ - Helper.log(["Connection Failed."]); - if(!connect_error){ - connect_error = true; - M.toast({html: "Error connecting to server, please wait..", displayLength: 100000000, classes: "red lighten connect_error"}); - } - }); + socket.on("connect_error", function() { + Helper.log(["Connection Failed."]); + if (!connect_error) { + connect_error = true; + M.toast({ + html: "Error connecting to server, please wait..", + displayLength: 100000000, + classes: "red lighten connect_error" + }); + } + }); } function loadChromecastVideo() { - castSession = cast.framework.CastContext.getInstance().getCurrentSession(); - var _seekTo; - try{ - if(videoSource == "youtube") { - _seekTo = Player.player.getCurrentTime(); - } else if(videoSource == "soundcloud") { - _seekTo = Player.soundcloud_player.currentTime() / 1000; - } - } catch(event){ - _seekTo = seekTo; + castSession = cast.framework.CastContext.getInstance().getCurrentSession(); + var _seekTo; + try { + if (videoSource == "youtube") { + _seekTo = Player.player.getCurrentTime(); + } else if (videoSource == "soundcloud") { + _seekTo = Player.soundcloud_player.currentTime() / 1000; } - var mediaInfo = new chrome.cast.media.MediaInfo(video_id, "video"); - var image = {url:'https://img.youtube.com/vi/'+video_id+'/mqdefault.jpg', heigth: 180, width: 320}; - if(Player.np.thumbnail) image.url = Player.np.thumbnail; - mediaInfo.metadata = new chrome.cast.media.GenericMediaMetadata(); - mediaInfo.metadata.title = Player.np.title; - mediaInfo.metadata.image = image; - mediaInfo.metadata.images = [image]; - var request = new chrome.cast.media.LoadRequest(mediaInfo); - request.media.customData = { - start: Player.np.start, - end: Player.np.end, - seekTo: _seekTo, - channel: chan.toLowerCase(), - source: videoSource, - thumbnail: Player.np.thumbnail != undefined ? Player.np.thumbnail : 'https://img.youtube.com/vi/'+video_id+'/mqdefault.jpg', - }; - castSession.loadMedia(request).then(function() { - console.log("Loaded chromecast-video. Don't look here, look at your TV!"); + } catch (event) { + _seekTo = seekTo; + } + var mediaInfo = new chrome.cast.media.MediaInfo(video_id, "video"); + var image = { + url: "https://img.youtube.com/vi/" + video_id + "/mqdefault.jpg", + heigth: 180, + width: 320 + }; + if (Player.np.thumbnail) image.url = Player.np.thumbnail; + mediaInfo.metadata = new chrome.cast.media.GenericMediaMetadata(); + mediaInfo.metadata.title = Player.np.title; + mediaInfo.metadata.image = image; + mediaInfo.metadata.images = [image]; + var request = new chrome.cast.media.LoadRequest(mediaInfo); + request.media.customData = { + start: Player.np.start, + end: Player.np.end, + seekTo: _seekTo, + channel: chan.toLowerCase(), + source: videoSource, + thumbnail: + Player.np.thumbnail != undefined + ? Player.np.thumbnail + : "https://img.youtube.com/vi/" + video_id + "/mqdefault.jpg" + }; + castSession.loadMedia(request).then( + function() { + console.log("Loaded chromecast-video. Don't look here, look at your TV!"); }, function(errorCode) { - console.log('Error code: ' + errorCode); - }); + console.log("Error code: " + errorCode); + } + ); } function showOnSmallNotMobile() { - var elements = document.querySelectorAll(".hide-on-mobile-only"); - for(var i = 0; i < elements.length; i++) { - Helper.removeClass(elements[i], "hide-on-small-only"); - } + var elements = document.querySelectorAll(".hide-on-mobile-only"); + for (var i = 0; i < elements.length; i++) { + Helper.removeClass(elements[i], "hide-on-small-only"); + } } function enable_intelligent_list() { - if(Crypt.get_intelligent_list_enabled()) { - intelligentList = true; - } + if (Crypt.get_intelligent_list_enabled()) { + intelligentList = true; + } } function change_intelligent(enabled) { - document.querySelector(".intelligent_switch_class").checked = enabled; + document.querySelector(".intelligent_switch_class").checked = enabled; } function clearIntelligentQueue() { - intelligentList = false; - for(var i = 0; i < intelligentQueue.length; i++) { - var currentElement = intelligentQueue[i]; - if(currentElement.type == "vote") { - Helper.removeElement("#"+currentElement.element.id); - List.insertAtIndex(currentElement.element, false); - } else if(currentElement.type == "delete") { - List.deleted_song(currentElement.element.id, false, true, currentElement.index); - deleted_elements += 1; - } else if(currentElement.type == "add") { - List.insertAtIndex(currentElement.element, true); - Helper.css(document.querySelector("#wrapper").children[List.page + List.can_fit], "display", "none"); - if(document.querySelector("#wrapper").children.length > List.page + List.can_fit){ - Helper.css(".next_page_hide", "display", "none"); - Helper.removeClass(".next_page", "hide"); - Helper.css(".last_page_hide", "display", "none"); - Helper.css(".next_page", "display", "inline-flex"); - Helper.css(".last_page", "display", "inline-flex"); - } else { - Helper.css(".next_page_hide", "display", "inline-flex"); - Helper.css(".next_page", "display", "none"); - } - } + intelligentList = false; + for (var i = 0; i < intelligentQueue.length; i++) { + var currentElement = intelligentQueue[i]; + if (currentElement.type == "vote") { + Helper.removeElement("#" + currentElement.element.id); + List.insertAtIndex(currentElement.element, false); + } else if (currentElement.type == "delete") { + List.deleted_song( + currentElement.element.id, + false, + true, + currentElement.index + ); + deleted_elements += 1; + } else if (currentElement.type == "add") { + List.insertAtIndex(currentElement.element, true); + Helper.css( + document.querySelector("#wrapper").children[List.page + List.can_fit], + "display", + "none" + ); + if ( + document.querySelector("#wrapper").children.length > + List.page + List.can_fit + ) { + Helper.css(".next_page_hide", "display", "none"); + Helper.removeClass(".next_page", "hide"); + Helper.css(".last_page_hide", "display", "none"); + Helper.css(".next_page", "display", "inline-flex"); + Helper.css(".last_page", "display", "inline-flex"); + } else { + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".next_page", "display", "none"); + } } - intelligentQueue = []; + } + intelligentQueue = []; } function updateChromecastMetadata() { - if(!chromecastAvailable) return; - var image = {url:'https://img.youtube.com/vi/'+video_id+'/mqdefault.jpg', heigth: 180, width: 320}; - if(Player.np.thumbnail) image.url = Player.np.thumbnail; - chrome.cast.media.GenericMediaMetadata({metadataType: 0, title:Player.np.title, image: image, images: [image]}); - return new chrome.cast.media.GenericMediaMetadata({metadataType: 0, title:Player.np.title, image: image, images: [image]}); + if (!chromecastAvailable) return; + var image = { + url: "https://img.youtube.com/vi/" + video_id + "/mqdefault.jpg", + heigth: 180, + width: 320 + }; + if (Player.np.thumbnail) image.url = Player.np.thumbnail; + chrome.cast.media.GenericMediaMetadata({ + metadataType: 0, + title: Player.np.title, + image: image, + images: [image] + }); + return new chrome.cast.media.GenericMediaMetadata({ + metadataType: 0, + title: Player.np.title, + image: image, + images: [image] + }); } -function setup_now_playing_listener(){ - socket.on("np", Player.now_playing_listener); +function setup_now_playing_listener() { + socket.on("np", Player.now_playing_listener); } function exitHandler(event) { - if (document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement !== null) { - if(!document.getElementById("main-row").classList.contains("fullscreened")) { - Helper.addClass("#main-row", "fullscreened"); - } else { - Helper.removeClass("#main-row", "fullscreened"); - document.querySelector(".host_switch_class").checked = false - enable_host_mode(false); - } + if ( + document.webkitIsFullScreen || + document.mozFullScreen || + document.msFullscreenElement !== null + ) { + if ( + !document.getElementById("main-row").classList.contains("fullscreened") + ) { + Helper.addClass("#main-row", "fullscreened"); + } else { + Helper.removeClass("#main-row", "fullscreened"); + document.querySelector(".host_switch_class").checked = false; + enable_host_mode(false); } + } } function enable_host_mode(enabled) { - if(!hostMode) { - var playerElement = document.querySelector("main"); - var requestFullScreen = playerElement.requestFullScreen || playerElement.mozRequestFullScreen || playerElement.webkitRequestFullScreen; - if (requestFullScreen) { - requestFullScreen.bind(playerElement)(); - M.Tabs.getInstance(document.querySelector('.playlist-tabs-loggedIn')).select("wrapper"); - Helper.addClass("#main-row", "host-mode-height"); - Helper.addClass("#main-row", "host-mode-width"); - Helper.addClass("main", "host-mode-height"); - Helper.addClass("main", "host-mode-width"); - Helper.addClass("#video-container", "host-mode-height"); - Helper.addClass("#playlist", "host-mode-height"); - Helper.css(".playlist-tabs-loggedIn", "display", "none"); - Helper.removeClass("#wrapper", "tabs_height"); - Helper.addClass("#wrapper", "host-mode-wrapper"); - Helper.css(".skip", "display", "none"); - var removeElements = document.querySelectorAll(".list-remove"); - for(var i = 0; i < removeElements.length; i++) { - removeElements[i].style.display = "none"; - } - Helper.css(".prev", "display", "none"); - Helper.css("#fullscreen", "display", "none"); - Helper.css("#playlist", "backgroundColor", "inherit"); - Helper.css("#main-row", "backgroundColor", "inherit"); - Helper.css(".main", "backgroundColor", "inherit"); - Helper.removeClass("#host-title", "hide"); - Helper.css("#soundcloud_info_container", "display", "none"); - Helper.css("#player", "pointer-events", "none"); - hostMode = enabled; - document.querySelector("#playlist").insertAdjacentHTML("beforeend", "
" + document.querySelector("#channel-share-modal").querySelector(".modal-content").innerHTML + "
"); - document.addEventListener('webkitfullscreenchange', exitHandler, false); - document.addEventListener('mozfullscreenchange', exitHandler, false); - document.addEventListener('fullscreenchange', exitHandler, false); - document.addEventListener('MSFullscreenChange', exitHandler, false); - } - } else { - Helper.removeClass("#main-row", "host-mode-height"); - Helper.removeClass("#main-row", "host-mode-width"); - Helper.css(".prev", "display", "block"); - Helper.removeClass(".main", "host-mode-height"); - Helper.removeClass(".main", "host-mode-width"); - Helper.removeClass("#video-container", "host-mode-height"); - Helper.removeClass("#playlist", "host-mode-height"); - Helper.css(".playlist-tabs-loggedIn", "display", "flex"); - Helper.css("#player", "pointer-events", "all"); - Helper.addClass("#wrapper", "tabs_height"); - Helper.addClass("#host-title", "hide"); - Helper.removeClass("#wrapper", "host-mode-wrapper"); - Helper.css("#soundcloud_info_container", "display", "flex"); - Helper.css(".skip", "display", "block"); - document.querySelector("#join-sidebar").remove(); - var removeElements = document.querySelectorAll(".list-remove"); - for(var i = 0; i < removeElements.length; i++) { - removeElements[i].style.display = "block"; - } - Helper.css("#fullscreen", "display", "block"); - hostMode = false; - document.removeEventListener('webkitfullscreenchange', exitHandler, false); - document.removeEventListener('mozfullscreenchange', exitHandler, false); - document.removeEventListener('fullscreenchange', exitHandler, false); - document.removeEventListener('MSFullscreenChange', exitHandler, false); + if (!hostMode) { + var playerElement = document.querySelector("main"); + var requestFullScreen = + playerElement.requestFullScreen || + playerElement.mozRequestFullScreen || + playerElement.webkitRequestFullScreen; + if (requestFullScreen) { + requestFullScreen.bind(playerElement)(); + M.Tabs.getInstance( + document.querySelector(".playlist-tabs-loggedIn") + ).select("wrapper"); + Helper.addClass("#main-row", "host-mode-height"); + Helper.addClass("#main-row", "host-mode-width"); + Helper.addClass("main", "host-mode-height"); + Helper.addClass("main", "host-mode-width"); + Helper.addClass("#video-container", "host-mode-height"); + Helper.addClass("#playlist", "host-mode-height"); + Helper.css(".playlist-tabs-loggedIn", "display", "none"); + Helper.removeClass("#wrapper", "tabs_height"); + Helper.addClass("#wrapper", "host-mode-wrapper"); + Helper.css(".skip", "display", "none"); + var removeElements = document.querySelectorAll(".list-remove"); + for (var i = 0; i < removeElements.length; i++) { + removeElements[i].style.display = "none"; + } + Helper.css(".prev", "display", "none"); + Helper.css("#fullscreen", "display", "none"); + Helper.css("#playlist", "backgroundColor", "inherit"); + Helper.css("#main-row", "backgroundColor", "inherit"); + Helper.css(".main", "backgroundColor", "inherit"); + Helper.removeClass("#host-title", "hide"); + Helper.css("#soundcloud_info_container", "display", "none"); + Helper.css("#player", "pointer-events", "none"); + hostMode = enabled; + document + .querySelector("#playlist") + .insertAdjacentHTML( + "beforeend", + "
" + + document + .querySelector("#channel-share-modal") + .querySelector(".modal-content").innerHTML + + "
" + ); + document.addEventListener("webkitfullscreenchange", exitHandler, false); + document.addEventListener("mozfullscreenchange", exitHandler, false); + document.addEventListener("fullscreenchange", exitHandler, false); + document.addEventListener("MSFullscreenChange", exitHandler, false); } - resizeFunction(); - List.dynamicContentPage(-10); + } else { + Helper.removeClass("#main-row", "host-mode-height"); + Helper.removeClass("#main-row", "host-mode-width"); + Helper.css(".prev", "display", "block"); + Helper.removeClass(".main", "host-mode-height"); + Helper.removeClass(".main", "host-mode-width"); + Helper.removeClass("#video-container", "host-mode-height"); + Helper.removeClass("#playlist", "host-mode-height"); + Helper.css(".playlist-tabs-loggedIn", "display", "flex"); + Helper.css("#player", "pointer-events", "all"); + Helper.addClass("#wrapper", "tabs_height"); + Helper.addClass("#host-title", "hide"); + Helper.removeClass("#wrapper", "host-mode-wrapper"); + Helper.css("#soundcloud_info_container", "display", "flex"); + Helper.css(".skip", "display", "block"); + document.querySelector("#join-sidebar").remove(); + var removeElements = document.querySelectorAll(".list-remove"); + for (var i = 0; i < removeElements.length; i++) { + removeElements[i].style.display = "block"; + } + Helper.css("#fullscreen", "display", "block"); + hostMode = false; + document.removeEventListener("webkitfullscreenchange", exitHandler, false); + document.removeEventListener("mozfullscreenchange", exitHandler, false); + document.removeEventListener("fullscreenchange", exitHandler, false); + document.removeEventListener("MSFullscreenChange", exitHandler, false); + } + resizeFunction(); + List.dynamicContentPage(-10); } -function get_list_listener(){ - socket.on("get_list", function(){ - var add = ""; - socket_connected = true; - //if(private_channel) add = Crypt.getCookie("_uI") + "_"; - /*var p = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); +function get_list_listener() { + socket.on("get_list", function() { + var add = ""; + socket_connected = true; + //if(private_channel) add = Crypt.getCookie("_uI") + "_"; + /*var p = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); if(p == undefined) p = "";*/ - socket.emit("list", { offline: offline, version: parseInt(_VERSION), channel: add + chan.toLowerCase()}); + socket.emit("list", { + offline: offline, + version: parseInt(_VERSION), + channel: add + chan.toLowerCase() }); - socket.on("id_chromecast", function(msg) { - chromecast_specs_sent = true; - castSession.sendMessage("urn:x-cast:zoff.me", {type: "mobilespecs", guid: msg.guid, socketid: msg.cookie_id, channel: chan.toLowerCase()}) - }) -} - -function setup_suggested_listener(){ - if(client) return; - socket.on("suggested", function(params){ - var single = true; - if(params.id === undefined) - single = false; - Suggestions.catchUserSuggests(params, single); + }); + socket.on("id_chromecast", function(msg) { + chromecast_specs_sent = true; + castSession.sendMessage("urn:x-cast:zoff.me", { + type: "mobilespecs", + guid: msg.guid, + socketid: msg.cookie_id, + channel: chan.toLowerCase() }); + }); } -function setup_viewers_listener(){ - socket.on("viewers", function(view){ - viewers = view; - var outPutWord = "visibility"//v > 1 ? "viewers" : "viewer"; - - Helper.setHtml("#viewers", outPutWord + " " + view); - - if(song_title !== undefined) - Player.getTitle(song_title, viewers); - }); +function setup_suggested_listener() { + if (client) return; + socket.on("suggested", function(params) { + var single = true; + if (params.id === undefined) single = false; + Suggestions.catchUserSuggests(params, single); + }); } -function setup_admin_listener(){ - socket.on("toast", toast); - socket.on("pw", Admin.pw); - socket.on("conf", Admin.conf); +function setup_viewers_listener() { + socket.on("viewers", function(view) { + viewers = view; + var outPutWord = "visibility"; //v > 1 ? "viewers" : "viewer"; + + Helper.setHtml("#viewers", outPutWord + " " + view); + + if (song_title !== undefined) Player.getTitle(song_title, viewers); + }); } -function setup_chat_listener(){ - socket.on("chat_history", function(msg) { - var data = msg.data; - for(var i = 0; i < data.length; i++) { - if(msg.all) { - Chat.allchat(data[i], data[i].createdAt, true); - document.getElementById("chatall").scrollTop = document.getElementById("chatall").scrollHeight; - } else { - Chat.channelchat(data[i], data[i].createdAt, true); - document.getElementById("chatchannel").scrollTop = document.getElementById("chatchannel").scrollHeight; - } - } - }); - socket.on("chat.all", Chat.allchat); - socket.on("chat", Chat.channelchat); +function setup_admin_listener() { + socket.on("toast", toast); + socket.on("pw", Admin.pw); + socket.on("conf", Admin.conf); } -function setup_list_listener(){ - if(!offline) { - socket.on("color", Player.setBGimage); +function setup_chat_listener() { + socket.on("chat_history", function(msg) { + var data = msg.data; + for (var i = 0; i < data.length; i++) { + if (msg.all) { + Chat.allchat(data[i], data[i].createdAt, true); + document.getElementById("chatall").scrollTop = document.getElementById( + "chatall" + ).scrollHeight; + } else { + Chat.channelchat(data[i], data[i].createdAt, true); + document.getElementById( + "chatchannel" + ).scrollTop = document.getElementById("chatchannel").scrollHeight; + } } - socket.on("channel", List.channel_function); + }); + socket.on("chat.all", Chat.allchat); + socket.on("chat", Chat.channelchat); } -function setup_playlist_listener(){ - Helper.log(["Setting up playlist_listener"]); - socket.on('playlists', Frontpage.frontpage_function); +function setup_list_listener() { + if (!offline) { + socket.on("color", Player.setBGimage); + } + socket.on("channel", List.channel_function); } -function setup_host_initialization(){ - if(!client) { - Helper.log(["Setting up host initialization listener"]); - socket.on("id", Hostcontroller.host_listener); +function setup_playlist_listener() { + Helper.log(["Setting up playlist_listener"]); + socket.on("playlists", Frontpage.frontpage_function); +} + +function setup_host_initialization() { + if (!client) { + Helper.log(["Setting up host initialization listener"]); + socket.on("id", Hostcontroller.host_listener); + } +} + +function setup_host_listener(id) { + if (!client) { + Helper.log(["Setting up host action listener"]); + socket.on(id, Hostcontroller.host_on_action); + } +} + +function enable_debug() { + try { + localStorage.debug = true; + } catch (e) {} +} + +function disable_debug() { + try { + localStorage.debug = false; + } catch (e) {} +} + +function embed_code( + autoplay, + width, + height, + color, + embed_videoonly, + embed_localmode +) { + var autoplay_add = ""; + if (autoplay == "&autoplay=true") autoplay_add = 'allow="autoplay"'; + return ( + '" + ); +} + +function change_offline(enabled, already_offline) { + if (client) { + offline = false; + return; + } + Crypt.set_offline(enabled); + offline = enabled; + ga("send", "event", "button-click", "offline", "", offline ? 1 : 0); + socket.emit("offline", { + status: enabled, + channel: chan != undefined ? chan.toLowerCase() : "" + }); + if (!Helper.mobilecheck()) { + if ( + document.querySelectorAll("#offline-mode").length == 1 && + M.Tooltip.getInstance(document.getElementById("offline-mode")) + ) { + Helper.tooltip("#offline-mode", "destroy"); } -} + } -function setup_host_listener(id){ - if(!client) { - Helper.log(["Setting up host action listener"]); - socket.on(id, Hostcontroller.host_on_action); - } -} + var mouseEnter = function(e) { + Helper.removeClass("#seekToDuration", "hide"); + }; -function enable_debug(){ - try { - localStorage.debug = true; - } catch(e){} -} + var mouseLeave = function(e) { + dragging = false; + Helper.addClass("#seekToDuration", "hide"); + }; -function disable_debug(){ - try { - localStorage.debug = false; - } catch(e){} -} - -function embed_code(autoplay, width, height, color, embed_videoonly, embed_localmode){ - var autoplay_add = ""; - if(autoplay == "&autoplay=true") autoplay_add = 'allow="autoplay"'; - return ''; -} - -function change_offline(enabled, already_offline){ - if(client) { - offline = false; - return; - } - Crypt.set_offline(enabled); - offline = enabled; - ga('send', 'event', "button-click", "offline", "", offline ? 1 : 0); - socket.emit("offline", {status: enabled, channel: chan != undefined ? chan.toLowerCase() : ""}); - if(!Helper.mobilecheck()) { - if(document.querySelectorAll("#offline-mode").length == 1 && M.Tooltip.getInstance(document.getElementById("offline-mode"))) { - Helper.tooltip("#offline-mode", 'destroy'); - } - } - - var mouseEnter = function(e){ - Helper.removeClass("#seekToDuration", "hide"); - }; - - var mouseLeave = function(e){ - dragging = false; - Helper.addClass("#seekToDuration", "hide"); - }; - - var mouseDown = function(e) { - var acceptable = ["bar", "controls", "duration"]; - if(acceptable.indexOf(e.target.id) >= 0) { - dragging = true; - } - }; - - var mouseUp = function(e) { - dragging = false; - }; - - if(enabled){ - Helper.addClass("#viewers", "hide"); - Helper.removeClass(".margin-playbar", "margin-playbar"); - Helper.addClass(".prev playbar", "margin-playbar"); - Helper.removeClass(".prev playbar", "hide"); - Helper.removeClass("#offline-mode", "waves-cyan"); - Helper.addClass("#offline-mode", "cyan"); - Helper.removeClass(".delete-context-menu", "context-menu-disabled"); - if(!Helper.mobilecheck()) { - Helper.tooltip("#offline-mode", { - delay: 5, - position: "bottom", - html: "Disable local mode" - }); - } - - if(window.location.pathname != "/"){ - socket.removeEventListener("color"); - document.getElementById("controls").addEventListener("mouseenter", mouseEnter, false); - document.getElementById("controls").addEventListener("mouseleave", mouseLeave, false); - document.getElementById("controls").addEventListener("mousedown", mouseDown, false); - document.getElementById("controls").addEventListener("mouseup", mouseUp, false); - document.getElementById("controls").addEventListener("mousemove", seekToMove); - document.getElementById("controls").addEventListener("click", seekToClick); - - document.querySelector("#main_components").insertAdjacentHTML("beforeend", "
00:00/01:00
"); - var controlElement = document.querySelector("#controls"); - if(!Helper.mobilecheck()) Helper.css("#seekToDuration", "top", -controlElement.offsetHeight - 25 + "px"); - else if(Helper.mobilecheck()) Helper.css("#seekToDuration", "top", -controlElement.offsetHeight - 25 + "px"); - Helper.addClass("#controls", "ewresize"); - } - if(full_playlist != undefined && !already_offline){ - for(var x = 0; x < full_playlist.length; x++){ - full_playlist[x].votes = 0; - } - List.sortList(); - List.populate_list(full_playlist); - } - } else { - if(!Admin.logged_in) Helper.addClass(".delete-context-menu", "context-menu-disabled"); - Helper.removeClass(".margin-playbar", "margin-playbar"); - Helper.addClass("#playpause", "margin-playbar"); - Helper.removeClass("#viewers", "hide"); - Helper.addClass(".prev playbar", "hide"); - Helper.addClass("#offline-mode", "waves-cyan"); - Helper.removeClass("#offline-mode", "cyan"); - if(!Helper.mobilecheck()) { - Helper.tooltip("#offline-mode", { - delay: 5, - position: "bottom", - html: "Enable local mode" - }); - } - - if(window.location.pathname != "/"){ - document.getElementById("controls").removeEventListener("mouseenter", mouseEnter, false); - document.getElementById("controls").removeEventListener("mouseleave", mouseLeave, false); - document.getElementById("controls").removeEventListener("mousedown", mouseDown, false); - document.getElementById("controls").removeEventListener("mouseup", mouseUp, false); - document.getElementById("controls").removeEventListener("mousemove", seekToMove); - document.getElementById("controls").removeEventListener("click", seekToClick); - Helper.removeElement("#seekToDuration"); - socket.on("color", Player.setBGimage); - socket.emit("pos", {channel: chan.toLowerCase()}); - var add = ""; - socket.emit("list", {version: parseInt(_VERSION), channel: add + chan.toLowerCase()}); - Helper.removeClass("#controls", "ewresize"); - } - } -} - -function seekToClick(e){ + var mouseDown = function(e) { var acceptable = ["bar", "controls", "duration"]; - - if(acceptable.indexOf(e.target.getAttribute("id")) >= 0) { - if(full_playlist == undefined) return; - var total = full_playlist[full_playlist.length - 1].duration / document.getElementById("controls").offsetWidth; - total = total * e.clientX; - - if(!chromecastAvailable){ - if(videoSource == "youtube") Player.player.seekTo(total + Player.np.start); - else if(videoSource == "soundcloud") Player.soundcloud_player.seek((total + Player.np.start) * 1000); - dMinutes = Math.floor(duration / 60); - dSeconds = duration - dMinutes * 60; - currDurr = total; - if(currDurr - Player.np.start > duration) { - currDurr = duration - Player.np.start; - } - currDurr = currDurr - Player.np.start; - minutes = Math.floor(currDurr / 60); - seconds = currDurr - (minutes * 60); - document.getElementById("duration").innerHTML = Helper.pad(minutes)+":"+Helper.pad(seconds)+" / "+Helper.pad(dMinutes)+":"+Helper.pad(dSeconds); - per = (100 / duration) * currDurr; - if(per >= 100) - per = 100; - else if(duration === 0) - per = 0; - document.getElementById("bar").style.width = per + "%" - } else { - castSession.sendMessage("urn:x-cast:zoff.me", {type: "seekTo", seekTo: total}); - } + if (acceptable.indexOf(e.target.id) >= 0) { + dragging = true; } + }; + + var mouseUp = function(e) { + dragging = false; + }; + + if (enabled) { + Helper.addClass("#viewers", "hide"); + Helper.removeClass(".margin-playbar", "margin-playbar"); + Helper.addClass(".prev playbar", "margin-playbar"); + Helper.removeClass(".prev playbar", "hide"); + Helper.removeClass("#offline-mode", "waves-cyan"); + Helper.addClass("#offline-mode", "cyan"); + Helper.removeClass(".delete-context-menu", "context-menu-disabled"); + if (!Helper.mobilecheck()) { + Helper.tooltip("#offline-mode", { + delay: 5, + position: "bottom", + html: "Disable local mode" + }); + } + + if (window.location.pathname != "/") { + socket.removeEventListener("color"); + document + .getElementById("controls") + .addEventListener("mouseenter", mouseEnter, false); + document + .getElementById("controls") + .addEventListener("mouseleave", mouseLeave, false); + document + .getElementById("controls") + .addEventListener("mousedown", mouseDown, false); + document + .getElementById("controls") + .addEventListener("mouseup", mouseUp, false); + document + .getElementById("controls") + .addEventListener("mousemove", seekToMove); + document + .getElementById("controls") + .addEventListener("click", seekToClick); + + document + .querySelector("#main_components") + .insertAdjacentHTML( + "beforeend", + "
00:00/01:00
" + ); + var controlElement = document.querySelector("#controls"); + if (!Helper.mobilecheck()) + Helper.css( + "#seekToDuration", + "top", + -controlElement.offsetHeight - 25 + "px" + ); + else if (Helper.mobilecheck()) + Helper.css( + "#seekToDuration", + "top", + -controlElement.offsetHeight - 25 + "px" + ); + Helper.addClass("#controls", "ewresize"); + } + if (full_playlist != undefined && !already_offline) { + for (var x = 0; x < full_playlist.length; x++) { + full_playlist[x].votes = 0; + } + List.sortList(); + List.populate_list(full_playlist); + } + } else { + if (!Admin.logged_in) + Helper.addClass(".delete-context-menu", "context-menu-disabled"); + Helper.removeClass(".margin-playbar", "margin-playbar"); + Helper.addClass("#playpause", "margin-playbar"); + Helper.removeClass("#viewers", "hide"); + Helper.addClass(".prev playbar", "hide"); + Helper.addClass("#offline-mode", "waves-cyan"); + Helper.removeClass("#offline-mode", "cyan"); + if (!Helper.mobilecheck()) { + Helper.tooltip("#offline-mode", { + delay: 5, + position: "bottom", + html: "Enable local mode" + }); + } + + if (window.location.pathname != "/") { + document + .getElementById("controls") + .removeEventListener("mouseenter", mouseEnter, false); + document + .getElementById("controls") + .removeEventListener("mouseleave", mouseLeave, false); + document + .getElementById("controls") + .removeEventListener("mousedown", mouseDown, false); + document + .getElementById("controls") + .removeEventListener("mouseup", mouseUp, false); + document + .getElementById("controls") + .removeEventListener("mousemove", seekToMove); + document + .getElementById("controls") + .removeEventListener("click", seekToClick); + Helper.removeElement("#seekToDuration"); + socket.on("color", Player.setBGimage); + socket.emit("pos", { channel: chan.toLowerCase() }); + var add = ""; + socket.emit("list", { + version: parseInt(_VERSION), + channel: add + chan.toLowerCase() + }); + Helper.removeClass("#controls", "ewresize"); + } + } } -function seekToMove(e){ - var pos_x = event.clientX - Math.ceil(document.getElementById("seekToDuration").offsetWidth / 2); - if(pos_x < 0) pos_x = 0; - else if(pos_x + document.getElementById("seekToDuration").offsetWidth > document.getElementById("controls").offsetWidth) { - pos_x = document.getElementById("controls").offsetWidth - document.getElementById("seekToDuration").offsetWidth; - } - Helper.css("#seekToDuration", "left", pos_x + "px"); - try{ - var total = full_playlist[full_playlist.length - 1].duration / document.getElementById("controls").offsetWidth; - total = total * event.clientX; - var _time = Helper.secondsToOther(total); - var _minutes = Helper.pad(_time[0]); - var _seconds = Helper.pad(Math.ceil(_time[1])); - Helper.setHtml("#seekToDuration", _minutes + ":" + _seconds); +function seekToClick(e) { + var acceptable = ["bar", "controls", "duration"]; - var acceptable = ["bar", "controls", "duration"]; - if(acceptable.indexOf(event.target.getAttribute("id")) >= 0 && dragging) { - document.getElementById("bar").style.width(((100 / duration) * total) + "%"); - } - } catch(e){} + if (acceptable.indexOf(e.target.getAttribute("id")) >= 0) { + if (full_playlist == undefined) return; + var total = + full_playlist[full_playlist.length - 1].duration / + document.getElementById("controls").offsetWidth; + total = total * e.clientX; + + if (!chromecastAvailable) { + if (videoSource == "youtube") + Player.player.seekTo(total + Player.np.start); + else if (videoSource == "soundcloud") + Player.soundcloud_player.seek((total + Player.np.start) * 1000); + dMinutes = Math.floor(duration / 60); + dSeconds = duration - dMinutes * 60; + currDurr = total; + if (currDurr - Player.np.start > duration) { + currDurr = duration - Player.np.start; + } + currDurr = currDurr - Player.np.start; + minutes = Math.floor(currDurr / 60); + seconds = currDurr - minutes * 60; + document.getElementById("duration").innerHTML = + Helper.pad(minutes) + + ":" + + Helper.pad(seconds) + + " / " + + Helper.pad(dMinutes) + + ":" + + Helper.pad(dSeconds); + per = (100 / duration) * currDurr; + if (per >= 100) per = 100; + else if (duration === 0) per = 0; + document.getElementById("bar").style.width = per + "%"; + } else { + castSession.sendMessage("urn:x-cast:zoff.me", { + type: "seekTo", + seekTo: total + }); + } + } +} + +function seekToMove(e) { + var pos_x = + event.clientX - + Math.ceil(document.getElementById("seekToDuration").offsetWidth / 2); + if (pos_x < 0) pos_x = 0; + else if ( + pos_x + document.getElementById("seekToDuration").offsetWidth > + document.getElementById("controls").offsetWidth + ) { + pos_x = + document.getElementById("controls").offsetWidth - + document.getElementById("seekToDuration").offsetWidth; + } + Helper.css("#seekToDuration", "left", pos_x + "px"); + try { + var total = + full_playlist[full_playlist.length - 1].duration / + document.getElementById("controls").offsetWidth; + total = total * event.clientX; + var _time = Helper.secondsToOther(total); + var _minutes = Helper.pad(_time[0]); + var _seconds = Helper.pad(Math.ceil(_time[1])); + Helper.setHtml("#seekToDuration", _minutes + ":" + _seconds); + + var acceptable = ["bar", "controls", "duration"]; + if (acceptable.indexOf(event.target.getAttribute("id")) >= 0 && dragging) { + document + .getElementById("bar") + .style.width((100 / duration) * total + "%"); + } + } catch (e) {} } function resizePlaylistPlaying(playing, resizing) { - if(document.querySelector("#wrapper") == null || embed || client) return; - if(window.innerWidth < 601) { - var subtract = 0; - if(playing) { - var height = window.innerHeight - 246 - 170 - subtract; - Helper.css("#chat-bar", "height", height + "px"); - Helper.css("#channelchat", "height", height - 130 + "px"); - Helper.css("#all_chat", "height", height - 130 + "px"); - Helper.css("#chat-container", "height", height + "px"); - subtract = 200; - } else { - document.querySelector("#chat-bar").style.height = ""; - document.querySelector("#channelchat").style.height = ""; - document.querySelector("#all_chat").style.height = ""; - document.querySelector("#chat-container").style.height = ""; - } - var page = List.page; - var canFit = List.can_fit; - Helper.css("#wrapper", "height", window.innerHeight - 246 - subtract + "px"); - - if(!embed && !client){ - temp_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71); - List.element_height = (Helper.computedStyle("#wrapper", "height") / temp_fit)-5.3; - } else { - temp_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71)+1; - List.element_height = (Helper.computedStyle("#wrapper", "height") / temp_fit)-5.3; - } - if(List.element_height < 55.2 && !client){ - temp_fit = temp_fit - 1; - List.element_height = 55.2; - temp_fit = Math.round((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / 71); - List.element_height = ((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / temp_fit)-5; - } - - if(temp_fit > List.can_fit || temp_fit < List.can_fit){ - List.dynamicContentPage(-10); - } - if(List.can_fit < temp_fit){ - Helper.css(document.querySelector("#wrapper").children, "display", "none"); - for(var i = 0; i < List.page + temp_fit; i++) { - Helper.css(document.querySelector("#wrapper").children[i], "display", "inline-flex"); - } - } else if(List.can_fit > temp_fit){ - //Helper.css(document.querySelector("#wrapper").children, "display", "none"); - Helper.css(document.querySelector("#wrapper").children[List.page + temp_fit], "display", "none"); - var elements = document.querySelector("#wrapper").children; - for(var i = List.page + temp_fit; i < elements.length; i++) { - Helper.css(document.querySelector("#wrapper").children[i], "display", "none"); - } - } - List.can_fit = temp_fit; - List.element_height = (Helper.computedStyle("#wrapper", "height") / List.can_fit)-5.3; - Helper.css(".list-song", "height", List.element_height + "px"); - Channel.set_title_width(); - var toJumpTo = page / canFit; - if(toJumpTo > Math.floor(full_playlist.length / List.can_fit) && resizing) { - toJumpTo = Math.floor(full_playlist.length / List.can_fit); - } - List.dynamicContentPageJumpTo(toJumpTo); - if(!client) { - var controlsPosition = document.querySelector("#controls").offsetHeight - Helper.computedStyle("#controls", "height"); - if(document.querySelectorAll("#controls").length > 0 && !Helper.mobilecheck()) { - Helper.css(document.querySelector("#seekToDuration"), "top", controlsPosition - 55); - } else if(document.querySelectorAll("#controls").length > 0) { - Helper.css(document.querySelector("#seekToDuration"), "top", controlsPosition - 20); - } - Channel.window_width_volume_slider(); - } + if (document.querySelector("#wrapper") == null || embed || client) return; + if (window.innerWidth < 601) { + var subtract = 0; + if (playing) { + var height = window.innerHeight - 246 - 170 - subtract; + Helper.css("#chat-bar", "height", height + "px"); + Helper.css("#channelchat", "height", height - 130 + "px"); + Helper.css("#all_chat", "height", height - 130 + "px"); + Helper.css("#chat-container", "height", height + "px"); + subtract = 200; + } else { + document.querySelector("#chat-bar").style.height = ""; + document.querySelector("#channelchat").style.height = ""; + document.querySelector("#all_chat").style.height = ""; + document.querySelector("#chat-container").style.height = ""; } + var page = List.page; + var canFit = List.can_fit; + Helper.css( + "#wrapper", + "height", + window.innerHeight - 246 - subtract + "px" + ); + + if (!embed && !client) { + temp_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71); + List.element_height = + Helper.computedStyle("#wrapper", "height") / temp_fit - 5.3; + } else { + temp_fit = + Math.round(Helper.computedStyle("#wrapper", "height") / 71) + 1; + List.element_height = + Helper.computedStyle("#wrapper", "height") / temp_fit - 5.3; + } + if (List.element_height < 55.2 && !client) { + temp_fit = temp_fit - 1; + List.element_height = 55.2; + temp_fit = Math.round( + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + 71 + ); + List.element_height = + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + temp_fit - + 5; + } + + if (temp_fit > List.can_fit || temp_fit < List.can_fit) { + List.dynamicContentPage(-10); + } + if (List.can_fit < temp_fit) { + Helper.css( + document.querySelector("#wrapper").children, + "display", + "none" + ); + for (var i = 0; i < List.page + temp_fit; i++) { + Helper.css( + document.querySelector("#wrapper").children[i], + "display", + "inline-flex" + ); + } + } else if (List.can_fit > temp_fit) { + //Helper.css(document.querySelector("#wrapper").children, "display", "none"); + Helper.css( + document.querySelector("#wrapper").children[List.page + temp_fit], + "display", + "none" + ); + var elements = document.querySelector("#wrapper").children; + for (var i = List.page + temp_fit; i < elements.length; i++) { + Helper.css( + document.querySelector("#wrapper").children[i], + "display", + "none" + ); + } + } + List.can_fit = temp_fit; + List.element_height = + Helper.computedStyle("#wrapper", "height") / List.can_fit - 5.3; + Helper.css(".list-song", "height", List.element_height + "px"); + Channel.set_title_width(); + var toJumpTo = page / canFit; + if ( + toJumpTo > Math.floor(full_playlist.length / List.can_fit) && + resizing + ) { + toJumpTo = Math.floor(full_playlist.length / List.can_fit); + } + List.dynamicContentPageJumpTo(toJumpTo); + if (!client) { + var controlsPosition = + document.querySelector("#controls").offsetHeight - + Helper.computedStyle("#controls", "height"); + if ( + document.querySelectorAll("#controls").length > 0 && + !Helper.mobilecheck() + ) { + Helper.css( + document.querySelector("#seekToDuration"), + "top", + controlsPosition - 55 + ); + } else if (document.querySelectorAll("#controls").length > 0) { + Helper.css( + document.querySelector("#seekToDuration"), + "top", + controlsPosition - 20 + ); + } + Channel.window_width_volume_slider(); + } + } } function pagination_results(e) { - this.preventDefault(); - var that = e; - var pageToken = that.getAttribute("data-pagination"); - var searchInput = that.getAttribute("data-original-search"); + this.preventDefault(); + var that = e; + var pageToken = that.getAttribute("data-pagination"); + var searchInput = that.getAttribute("data-original-search"); - Helper.addClass(".next-results-button", "disabled"); - Helper.addClass(".prev-results-button", "disabled"); - Search.search(searchInput, false, false, pageToken); + Helper.addClass(".next-results-button", "disabled"); + Helper.addClass(".prev-results-button", "disabled"); + Search.search(searchInput, false, false, pageToken); } function handleEvent(e, target, tried, type) { - var path = e.path || (e.composedPath && e.composedPath()); - if(!path) { - var path = [target]; - var parent = target.parentElement; - while(parent != null) { - path.push(parent); - try { - parent = parent.parentElement; - } catch(e){break;} - } + var path = e.path || (e.composedPath && e.composedPath()); + if (!path) { + var path = [target]; + var parent = target.parentElement; + while (parent != null) { + path.push(parent); + try { + parent = parent.parentElement; + } catch (e) { + break; + } } - if(path) { - for(var y = 0; y < path.length; y++) { - var target = path[y]; - if(dynamicListeners[type] && dynamicListeners[type]["#" + target.id]) { - dynamicListeners[type]["#" + target.id].call(e, target); - return; - } else { - if(target.classList == undefined) return; - for(var i = 0; i < target.classList.length; i++) { - if(dynamicListeners[type] && dynamicListeners[type]["." + target.classList[i]]) { - dynamicListeners[type]["." + target.classList[i]].call(e, target); - return; - } - } - } + } + if (path) { + for (var y = 0; y < path.length; y++) { + var target = path[y]; + if (dynamicListeners[type] && dynamicListeners[type]["#" + target.id]) { + dynamicListeners[type]["#" + target.id].call(e, target); + return; + } else { + if (target.classList == undefined) return; + for (var i = 0; i < target.classList.length; i++) { + if ( + dynamicListeners[type] && + dynamicListeners[type]["." + target.classList[i]] + ) { + dynamicListeners[type]["." + target.classList[i]].call(e, target); + return; + } } + } } + } } function addListener(type, element, callback) { - if(dynamicListeners[type] == undefined) dynamicListeners[type] = {}; - dynamicListeners[type][element] = callback; + if (dynamicListeners[type] == undefined) dynamicListeners[type] = {}; + dynamicListeners[type][element] = callback; } function removeListener(type, element) { - delete dynamicListeners[type][element]; + delete dynamicListeners[type][element]; } function toast(msg, _class) { - switch(msg) { - case "other_list_pass": - msg = "The other list has a pass, can't import the songs.."; - break; - case "suggested_rules": - msg = "Your rules have been suggested"; - break; - case "rules_denied": - msg = "Your rules will be denied"; - break; - case "nolist": - msg = "There is no list with that name"; - break; - case "suggested_thumbnail": - if(embed) return; - msg = "The thumbnail has been suggested!"; - break; - case "faulty_start_end": - if(embed) return; - msg = "You tried to send a faulty start/end value. Try again.."; - break; - case "wait_longer": - if(embed) return; - msg = Helper.rnd(["Have you tried to wait longer between commands?!", "Looks like you're clicking that button too much..", "You need to wait longer between clicks.."]); - break; - case "suggested_description": - if(embed) return; - msg = "The description has been suggested!"; - break; - case "thumbnail_denied": - if(embed) return; - msg = "The thumbnail is not an url.."; - break; - case "description_denied": - if(embed) return; - msg = "The description will be denied"; - break; - case "addedsong": - if(embed) return; - msg=Helper.rnd(["I added your song", "Your song has been added", "Yay, more songs!", "Thats a cool song!", "I added that song for you", "I see you like adding songs..."]); - break; - case "addedplaylist": - if(embed) return; - if(Search.submitYouTubeError) { - M.toast({html: "Added most of your playlist, but something was wrong. Check the playlist..", displayLength: 4000, classes: "red lighten connect_error"}); - Search.submitYouTubeError = false; - return; + switch (msg) { + case "other_list_pass": + msg = "The other list has a pass, can't import the songs.."; + break; + case "suggested_rules": + msg = "Your rules have been suggested"; + break; + case "rules_denied": + msg = "Your rules will be denied"; + break; + case "nolist": + msg = "There is no list with that name"; + break; + case "suggested_thumbnail": + if (embed) return; + msg = "The thumbnail has been suggested!"; + break; + case "faulty_start_end": + if (embed) return; + msg = "You tried to send a faulty start/end value. Try again.."; + break; + case "wait_longer": + if (embed) return; + msg = Helper.rnd([ + "Have you tried to wait longer between commands?!", + "Looks like you're clicking that button too much..", + "You need to wait longer between clicks.." + ]); + break; + case "suggested_description": + if (embed) return; + msg = "The description has been suggested!"; + break; + case "thumbnail_denied": + if (embed) return; + msg = "The thumbnail is not an url.."; + break; + case "description_denied": + if (embed) return; + msg = "The description will be denied"; + break; + case "addedsong": + if (embed) return; + msg = Helper.rnd([ + "I added your song", + "Your song has been added", + "Yay, more songs!", + "Thats a cool song!", + "I added that song for you", + "I see you like adding songs..." + ]); + break; + case "addedplaylist": + if (embed) return; + if (Search.submitYouTubeError) { + M.toast({ + html: + "Added most of your playlist, but something was wrong. Check the playlist..", + displayLength: 4000, + classes: "red lighten connect_error" + }); + Search.submitYouTubeError = false; + return; + } + msg = Helper.rnd([ + "I added the playlist", + "Your playlist has been added", + "Yay, many more songs!", + "Thats a cool playlist!", + "I added all the songs for you", + "I see you like adding songs.." + ]); + document.getElementById("import").disabled = false; + Helper.addClass("#playlist_loader", "hide"); + Helper.removeClass("#import", "hide"); + break; + case "savedsettings": + if (embed) return; + msg = Helper.rnd([ + "I've saved your settings", + "I stored all your settings", + "Your settings have been stored in a safe place" + ]); + break; + case "wrongpass": + if (embed) return; + msg = Helper.rnd([ + "That's not the right password!", + "Wrong! Better luck next time...", + "You seem to have mistyped the password", + "Incorrect. Have you tried meditating?", + "Nope, wrong password!", + "Wrong password. The authorities have been notified." + ]); + //Crypt.remove_pass(chan.toLowerCase()); + Admin.display_logged_out(); + Helper.css("#thumbnail_form", "display", "none"); + Helper.css("#description_form", "display", "none"); + w_p = true; + break; + case "deleted_songs": + if (embed) return; + msg = "All songs in the channel has been deleted!"; + break; + case "shuffled": + if (embed) return; + msg = Helper.rnd([ + "♫ You stir me right round, baby. ♫", + "♫ Stir, stir, stir my boat ♫", + "I vigorously stirred your playlist!", + "I hope you like your list stirred, not shaken.", + "I shuffled your playlist with the cosmic background radiation as a seed. Enjoy.", + "100% randomized, for your listening pleasure!", + "I hope you enjoy your fresh playlist!" + ]); + break; + case "deletesong": + if (embed) return; + msg = Helper.rnd([ + "Your song is now in a better place...", + "You won't be seeing any more of that video...", + "EXTERMINATE! EXTERMINATE! EXTERMINATE!", + "I killed it with fire", + "Thanks for deleting that song. I didn't like it anyways...", + "Removed song securely." + ]); + break; + case "voted": + msg = Helper.rnd([ + "You voted!", + "You vote like a boss", + "Voting is the key to democracy", + "May you get your song to the very top!", + "I love that song! I vouch for you.", + "Only you vote that good", + "I like the way you vote...", + "Up the video goes!", + "Voted Zoff for president", + "Only 999 more to go!" + ]); + break; + case "alreadyvoted": + msg = Helper.rnd([ + "You can't vote twice on that song!", + "I see you have voted on that song before", + "One vote per person!", + "I know you want to hear your song, but have patience!", + "I'm sorry, but I can't let you vote twice, Dave." + ]); + break; + case "skip": + if (embed) return; + msg = Helper.rnd([ + "The song was skipped", + "I have skipped a song", + "Skipped to the beat", + "Skipmaster3000", + "They see me skippin', they hatin'" + ]); + break; + case "listhaspass": + if (embed) return; + if (!tried_again && lastCommand != undefined && lastCommand.length > 0) { + if (Crypt.get_pass() != undefined) { + tried_again = true; + if (lastCommand.length == 1) { + socket.emit(lastCommand[0]); + } else if (lastCommand.length == 2) { + socket.emit(lastCommand[0], lastCommand[1]); + } + lastCommand = []; + return; } - msg=Helper.rnd(["I added the playlist", "Your playlist has been added", "Yay, many more songs!", "Thats a cool playlist!", "I added all the songs for you", "I see you like adding songs.."]); - document.getElementById("import").disabled = false; - Helper.addClass("#playlist_loader", "hide"); - Helper.removeClass("#import", "hide"); - break; - case "savedsettings": - if(embed) return; - msg=Helper.rnd(["I've saved your settings", "I stored all your settings", "Your settings have been stored in a safe place"]); - break; - case "wrongpass": - if(embed) return; - msg=Helper.rnd(["That's not the right password!", "Wrong! Better luck next time...", "You seem to have mistyped the password", "Incorrect. Have you tried meditating?","Nope, wrong password!", "Wrong password. The authorities have been notified."]); - //Crypt.remove_pass(chan.toLowerCase()); - Admin.display_logged_out(); - Helper.css("#thumbnail_form", "display", "none"); - Helper.css("#description_form", "display", "none"); - w_p = true; - break; - case "deleted_songs": - if(embed) return; - msg="All songs in the channel has been deleted!"; - break; - case "shuffled": - if(embed) return; - msg=Helper.rnd(["♫ You stir me right round, baby. ♫","♫ Stir, stir, stir my boat ♫","I vigorously stirred your playlist!", "I hope you like your list stirred, not shaken.", "I shuffled your playlist with the cosmic background radiation as a seed. Enjoy.", "100% randomized, for your listening pleasure!", "I hope you enjoy your fresh playlist!"]); - break; - case "deletesong": - if(embed) return; - msg=Helper.rnd(["Your song is now in a better place...", "You won't be seeing any more of that video...", "EXTERMINATE! EXTERMINATE! EXTERMINATE!", "I killed it with fire", "Thanks for deleting that song. I didn't like it anyways...", "Removed song securely."]); - break; - case "voted": - msg=Helper.rnd(["You voted!", "You vote like a boss", "Voting is the key to democracy", "May you get your song to the very top!", "I love that song! I vouch for you.", "Only you vote that good", "I like the way you vote...", "Up the video goes!", "Voted Zoff for president", "Only 999 more to go!"]); - break; - case "alreadyvoted": - msg=Helper.rnd(["You can't vote twice on that song!", "I see you have voted on that song before", "One vote per person!", "I know you want to hear your song, but have patience!", "I'm sorry, but I can't let you vote twice, Dave."]); - break; - case "skip": - if(embed) return; - msg=Helper.rnd(["The song was skipped", "I have skipped a song", "Skipped to the beat", "Skipmaster3000", "They see me skippin', they hatin'"]); - break; - case "listhaspass": - if(embed) return; - if(!tried_again && lastCommand != undefined && lastCommand.length > 0) { - if(Crypt.get_pass() != undefined) { - tried_again = true; - if(lastCommand.length == 1) { - socket.emit(lastCommand[0]); - } else if(lastCommand.length == 2) { - socket.emit(lastCommand[0], lastCommand[1]); - } - lastCommand = []; - return; - } + } + document.getElementById("import_spotify").disabled = false; + document.getElementById("import").disabled = false; + tried_again = false; + msg = Helper.rnd([ + "I'm sorry, but you have to be an admin to do that!", + "Only admins can do that", + "You're not allowed to do that, try logging in!", + "I can't let you do that", + "Please log in to do that" + ]); + //Crypt.remove_pass(chan.toLowerCase()); + Admin.display_logged_out(); + Helper.css("#thumbnail_form", "display", "none"); + Helper.css("#description_form", "display", "none"); + w_p = true; + Helper.addClass("#playlist_loader", "hide"); + Helper.addClass("#playlist_loader_spotify", "hide"); + Helper.removeClass("#import_spotify", "hide"); + Helper.removeClass("#import", "hide"); + break; + case "noskip": + if (embed) return; + if (!tried_again && lastCommand != undefined && lastCommand.length > 0) { + if (Crypt.get_pass() != undefined) { + tried_again = true; + if (lastCommand.length == 1) { + socket.emit(lastCommand[0]); + } else if (lastCommand.length == 2) { + socket.emit(lastCommand[0], lastCommand[1]); + } + lastCommand = []; + return; } - document.getElementById("import_spotify").disabled = false; - document.getElementById("import").disabled = false; - tried_again = false; - msg=Helper.rnd(["I'm sorry, but you have to be an admin to do that!", "Only admins can do that", "You're not allowed to do that, try logging in!", "I can't let you do that", "Please log in to do that"]); - //Crypt.remove_pass(chan.toLowerCase()); - Admin.display_logged_out(); - Helper.css("#thumbnail_form", "display", "none"); - Helper.css("#description_form", "display", "none"); - w_p = true; - Helper.addClass("#playlist_loader", "hide"); - Helper.addClass("#playlist_loader_spotify", "hide"); - Helper.removeClass("#import_spotify", "hide"); - Helper.removeClass("#import", "hide"); - break; - case "noskip": - if(embed) return; - if(!tried_again && lastCommand != undefined && lastCommand.length > 0) { - if(Crypt.get_pass() != undefined) { - tried_again = true; - if(lastCommand.length == 1) { - socket.emit(lastCommand[0]); - } else if(lastCommand.length == 2) { - socket.emit(lastCommand[0], lastCommand[1]); - } - lastCommand = []; - return; - } - } - tried_again = false; - msg=Helper.rnd(["Only Admins can skip songs, peasant!", "You have to log in to skip songs on this channel", "Try clicking the settings icon and logging in before you skip"]); - break; - case "alreadyskip": - if(embed) return; - msg=Helper.rnd(["Skipping is democratic, only one vote per person!", "More people have to vote to skip, not just you!", "Get someone else to skip too! You can't do it on yourself."]); - break; - case "notyetskip": - if(embed) return; - msg="Skipping is disabled the first 10 seconds."; - break; - case "correctpass": - if(embed) return; - tried_again = false; - adminpass = Crypt.get_pass(chan.toLowerCase()) == undefined ? Crypt.tmp_pass : Crypt.get_pass(chan.toLowerCase()); - msg="Correct password. You now have access to the sacred realm of The Admin."; - Helper.css("#thumbnail_form", "display", "inline-block"); - Helper.css("#description_form", "display", "inline-block"); - break; - case "changedpass": - if(embed) return; - msg="Your password has been changed!"; - break; - case "suggested": - if(embed) return; - msg="Your song was suggested!"; - break; - case "alreadyplay": - if(embed) return; - msg="Seems the song you want is already playing. No fooling the system!"; - break; - } - before_toast(); - var classes = _class == undefined ? "" : _class; - M.toast({ html: msg, displayLength: 4000, classes: classes}); + } + tried_again = false; + msg = Helper.rnd([ + "Only Admins can skip songs, peasant!", + "You have to log in to skip songs on this channel", + "Try clicking the settings icon and logging in before you skip" + ]); + break; + case "alreadyskip": + if (embed) return; + msg = Helper.rnd([ + "Skipping is democratic, only one vote per person!", + "More people have to vote to skip, not just you!", + "Get someone else to skip too! You can't do it on yourself." + ]); + break; + case "notyetskip": + if (embed) return; + msg = "Skipping is disabled the first 10 seconds."; + break; + case "correctpass": + if (embed) return; + tried_again = false; + adminpass = + Crypt.get_pass(chan.toLowerCase()) == undefined + ? Crypt.tmp_pass + : Crypt.get_pass(chan.toLowerCase()); + msg = + "Correct password. You now have access to the sacred realm of The Admin."; + Helper.css("#thumbnail_form", "display", "inline-block"); + Helper.css("#description_form", "display", "inline-block"); + break; + case "changedpass": + if (embed) return; + msg = "Your password has been changed!"; + break; + case "suggested": + if (embed) return; + msg = "Your song was suggested!"; + break; + case "alreadyplay": + if (embed) return; + msg = + "Seems the song you want is already playing. No fooling the system!"; + break; + } + before_toast(); + var classes = _class == undefined ? "" : _class; + M.toast({ html: msg, displayLength: 4000, classes: classes }); } function emit() { - if(!embed) { - lastCommand = []; - for(var i = 0; i < arguments.length; i++) { - lastCommand.push(arguments[i]); - } - } - if(arguments.length == 1) { - socket.emit(arguments[0]); - } else { - socket.emit(arguments[0], arguments[1]); + if (!embed) { + lastCommand = []; + for (var i = 0; i < arguments.length; i++) { + lastCommand.push(arguments[i]); } + } + if (arguments.length == 1) { + socket.emit(arguments[0]); + } else { + socket.emit(arguments[0], arguments[1]); + } } -function before_toast(){ - M.Toast.dismissAll(); +function before_toast() { + M.Toast.dismissAll(); } function addJoinBox() { - document.querySelector("#video-container").insertAdjacentHTML("beforeend", '
Listen directly on https://zoff.me
'); + document + .querySelector("#video-container") + .insertAdjacentHTML( + "beforeend", + '
Listen directly on https://zoff.me
' + ); } function scrollChat() { - var current = document.querySelector(".chatTabs .active").getAttribute("href"); - if(current == "#channelchat") { - document.querySelector('#chatchannel').scrollTop = document.querySelector('#chatchannel').scrollHeight; - } else if(current == "#all_chat") { - document.querySelector('#chatall').scrollTop = document.querySelector('#chatall').scrollHeight; - } + var current = document + .querySelector(".chatTabs .active") + .getAttribute("href"); + if (current == "#channelchat") { + document.querySelector("#chatchannel").scrollTop = document.querySelector( + "#chatchannel" + ).scrollHeight; + } else if (current == "#all_chat") { + document.querySelector("#chatall").scrollTop = document.querySelector( + "#chatall" + ).scrollHeight; + } } function hideAllExtra() { - document.querySelector(".settings-collapsible").children[0].style.display = "none"; - document.querySelector(".settings-collapsible").children[2].style.display = "none"; - document.querySelector(".settings-collapsible").children[3].style.display = "none"; - document.querySelector(".settings-collapsible").children[4].style.display = "none"; - document.querySelector(".settings-collapsible").children[5].style.display = "none"; - document.querySelector(".settings-collapsible").children[6].style.display = "none"; - document.querySelector(".settings-collapsible").children[7].style.display = "none"; - + document.querySelector(".settings-collapsible").children[0].style.display = + "none"; + document.querySelector(".settings-collapsible").children[2].style.display = + "none"; + document.querySelector(".settings-collapsible").children[3].style.display = + "none"; + document.querySelector(".settings-collapsible").children[4].style.display = + "none"; + document.querySelector(".settings-collapsible").children[5].style.display = + "none"; + document.querySelector(".settings-collapsible").children[6].style.display = + "none"; + document.querySelector(".settings-collapsible").children[7].style.display = + "none"; } function searchTimeout(event) { - search_input = document.getElementsByClassName("search_input")[0].value; + search_input = document.getElementsByClassName("search_input")[0].value; - code = event.keyCode || event.which; + code = event.keyCode || event.which; - if (code != 40 && code != 38 && code != 13 && code != 39 && code != 37 && code != 17 && code != 16 && code != 225 && code != 18 && code != 27) { - clearTimeout(timeout_search); - /*if(search_input.length < 3){ + if ( + code != 40 && + code != 38 && + code != 13 && + code != 39 && + code != 37 && + code != 17 && + code != 16 && + code != 225 && + code != 18 && + code != 27 + ) { + clearTimeout(timeout_search); + /*if(search_input.length < 3){ Helper.css(".results-tabs", "display", "none"); document.querySelector("#results").innerHTML = ""; document.querySelector("#results_soundcloud").innerHTML = ""; @@ -1433,14 +1964,14 @@ function searchTimeout(event) { document.querySelector("body").setAttribute("style", "overflow-y: auto"); } }*/ -if(code == 13){ - Search.search(search_input); - Search.soundcloudSearch(search_input); -}else{ - timeout_search = setTimeout(function(){ + if (code == 13) { + Search.search(search_input); + Search.soundcloudSearch(search_input); + } else { + timeout_search = setTimeout(function() { Search.search(search_input); Search.soundcloudSearch(search_input); - }, 1000); -} -} + }, 1000); + } + } } diff --git a/server/public/assets/js/list.js b/server/public/assets/js/list.js index 07a8ca1d..95bd1e55 100755 --- a/server/public/assets/js/list.js +++ b/server/public/assets/js/list.js @@ -1,1376 +1,2018 @@ var List = { + empty: false, + page: 0, + can_fit: + document.querySelectorAll("#wrapper").length > 0 + ? Math.round(Helper.computedStyle("#wrapper", "height") / 71) + : 0, + element_height: + document.querySelectorAll("#wrapper").length > 0 + ? Helper.computedStyle("#wrapper", "height") / + Math.round(Helper.computedStyle("#wrapper", "height") / 71) - + 25 + : 0, + uris: [], + not_found: [], + num_songs: 0, + found: [], - empty: false, - page: 0, - can_fit: document.querySelectorAll("#wrapper").length > 0 ? Math.round(Helper.computedStyle("#wrapper", "height") / 71) : 0, - element_height: document.querySelectorAll("#wrapper").length > 0 ? (Helper.computedStyle("#wrapper", "height") / Math.round(Helper.computedStyle("#wrapper", "height") / 71)) - 25 : 0, - uris: [], - not_found: [], - num_songs: 0, - found: [], - - channel_function: function(msg) { - if(Helper.mobilecheck()) socket_connected = true; - if(user_auth_started) { - user_auth_started = false; - M.Modal.getInstance(document.getElementById("user_password")).close(); - } - switch(msg.type) - { - - case "list": - //if(full_playlist == undefined || !offline){ - if((!offline || (offline && !msg.shuffled)) && !(offline && prev_chan_list == chan)){ - prev_chan_list = chan; - List.populate_list(msg.playlist); - if(full_playlist.length > 0) { - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - } - } else if(offline && prev_chan_list == chan && full_playlist != undefined && !msg.shuffled){ - List.populate_list(full_playlist, true); - if(full_playlist.length > 0) { - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - } - } - break; - case "added": - List.added_song(msg.value); - if(full_playlist.length > 0) { - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - } - found_array = []; - found_array_index = 0; - break; - case "deleted": - List.deleted_song(msg.value, msg.removed); - found_array = []; - found_array_index = 0; - break; - case "vote": - if(!offline){ - List.voted_song(msg.value, msg.time); - if(full_playlist.length > 0) { - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - } - } - found_array = []; - found_array_index = 0; - break; - case "song_change": - if((offline && msg.offline_change) || !offline) { - if(window.location.pathname != "/") List.song_change(msg.time, msg.remove, msg.id); - if(full_playlist.length > 0) { - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - } - found_array = []; - found_array_index = 0; - } - break; - case "changed_values": - List.changedValues(msg.value); - break; - case "song_change_prev": - if((offline && msg.offline_change) || !offline) { - - if(window.location.pathname != "/") List.song_change_prev(msg.time); - if(full_playlist.length > 0) { - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - } - found_array = []; - found_array_index = 0; - } - break; - } - }, - - changedValues: function(song) { - if(song.type == "suggested") { - try { - document.querySelector("#suggested-" + song.id).querySelector(".vote-container").setAttribute("title", song.title); - document.querySelector("#suggested-" + song.id).querySelector(".list-title").setAttribute("title", song.title); - document.querySelector("#suggested-" + song.id).querySelector(".list-title").innerText = song.title; - var _temp_duration = Helper.secondsToOther(song.duration); - document.querySelector("#suggested-" + song.id).querySelector(".card-duration").innerText = Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); - document.querySelector("#suggested-" + song.id).querySelector(".list-image").setAttribute("style", "background-image:url('//img.youtube.com/vi/"+song.new_id+"/mqdefault.jpg');"); - document.querySelector("#suggested-" + song.id).setAttribute("id", song.new_id); - } catch(e) {} - return; - } - var i = List.getIndexOfSong(song.id); - if(i >= 0 && window.location.pathname != "/") { - full_playlist[i].title = song.title; - full_playlist[i].duration = song.duration; - full_playlist[i].start = song.start; - full_playlist[i].end = song.end; - full_playlist[i].id = song.new_id; - try { - document.querySelector("#" + song.id).querySelector(".vote-container").setAttribute("title", song.title); - document.querySelector("#" + song.id).querySelector(".list-title").setAttribute("title", song.title); - document.querySelector("#" + song.id).querySelector(".list-title").innerText = song.title; - var _temp_duration = Helper.secondsToOther(song.duration); - document.querySelector("#" + song.id).querySelector(".card-duration").innerText = Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); - document.querySelector("#" + song.id).querySelector(".list-image").setAttribute("style", "background-image:url('//img.youtube.com/vi/"+song.new_id+"/mqdefault.jpg');"); - document.querySelector("#" + song.id).setAttribute("id", song.new_id); - } catch(e) {} - } - }, - - insertAtBeginning: function(song_info, transition) { - if(document.querySelector("#wrapper") == null) return; - var display = List.page == 0 ? "" : "none"; - var add = List.generateSong(song_info, transition, false, true, false, display, false); - document.querySelector("#wrapper").insertAdjacentHTML("beforeend", add); - }, - - insertAtIndex: function(song_info, transition, change) { - if(document.querySelector("#wrapper") == null) return; - var i = List.getIndexOfSong(song_info.id); - if(i == -1) return; - if(!song_info.now_playing){ - var display = "none"; - if(i >= List.page && i < List.page + (List.can_fit)) display = "inline-flex" - var add = List.generateSong(song_info, transition, false, true, false, display, false); - if(i === 0) { - document.querySelector("#wrapper").insertAdjacentHTML("afterbegin", add); - } else { - document.querySelector("#wrapper > div:nth-child(" + (i) + ")").insertAdjacentHTML("afterend", add); - } - var added = document.querySelector("#wrapper").children[i]; - Helper.css(added, "display", display); - if(display == "inline-flex" && document.querySelector("#wrapper").children.length >= List.page + List.can_fit + 1){ - Helper.css(document.querySelector("#wrapper").children[List.page + List.can_fit], "display", "none"); - } else if(i < List.page && document.querySelector("#wrapper").children.length - (List.page + 1) >= 0){ - Helper.css(document.querySelector("#wrapper").children[List.page], "display", "inline-flex"); - } else if(document.querySelector("#wrapper").children.length > List.page + List.can_fit){ - Helper.css(document.querySelector("#wrapper").children[List.page + List.can_fit - 1], "display", "inline-flex"); - } - if(change && List.page > 0){ - Helper.css(document.querySelector("#wrapper").children[List.page - 1], "display", "none"); - } - if(transition){ - setTimeout(function(){ - Helper.css(added, "transform", "translateX(0%)"); - setTimeout(function() { - Helper.removeClass(added, "side_away"); - }, 300); - },5); - } - } - }, - - calculate_song_heights: function(){ - if(!Helper.mobilecheck() && !embed && !client){ - List.can_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71); - List.element_height = (Helper.computedStyle("#wrapper", "height") / List.can_fit)-5.3; - } else if(embed) { - List.can_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 91) + 1; - List.element_height = (Helper.computedStyle("#wrapper", "height") / List.can_fit)-4; - } else if(!client){ - List.can_fit = Math.round((Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / 71)+1; - List.element_height = ((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / List.can_fit)-5; - } else { - List.can_fit = Math.round(Helper.computedStyle("#wrapper", "height") / 71)+1; - List.element_height = (Helper.computedStyle("#wrapper", "height") / List.can_fit)-5.3; - } - if(List.element_height < 55.2 && !client && !embed){ - List.can_fit = List.can_fit - 1; - List.element_height = 55.2; - List.can_fit = Math.round((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / 71); - List.element_height = ((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / List.can_fit)-5; - } else if(List.element_height < 55.2 && embed) { - //List.can_fit = List.can_fit - 1; - List.can_fit = Math.round((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / 71); - List.element_height = ((window.innerHeight - Helper.computedStyle(".tabs", "height") - Helper.computedStyle("header", "height") - 64 - 40) / List.can_fit)-5; - List.can_fit = List.can_fit - 2; - } - }, - - populate_list: function(msg, no_reset) { - if(document.querySelector("#wrapper") == null) return; - // This math is fucked and I don't know how it works. Should be fixed sometime - if(list_html === undefined) list_html = Helper.html("#list-song-html"); - full_playlist = msg; - if(offline && !no_reset){ - for(var x = 0; x < full_playlist.length; x++){ - full_playlist[x].votes = 0; - } - } - List.sortList(); - - Helper.setHtml("#wrapper", ""); - - Helper.log([ - "FULL PLAYLIST", - full_playlist - ]); - if(full_playlist.length > 1){ - for(var j = 0; j < full_playlist.length; j++) { - var _current_song = full_playlist[j]; - if(!_current_song.hasOwnProperty("start")) full_playlist[j].start = 0; - if(!_current_song.hasOwnProperty("end")) full_playlist[j].end = full_playlist[j].duration; - if(!_current_song.now_playing && _current_song.type != "suggested"){ //check that the song isnt playing - var generated = List.generateSong(_current_song, false, lazy_load, true, false, "inline-flex", true) - document.querySelector("#wrapper").insertAdjacentHTML("beforeend", generated); - } - } - if(document.querySelector("#wrapper").children.length > List.can_fit && !document.querySelectorAll("#pageButtons").length){ - Helper.css(".prev_page", "display", "none"); - Helper.css(".first_page", "display", "none"); - Helper.css(".next_page_hide", "display","none"); - Helper.css(".last_page_hide", "display","none"); - } else if(!document.querySelectorAll("#pageButtons").length){ - Helper.css(".prev_page", "display", "none"); - Helper.css(".next_page", "display", "none"); - Helper.css(".last_page", "display", "none"); - Helper.css(".first_page", "display", "none"); - Helper.css(".next_page_hide", "display","inline-flex"); - Helper.css(".prev_page_hide", "display","inline-flex"); - } else { - Helper.css(".next_page", "display", "none"); - Helper.css(".last_page", "display", "none"); - } - - List.dynamicContentPage(-10); - - - } else { - List.empty = true; - Helper.setHtml("#wrapper", "The playlist is empty."); - Helper.css(".prev_page","display", "none"); - Helper.css(".next_page","display", "none"); - Helper.css(".last_page","display", "none"); - Helper.css(".last_page_hide","display", "inline-flex"); - Helper.css(".first_page","display", "none"); - Helper.css(".next_page_hide", "display","inline-flex"); - Helper.css(".prev_page_hide","display","inline-flex"); - } - Helper.css("#settings","visibility", "visible"); - Helper.css("#settings","opacity", "1"); - Helper.css("#wrapper","opacity", "1"); - Helper.removeClass("#pageButtons", "hide"); - - if(!embed) { - Helper.log(["Starting empty-checker"]); - clearTimeout(timed_remove_check); - timed_remove_check = setTimeout(function() { - if(full_playlist.length > 0) { - List.check_error_videos(0); - } - }, 1500); - } - }, - - check_error_videos: function(i) { - //Helper.log("Empty-checker at " + i); - if(full_playlist.length == 0) return; - else if(full_playlist[i].source == "soundcloud" && full_playlist.length > i + 1 && window.location.pathname != "/") List.check_error_videos(i + 1); - else { - Helper.ajax({ - method: "get", - url: 'https://www.googleapis.com/youtube/v3/videos?id=' + full_playlist[i].id - + "&key=" + api_key.youtube + "&part=snippet", - success: function (data) { - data = JSON.parse(data); - //Helper.log("Empty-checker items " + data.items.length); - if (data.items.length == 0) { - Helper.log(["Emtpy-checker error at " + full_playlist[i].id + " " + full_playlist[i].title]); - socket.emit("error_video", {channel: chan.toLowerCase(), id: full_playlist[i].id, title: full_playlist[i].title, source: full_playlist[i].source}); - } - if(full_playlist.length > i + 1 && window.location.pathname != "/") { - List.check_error_videos(i + 1); - } - } + channel_function: function(msg) { + if (Helper.mobilecheck()) socket_connected = true; + if (user_auth_started) { + user_auth_started = false; + M.Modal.getInstance(document.getElementById("user_password")).close(); + } + switch (msg.type) { + case "list": + //if(full_playlist == undefined || !offline){ + if ( + (!offline || (offline && !msg.shuffled)) && + !(offline && prev_chan_list == chan) + ) { + prev_chan_list = chan; + List.populate_list(msg.playlist); + if (full_playlist.length > 0) { + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail }); + } + } else if ( + offline && + prev_chan_list == chan && + full_playlist != undefined && + !msg.shuffled + ) { + List.populate_list(full_playlist, true); + if (full_playlist.length > 0) { + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + } } - }, - - dynamicContentPageJumpTo: function(page) { - if(document.querySelector("#wrapper") == null) return - page = page * List.can_fit; - var wrapperChildren = [].slice.call(document.querySelector("#wrapper").children); - if(page > List.page || page < List.page){ - Helper.css(wrapperChildren.slice(List.page, List.page + List.can_fit), "display", "none"); - List.page = page; - Helper.css(wrapperChildren.slice(List.page, List.page + List.can_fit), "display", "inline-flex"); - if(List.page > 0 && document.querySelector(".prev_page").style.display == "none"){ - Helper.css(".prev_page", "display", "inline-flex"); - Helper.css(".prev_page_hide", "display", "none"); - Helper.css(".first_page", "display", "inline-flex"); - Helper.css(".first_page_hide", "display", "none"); - } - - if(List.page + List.can_fit >= wrapperChildren.length){ - Helper.css(".next_page_hide", "display", "inline-flex"); - Helper.css(".next_page", "display", "none"); - Helper.css(".last_page_hide", "display", "inline-flex"); - Helper.css(".last_page", "display", "none"); - } - - Helper.setHtml("#pageNumber", (List.page / List.can_fit) + 1); + break; + case "added": + List.added_song(msg.value); + if (full_playlist.length > 0) { + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); } - }, + found_array = []; + found_array_index = 0; + break; + case "deleted": + List.deleted_song(msg.value, msg.removed); + found_array = []; + found_array_index = 0; + break; + case "vote": + if (!offline) { + List.voted_song(msg.value, msg.time); + if (full_playlist.length > 0) { + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + } + } + found_array = []; + found_array_index = 0; + break; + case "song_change": + if ((offline && msg.offline_change) || !offline) { + if (window.location.pathname != "/") + List.song_change(msg.time, msg.remove, msg.id); + if (full_playlist.length > 0) { + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + } + found_array = []; + found_array_index = 0; + } + break; + case "changed_values": + List.changedValues(msg.value); + break; + case "song_change_prev": + if ((offline && msg.offline_change) || !offline) { + if (window.location.pathname != "/") List.song_change_prev(msg.time); + if (full_playlist.length > 0) { + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + } + found_array = []; + found_array_index = 0; + } + break; + } + }, - dynamicContentPage: function(way) { - if(document.querySelector("#wrapper") == null) return - var wrapperChildren = [].slice.call(document.querySelector("#wrapper").children); - if(way == 1 || way == 10) { - Helper.css(wrapperChildren.slice(List.page, List.page + List.can_fit), "display", "none"); - if(way == 1){ - List.page = List.page + List.can_fit; - } else if(way == 10) { - List.page = (Math.floor((document.querySelector("#wrapper").children.length - 1)/ List.can_fit) * List.can_fit); + changedValues: function(song) { + if (song.type == "suggested") { + try { + document + .querySelector("#suggested-" + song.id) + .querySelector(".vote-container") + .setAttribute("title", song.title); + document + .querySelector("#suggested-" + song.id) + .querySelector(".list-title") + .setAttribute("title", song.title); + document + .querySelector("#suggested-" + song.id) + .querySelector(".list-title").innerText = song.title; + var _temp_duration = Helper.secondsToOther(song.duration); + document + .querySelector("#suggested-" + song.id) + .querySelector(".card-duration").innerText = + Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); + document + .querySelector("#suggested-" + song.id) + .querySelector(".list-image") + .setAttribute( + "style", + "background-image:url('//img.youtube.com/vi/" + + song.new_id + + "/mqdefault.jpg');" + ); + document + .querySelector("#suggested-" + song.id) + .setAttribute("id", song.new_id); + } catch (e) {} + return; + } + var i = List.getIndexOfSong(song.id); + if (i >= 0 && window.location.pathname != "/") { + full_playlist[i].title = song.title; + full_playlist[i].duration = song.duration; + full_playlist[i].start = song.start; + full_playlist[i].end = song.end; + full_playlist[i].id = song.new_id; + try { + document + .querySelector("#" + song.id) + .querySelector(".vote-container") + .setAttribute("title", song.title); + document + .querySelector("#" + song.id) + .querySelector(".list-title") + .setAttribute("title", song.title); + document + .querySelector("#" + song.id) + .querySelector(".list-title").innerText = song.title; + var _temp_duration = Helper.secondsToOther(song.duration); + document + .querySelector("#" + song.id) + .querySelector(".card-duration").innerText = + Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); + document + .querySelector("#" + song.id) + .querySelector(".list-image") + .setAttribute( + "style", + "background-image:url('//img.youtube.com/vi/" + + song.new_id + + "/mqdefault.jpg');" + ); + document.querySelector("#" + song.id).setAttribute("id", song.new_id); + } catch (e) {} + } + }, - } - Helper.css(wrapperChildren.slice(List.page, List.page + List.can_fit), "display", "inline-flex"); + insertAtBeginning: function(song_info, transition) { + if (document.querySelector("#wrapper") == null) return; + var display = List.page == 0 ? "" : "none"; + var add = List.generateSong( + song_info, + transition, + false, + true, + false, + display, + false + ); + document.querySelector("#wrapper").insertAdjacentHTML("beforeend", add); + }, - if(List.page > 0 && document.querySelector(".prev_page").style.display == "none"){ - Helper.css(".prev_page", "display", "inline-flex"); - Helper.css(".prev_page_hide", "display", "none"); - Helper.css(".first_page", "display", "inline-flex"); - Helper.css(".first_page_hide", "display", "none"); - } - if(List.page + List.can_fit >= document.querySelector("#wrapper").children.length){ - Helper.css(".next_page_hide", "display", "inline-flex"); - Helper.css(".next_page", "display", "none"); - Helper.css(".last_page_hide", "display", "inline-flex"); - Helper.css(".last_page", "display", "none"); - } + insertAtIndex: function(song_info, transition, change) { + if (document.querySelector("#wrapper") == null) return; + var i = List.getIndexOfSong(song_info.id); + if (i == -1) return; + if (!song_info.now_playing) { + var display = "none"; + if (i >= List.page && i < List.page + List.can_fit) + display = "inline-flex"; + var add = List.generateSong( + song_info, + transition, + false, + true, + false, + display, + false + ); + if (i === 0) { + document + .querySelector("#wrapper") + .insertAdjacentHTML("afterbegin", add); + } else { + document + .querySelector("#wrapper > div:nth-child(" + i + ")") + .insertAdjacentHTML("afterend", add); + } + var added = document.querySelector("#wrapper").children[i]; + Helper.css(added, "display", display); + if ( + display == "inline-flex" && + document.querySelector("#wrapper").children.length >= + List.page + List.can_fit + 1 + ) { + Helper.css( + document.querySelector("#wrapper").children[List.page + List.can_fit], + "display", + "none" + ); + } else if ( + i < List.page && + document.querySelector("#wrapper").children.length - (List.page + 1) >= + 0 + ) { + Helper.css( + document.querySelector("#wrapper").children[List.page], + "display", + "inline-flex" + ); + } else if ( + document.querySelector("#wrapper").children.length > + List.page + List.can_fit + ) { + Helper.css( + document.querySelector("#wrapper").children[ + List.page + List.can_fit - 1 + ], + "display", + "inline-flex" + ); + } + if (change && List.page > 0) { + Helper.css( + document.querySelector("#wrapper").children[List.page - 1], + "display", + "none" + ); + } + if (transition) { + setTimeout(function() { + Helper.css(added, "transform", "translateX(0%)"); + setTimeout(function() { + Helper.removeClass(added, "side_away"); + }, 300); + }, 5); + } + } + }, + + calculate_song_heights: function() { + if (!Helper.mobilecheck() && !embed && !client) { + List.can_fit = Math.round( + Helper.computedStyle("#wrapper", "height") / 71 + ); + List.element_height = + Helper.computedStyle("#wrapper", "height") / List.can_fit - 5.3; + } else if (embed) { + List.can_fit = + Math.round(Helper.computedStyle("#wrapper", "height") / 91) + 1; + List.element_height = + Helper.computedStyle("#wrapper", "height") / List.can_fit - 4; + } else if (!client) { + List.can_fit = + Math.round( + (Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + 71 + ) + 1; + List.element_height = + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + List.can_fit - + 5; + } else { + List.can_fit = + Math.round(Helper.computedStyle("#wrapper", "height") / 71) + 1; + List.element_height = + Helper.computedStyle("#wrapper", "height") / List.can_fit - 5.3; + } + if (List.element_height < 55.2 && !client && !embed) { + List.can_fit = List.can_fit - 1; + List.element_height = 55.2; + List.can_fit = Math.round( + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + 71 + ); + List.element_height = + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + List.can_fit - + 5; + } else if (List.element_height < 55.2 && embed) { + //List.can_fit = List.can_fit - 1; + List.can_fit = Math.round( + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + 71 + ); + List.element_height = + (window.innerHeight - + Helper.computedStyle(".tabs", "height") - + Helper.computedStyle("header", "height") - + 64 - + 40) / + List.can_fit - + 5; + List.can_fit = List.can_fit - 2; + } + }, + + populate_list: function(msg, no_reset) { + if (document.querySelector("#wrapper") == null) return; + // This math is fucked and I don't know how it works. Should be fixed sometime + if (list_html === undefined) list_html = Helper.html("#list-song-html"); + full_playlist = msg; + if (offline && !no_reset) { + for (var x = 0; x < full_playlist.length; x++) { + full_playlist[x].votes = 0; + } + } + List.sortList(); + + Helper.setHtml("#wrapper", ""); + + Helper.log(["FULL PLAYLIST", full_playlist]); + if (full_playlist.length > 1) { + for (var j = 0; j < full_playlist.length; j++) { + var _current_song = full_playlist[j]; + if (!_current_song.hasOwnProperty("start")) full_playlist[j].start = 0; + if (!_current_song.hasOwnProperty("end")) + full_playlist[j].end = full_playlist[j].duration; + if (!_current_song.now_playing && _current_song.type != "suggested") { + //check that the song isnt playing + var generated = List.generateSong( + _current_song, + false, + lazy_load, + true, + false, + "inline-flex", + true + ); + document + .querySelector("#wrapper") + .insertAdjacentHTML("beforeend", generated); + } + } + if ( + document.querySelector("#wrapper").children.length > List.can_fit && + !document.querySelectorAll("#pageButtons").length + ) { + Helper.css(".prev_page", "display", "none"); + Helper.css(".first_page", "display", "none"); + Helper.css(".next_page_hide", "display", "none"); + Helper.css(".last_page_hide", "display", "none"); + } else if (!document.querySelectorAll("#pageButtons").length) { + Helper.css(".prev_page", "display", "none"); + Helper.css(".next_page", "display", "none"); + Helper.css(".last_page", "display", "none"); + Helper.css(".first_page", "display", "none"); + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".prev_page_hide", "display", "inline-flex"); + } else { + Helper.css(".next_page", "display", "none"); + Helper.css(".last_page", "display", "none"); + } + + List.dynamicContentPage(-10); + } else { + List.empty = true; + Helper.setHtml( + "#wrapper", + "The playlist is empty." + ); + Helper.css(".prev_page", "display", "none"); + Helper.css(".next_page", "display", "none"); + Helper.css(".last_page", "display", "none"); + Helper.css(".last_page_hide", "display", "inline-flex"); + Helper.css(".first_page", "display", "none"); + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".prev_page_hide", "display", "inline-flex"); + } + Helper.css("#settings", "visibility", "visible"); + Helper.css("#settings", "opacity", "1"); + Helper.css("#wrapper", "opacity", "1"); + Helper.removeClass("#pageButtons", "hide"); + + if (!embed) { + Helper.log(["Starting empty-checker"]); + clearTimeout(timed_remove_check); + timed_remove_check = setTimeout(function() { + if (full_playlist.length > 0) { + List.check_error_videos(0); + } + }, 1500); + } + }, + + check_error_videos: function(i) { + //Helper.log("Empty-checker at " + i); + if (full_playlist.length == 0) return; + else if ( + full_playlist[i].source == "soundcloud" && + full_playlist.length > i + 1 && + window.location.pathname != "/" + ) + List.check_error_videos(i + 1); + else { + Helper.ajax({ + method: "get", + url: + "https://www.googleapis.com/youtube/v3/videos?id=" + + full_playlist[i].id + + "&key=" + + api_key.youtube + + "&part=snippet", + success: function(data) { + data = JSON.parse(data); + //Helper.log("Empty-checker items " + data.items.length); + if (data.items.length == 0) { + Helper.log([ + "Emtpy-checker error at " + + full_playlist[i].id + + " " + + full_playlist[i].title + ]); + socket.emit("error_video", { + channel: chan.toLowerCase(), + id: full_playlist[i].id, + title: full_playlist[i].title, + source: full_playlist[i].source + }); + } + if (full_playlist.length > i + 1 && window.location.pathname != "/") { + List.check_error_videos(i + 1); + } + } + }); + } + }, + + dynamicContentPageJumpTo: function(page) { + if (document.querySelector("#wrapper") == null) return; + page = page * List.can_fit; + var wrapperChildren = [].slice.call( + document.querySelector("#wrapper").children + ); + if (page > List.page || page < List.page) { + Helper.css( + wrapperChildren.slice(List.page, List.page + List.can_fit), + "display", + "none" + ); + List.page = page; + Helper.css( + wrapperChildren.slice(List.page, List.page + List.can_fit), + "display", + "inline-flex" + ); + if ( + List.page > 0 && + document.querySelector(".prev_page").style.display == "none" + ) { + Helper.css(".prev_page", "display", "inline-flex"); + Helper.css(".prev_page_hide", "display", "none"); + Helper.css(".first_page", "display", "inline-flex"); + Helper.css(".first_page_hide", "display", "none"); + } + + if (List.page + List.can_fit >= wrapperChildren.length) { + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".next_page", "display", "none"); + Helper.css(".last_page_hide", "display", "inline-flex"); + Helper.css(".last_page", "display", "none"); + } + + Helper.setHtml("#pageNumber", List.page / List.can_fit + 1); + } + }, + + dynamicContentPage: function(way) { + if (document.querySelector("#wrapper") == null) return; + var wrapperChildren = [].slice.call( + document.querySelector("#wrapper").children + ); + if (way == 1 || way == 10) { + Helper.css( + wrapperChildren.slice(List.page, List.page + List.can_fit), + "display", + "none" + ); + if (way == 1) { + List.page = List.page + List.can_fit; + } else if (way == 10) { + List.page = + Math.floor( + (document.querySelector("#wrapper").children.length - 1) / + List.can_fit + ) * List.can_fit; + } + Helper.css( + wrapperChildren.slice(List.page, List.page + List.can_fit), + "display", + "inline-flex" + ); + + if ( + List.page > 0 && + document.querySelector(".prev_page").style.display == "none" + ) { + Helper.css(".prev_page", "display", "inline-flex"); + Helper.css(".prev_page_hide", "display", "none"); + Helper.css(".first_page", "display", "inline-flex"); + Helper.css(".first_page_hide", "display", "none"); + } + if ( + List.page + List.can_fit >= + document.querySelector("#wrapper").children.length + ) { + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".next_page", "display", "none"); + Helper.css(".last_page_hide", "display", "inline-flex"); + Helper.css(".last_page", "display", "none"); + } + } else { + if (way == -10) { + Helper.css( + wrapperChildren.slice(List.page, List.page + List.can_fit), + "display", + "none" + ); + List.page = 0; + Helper.css( + wrapperChildren.slice(List.page, List.page + List.can_fit), + "display", + "inline-flex" + ); + } else { + Helper.css( + wrapperChildren.slice(List.page - List.can_fit, List.page), + "display", + "inline-flex" + ); + Helper.css( + wrapperChildren.slice(List.page, List.page + List.can_fit), + "display", + "none" + ); + List.page = List.page - List.can_fit < 0 ? 0 : List.page - List.can_fit; + } + if ( + List.page == 0 && + document.querySelector(".prev_page").style.display != "none" + ) { + Helper.css(".prev_page", "display", "none"); + Helper.css(".prev_page_hide", "display", "inline-flex"); + Helper.css(".first_page", "display", "none"); + Helper.css(".first_page_hide", "display", "inline-flex"); + } else if (document.querySelector(".prev_page").style.display == "none") { + Helper.css(".prev_page_hide", "display", "inline-flex"); + Helper.css(".first_page_hide", "display", "inline-flex"); + } else { + Helper.css(".prev_page_hide", "display", "none"); + Helper.css(".first_page_hide", "display", "none"); + } + if ( + List.page + List.can_fit < + document.querySelector("#wrapper").children.length + ) { + Helper.css(".next_page_hide", "display", "none"); + Helper.css(".next_page", "display", "inline-flex"); + Helper.css(".last_page_hide", "display", "none"); + Helper.css(".last_page", "display", "inline-flex"); + } + } + document.querySelector("#pageNumber").innerText = + List.page / List.can_fit + 1; + }, + + added_song: function(added) { + var now_playing; + if (added != undefined) { + if (full_playlist.length !== 0) { + now_playing = full_playlist.pop(); + } + full_playlist.push(added); + List.sortList(); + if (now_playing) { + full_playlist.push(now_playing); + } + + if (hostMode) { + M.toast({ + html: + "

New song added

" + + added.title + + "

", + displayLength: 10000 + }); + document + .querySelector("#toast-container") + .setAttribute("style", "z-index: 99999999999 !important"); + } + if ( + added.source != "soundcloud" && + document.querySelectorAll("#suggested-" + added.id).length > 0 + ) { + number_suggested = number_suggested - 1; + if (number_suggested < 0) number_suggested = 0; + + var to_display = number_suggested > 9 ? "9+" : number_suggested; + if (to_display == 0) { + Helper.addClass( + document.querySelector(".suggested-link span.badge.new.white"), + "hide" + ); + } + + document.querySelector( + ".suggested-link span.badge.new.white" + ).innerText = to_display; + Helper.removeElement("#suggested-" + added.id); + } + + if (List.empty) { + List.empty = false; + } + if (document.querySelectorAll("#empty-channel-message").length > 0) { + document.querySelector("#empty-channel-message").remove(); + } + if (intelligentList) { + intelligentQueue.push({ + type: "add", + element: added + }); + if (Helper.mobilecheck()) { + say_updated(); + } + } else { + List.insertAtIndex(added, true); + Helper.css( + document.querySelector("#wrapper").children[List.page + List.can_fit], + "display", + "none" + ); + if ( + document.querySelector("#wrapper").children.length > + List.page + List.can_fit + ) { + Helper.css(".next_page_hide", "display", "none"); + Helper.removeClass(".next_page", "hide"); + Helper.css(".last_page_hide", "display", "none"); + Helper.css(".next_page", "display", "inline-flex"); + Helper.css(".last_page", "display", "inline-flex"); } else { - if(way==-10) { - Helper.css(wrapperChildren.slice(List.page, List.page + List.can_fit), "display", "none"); - List.page = 0; - Helper.css(wrapperChildren.slice(List.page, List.page + List.can_fit), "display", "inline-flex"); - } else { - Helper.css(wrapperChildren.slice(List.page - List.can_fit, List.page), "display", "inline-flex"); - Helper.css(wrapperChildren.slice(List.page, List.page + List.can_fit), "display", "none"); - List.page = List.page - List.can_fit < 0 ? 0 : List.page - List.can_fit; - } - if(List.page == 0 && document.querySelector(".prev_page").style.display != "none"){ - Helper.css(".prev_page", "display", "none"); - Helper.css(".prev_page_hide", "display", "inline-flex"); - Helper.css(".first_page", "display", "none"); - Helper.css(".first_page_hide", "display", "inline-flex"); - } else if(document.querySelector(".prev_page").style.display == "none"){ - Helper.css(".prev_page_hide", "display", "inline-flex"); - Helper.css(".first_page_hide", "display", "inline-flex"); - } else { - Helper.css(".prev_page_hide", "display", "none"); - Helper.css(".first_page_hide", "display", "none"); - } - if(List.page + List.can_fit < document.querySelector("#wrapper").children.length){ - Helper.css(".next_page_hide", "display", "none"); - Helper.css(".next_page", "display", "inline-flex"); - Helper.css(".last_page_hide", "display", "none"); - Helper.css(".last_page", "display", "inline-flex"); - } + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".next_page", "display", "none"); } - document.querySelector("#pageNumber").innerText = (List.page / List.can_fit) + 1; - }, + } + } + }, - added_song: function(added) { - var now_playing; - if(added != undefined){ - if(full_playlist.length !== 0){ - now_playing = full_playlist.pop(); - } - full_playlist.push(added); - List.sortList(); - if(now_playing){ - full_playlist.push(now_playing); - } - - if(hostMode) { - M.toast({html: "

New song added

" + added.title + "

", displayLength: 10000}); - document.querySelector("#toast-container").setAttribute("style", "z-index: 99999999999 !important"); - } - if(added.source != "soundcloud" && document.querySelectorAll("#suggested-"+added.id).length > 0) { - number_suggested = number_suggested - 1; - if(number_suggested < 0) number_suggested = 0; - - var to_display = number_suggested > 9 ? "9+" : number_suggested; - if(to_display == 0){ - Helper.addClass(document.querySelector(".suggested-link span.badge.new.white"), "hide"); - } - - document.querySelector(".suggested-link span.badge.new.white").innerText = to_display; - Helper.removeElement("#suggested-"+added.id); - } - - if(List.empty){ - List.empty = false; - } - if(document.querySelectorAll("#empty-channel-message").length > 0) { - document.querySelector("#empty-channel-message").remove(); - } - if(intelligentList) { - intelligentQueue.push({ - type: "add", - element: added, - }); - if(Helper.mobilecheck()) { - say_updated(); - } - } else { - List.insertAtIndex(added, true); - Helper.css(document.querySelector("#wrapper").children[List.page + List.can_fit], "display", "none"); - if(document.querySelector("#wrapper").children.length > List.page + List.can_fit){ - Helper.css(".next_page_hide", "display", "none"); - Helper.removeClass(".next_page", "hide"); - Helper.css(".last_page_hide", "display", "none"); - Helper.css(".next_page", "display", "inline-flex"); - Helper.css(".last_page", "display", "inline-flex"); - } else { - Helper.css(".next_page_hide", "display", "inline-flex"); - Helper.css(".next_page", "display", "none"); - } - } + deleted_song: function(deleted, removed, intelligentSecond, deleted_index) { + try { + var index = List.getIndexOfSong(deleted); + if (intelligentList && !intelligentSecond) { + intelligentQueue.push({ + type: "delete", + element: full_playlist[index], + index: index + }); + if (Helper.mobilecheck()) { + say_updated(); + } + if (index != -1) full_playlist.splice(index, 1); + var this_element = document.getElementById(deleted); + Helper.addClass(this_element, "disabled-vote"); + this_element.querySelector(".vote-span").innerText = "Deleted"; + Helper.addClass( + this_element.querySelector(".vote-container"), + "deleted-vote-container" + ); + Helper.removeClass( + this_element.querySelector(".vote-container"), + "clickable" + ); + Helper.removeClass( + this_element.querySelector(".vote-container"), + "vote-container" + ); + return; + } else { + //if(!removed) to_delete.style.height = 0; + var nextToChange; + if (index == -1) index = deleted_index; + if ( + index < List.page && + document.querySelector("#wrapper").children.length - + (List.page + 2) >= + 0 + ) { + //Helper.css(document.querySelector("#wrapper").children[List.page], "height", 0 + "px"); + nextToChange = document.querySelector("#wrapper").children[List.page]; + //Helper.css(document.querySelector("#wrapper").children[List.page], "display", "inline-flex"); + //Helper.css(document.querySelector("#wrapper").children[List.page], "height", List.element_height + "px"); + } else if ( + document.querySelector("#wrapper").children.length > + List.page + List.can_fit + ) { + //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit)], "height", 0 + "px"); + nextToChange = document.querySelector("#wrapper").children[ + List.page + List.can_fit + ]; + //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit)], "display", "inline-flex"); + //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit)], "height", List.element_height + "px"); + } + if ( + List.page >= + document.querySelector("#wrapper").children.length - 1 + ) { + List.dynamicContentPage(-1); + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".next_page", "display", "none"); + Helper.css(".last_page_hide", "display", "inline-flex"); + Helper.css(".last_page", "display", "none"); + } else if ( + List.page + List.can_fit + 1 >= + document.querySelector("#wrapper").children.length - 1 + ) { + Helper.css(".next_page_hide", "display", "inline-flex"); + Helper.css(".next_page", "display", "none"); + Helper.css(".last_page_hide", "display", "inline-flex"); + Helper.css(".last_page", "display", "none"); } - }, - deleted_song: function(deleted, removed, intelligentSecond, deleted_index) { - try{ - var index = List.getIndexOfSong(deleted); - if(intelligentList && !intelligentSecond) { - intelligentQueue.push({ - type: "delete", - element: full_playlist[index], - index: index, - }); - if(Helper.mobilecheck()) { - say_updated(); - } - if(index != -1) full_playlist.splice(index, 1); - var this_element = document.getElementById(deleted); - Helper.addClass(this_element, "disabled-vote"); - this_element.querySelector(".vote-span").innerText = "Deleted"; - Helper.addClass(this_element.querySelector(".vote-container"), "deleted-vote-container"); - Helper.removeClass(this_element.querySelector(".vote-container"), "clickable"); - Helper.removeClass(this_element.querySelector(".vote-container"), "vote-container"); - return; - } else { - //if(!removed) to_delete.style.height = 0; - var nextToChange; - if(index == -1) index = deleted_index; - if(index < List.page && document.querySelector("#wrapper").children.length - (List.page + 2) >= 0){ - //Helper.css(document.querySelector("#wrapper").children[List.page], "height", 0 + "px"); - nextToChange = document.querySelector("#wrapper").children[List.page]; - //Helper.css(document.querySelector("#wrapper").children[List.page], "display", "inline-flex"); - //Helper.css(document.querySelector("#wrapper").children[List.page], "height", List.element_height + "px"); - } else if(document.querySelector("#wrapper").children.length > List.page + (List.can_fit)){ - //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit)], "height", 0 + "px"); - nextToChange = document.querySelector("#wrapper").children[List.page + (List.can_fit)]; - //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit)], "display", "inline-flex"); - //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit)], "height", List.element_height + "px"); - } - if(List.page >= document.querySelector("#wrapper").children.length - 1){ - List.dynamicContentPage(-1); - Helper.css(".next_page_hide", "display", "inline-flex"); - Helper.css(".next_page", "display", "none"); - Helper.css(".last_page_hide", "display", "inline-flex"); - Helper.css(".last_page", "display", "none"); - } else if(List.page + List.can_fit + 1 >= document.querySelector("#wrapper").children.length - 1){ - Helper.css(".next_page_hide", "display", "inline-flex"); - Helper.css(".next_page", "display", "none"); - Helper.css(".last_page_hide", "display", "inline-flex"); - Helper.css(".last_page", "display", "none"); - } + if (List.page <= index && List.page - List.can_fit <= index) { + Helper.addClass("#" + deleted, "side_away"); - if(List.page <= index && List.page - List.can_fit <= index) { - Helper.addClass("#" + deleted, "side_away"); - - //document.getElementById(deleted).querySelector(".mobile-delete").remove(); - Helper.css("#" + deleted, "transform", "translateX(-100%)"); - setTimeout(function() { - Helper.removeElement("#" + deleted); - /*var wrapperChildren = [].slice.call(document.querySelector("#wrapper").children); + //document.getElementById(deleted).querySelector(".mobile-delete").remove(); + Helper.css("#" + deleted, "transform", "translateX(-100%)"); + setTimeout(function() { + Helper.removeElement("#" + deleted); + /*var wrapperChildren = [].slice.call(document.querySelector("#wrapper").children); if(wrapperChildren.length > List.can_fit) { Helper.css(wrapperChildren[List.can_fit], "display", "inline-flex"); }*/ - if(nextToChange != undefined) { - Helper.css(nextToChange, "display", "inline-flex"); - Helper.css(nextToChange, "height", List.element_height + "px"); - } - }, 300); - } else { - Helper.removeElement("#"+deleted); - if(nextToChange != undefined) { - Helper.css(nextToChange, "display", "inline-flex"); - Helper.css(nextToChange, "height", List.element_height + "px"); - } - } - var index = List.getIndexOfSong(deleted); - if(index != -1) full_playlist.splice(index, 1); - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - //} + if (nextToChange != undefined) { + Helper.css(nextToChange, "display", "inline-flex"); + Helper.css(nextToChange, "height", List.element_height + "px"); } + }, 300); + } else { + Helper.removeElement("#" + deleted); + if (nextToChange != undefined) { + Helper.css(nextToChange, "display", "inline-flex"); + Helper.css(nextToChange, "height", List.element_height + "px"); + } + } + var index = List.getIndexOfSong(deleted); + if (index != -1) full_playlist.splice(index, 1); + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + //} + } + } catch (err) { + var index = List.getIndexOfSong(deleted); + if (index != -1) full_playlist.splice(index, 1); + if (!List.empty) { + try { + document.getElementById(deleted).remove(); + } catch (e) {} + if ( + index < List.page && + document.querySelector("#wrapper").children.length - + (List.page + 1) >= + 0 + ) { + //Helper.css(document.querySelector("#wrapper").children[List.page - 1], "display", "inline-flex"); + } else if ( + document.querySelector("#wrapper").children.length > + List.page + List.can_fit + ) { + //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit - 1)], "display", "inline-flex"); + } + if (nextToChange != undefined) { + Helper.css(nextToChange, "display", "inline-flex"); + Helper.css(nextToChange, "height", List.element_height + "px"); + } + Player.sendNext({ + title: full_playlist[0].title, + videoId: full_playlist[0].id, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + } + } + if (full_playlist.length < 2) { + List.empty = true; + Helper.setHtml( + "#wrapper", + "The playlist is empty." + ); + } + Helper.removeElement("#suggested-" + deleted); + if ( + List.page + List.can_fit < + document.querySelector("#wrapper").children.length + 1 + ) { + //$(".next_page_hide").css("display", "none"); + //$(".next_page").css("display", "flex"); + } + if (List.page >= document.querySelector("#wrapper").children.length) { + List.dynamicContentPage(-1); + } + Suggestions.checkUserEmpty(); + }, - } catch(err) { - var index = List.getIndexOfSong(deleted); - if(index != -1) full_playlist.splice(index, 1); - if(!List.empty){ - try { - document.getElementById(deleted).remove(); - }catch(e){} - if(index < List.page && document.querySelector("#wrapper").children.length - (List.page + 1) >= 0){ - //Helper.css(document.querySelector("#wrapper").children[List.page - 1], "display", "inline-flex"); - } else if(document.querySelector("#wrapper").children.length > List.page + List.can_fit){ - //Helper.css(document.querySelector("#wrapper").children[List.page + (List.can_fit - 1)], "display", "inline-flex"); - } - if(nextToChange != undefined) { - Helper.css(nextToChange, "display", "inline-flex"); - Helper.css(nextToChange, "height", List.element_height + "px"); - } - Player.sendNext({title: full_playlist[0].title, videoId: full_playlist[0].id, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); + voted_song: function(voted, time) { + var index_of_song = List.getIndexOfSong(voted); + if (index_of_song == -1) return; + var song_voted_on = full_playlist[index_of_song]; + + full_playlist[index_of_song].votes += 1; + full_playlist[index_of_song].added = time; + + if (intelligentList) { + document.getElementById(voted).querySelector(".list-votes").innerText = + full_playlist[index_of_song].votes; + intelligentQueue.push({ + type: "vote", + element: song_voted_on + }); + List.sortList(); + if (Helper.mobilecheck()) { + say_updated(); + } + } else { + List.sortList(); + Helper.removeElement("#" + voted); + List.insertAtIndex(song_voted_on, false); + } + }, + + song_change_prev: function(time) { + full_playlist[full_playlist.length - 1].now_playing = false; + full_playlist[full_playlist.length - 1].votes = full_playlist[0].votes; + full_playlist[full_playlist.length - 1].guids = []; + full_playlist[full_playlist.length - 1].added = full_playlist[0].added - 1; + + full_playlist.unshift(full_playlist.pop()); + + full_playlist[full_playlist.length - 1].now_playing = true; + + if (full_playlist.length == 1) return; + document + .querySelector("#wrapper") + .children[ + document.querySelector("#wrapper").children.length - 1 + ].remove(); + + var length = full_playlist.length - 2; + if (length < 0) { + length = 0; + } + + List.insertAtIndex(full_playlist[0], false, true); + }, + + song_change: function(time, remove, id) { + try { + var length = full_playlist.length - 1; + if (full_playlist.length <= 1) { + List.empty = true; + Helper.setHtml( + "#wrapper", + "The playlist is empty." + ); + } + if (id != full_playlist[0].id) { + return; + } + var newLast = full_playlist[0]; + full_playlist[0].now_playing = true; + full_playlist[0].votes = 0; + full_playlist[0].guids = []; + full_playlist[0].added = time; + var i = intelligentQueue.length; + + while (i--) { + var current = intelligentQueue[i]; + if (current.type == "delete") { + intelligentQueue.splice(i, 1); + Helper.removeElement("#" + current.element.id); + deleted_elements += 1; + } + } + try { + document.getElementById(full_playlist[0].id).remove(); + } catch (e) {} + if (!remove) { + full_playlist[length].now_playing = false; + } else { + delete full_playlist[length]; + } + Helper.log(["SONG ON FIRST INDEX", full_playlist[0]]); + + full_playlist.push(full_playlist.shift()); + if (!remove) { + if (full_playlist.length >= 2) { + var index = full_playlist.length - 2; + List.insertAtIndex(full_playlist[index], false, true); + } + } + var wrapperChildren = [].slice.call( + document.querySelector("#wrapper").children + ); + if (wrapperChildren.length >= List.can_fit && deleted_elements > 0) { + for (var i = 0; i < deleted_elements + 1; i++) { + //Helper.css(wrapperChildren[List.can_fit - 2], "display", "inline-flex"); + Helper.css( + wrapperChildren[List.page + List.can_fit - 1 - i], + "display", + "inline-flex" + ); + } + } + deleted_elements = 0; + } catch (e) {} + }, + + vote: function(id, vote) { + Helper.log([ + "Voting on video", + "client " + client, + "socket_connected " + socket_connected + ]); + if ((client || Helper.mobilecheck()) && !socket_connected) { + if (vote != "del") { + vote_ajax(id); + } else { + del_ajax(id); + } + return; + } + + if ( + !offline || + (vote == "del" && (hasadmin && (!w_p && adminpass != ""))) + ) { + /*var u = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); + if(u == undefined) u = "";*/ + emit("vote", { channel: chan, id: id, type: vote }); + } else { + if (vote == "pos") { + List.voted_song(id, new Date().getTime() / 1000); + } else { + List.deleted_song(id); + } + } + return true; + }, + + skip: function(way) { + if (!offline) { + /*var u = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); + if(u == undefined) u = "";*/ + emit("skip", { id: video_id, channel: chan.toLowerCase() }); + } else { + if (way) { + Player.playNext(); + } else { + Player.playPrev(); + } + } + return true; + }, + + exportToSoundCloud: function(thisSong, i) { + if (i >= full_playlist.length) { + if (List.found.length == 0) { + for (var x = 0; x < List.not_found.length; x++) { + var data = List.not_found[x]; + var not_added_song = document.createElement("div"); + not_added_song.innerHTML = not_export_html; + not_added_song + .querySelector(".extra-add-text") + .setAttribute("value", data); + not_added_song + .querySelector(".extra-add-text") + .setAttribute("title", data); + document + .querySelector(".not-exported-container") + .insertAdjacentHTML("beforeend", not_added_song.innerHTML); + } + Helper.removeClass(".not-exported", "hide"); + Helper.addClass(".current_number", "hide"); + Helper.addClass("#playlist_loader_export", "hide"); + Helper.addClass(".exported-list-container", "hide"); + List.found = []; + List.not_found = []; + } else { + SC_player.post("/playlists", { + playlist: { + title: chan.toLowerCase() + " - Zoff", + tracks: List.found, + description: + "Playlist exported from https://zoff.me/" + + Helper.encodeChannelName(chan.toLowerCase()) + } + }) + .then(function(result) { + for (var x = 0; x < List.not_found.length; x++) { + var data = List.not_found[x]; + var not_added_song = document.createElement("div"); + not_added_song.innerHTML = not_export_html; + not_added_song + .querySelector(".extra-add-text") + .setAttribute("value", data); + not_added_song + .querySelector(".extra-add-text") + .setAttribute("title", data); + document + .querySelector(".not-exported-container") + .insertAdjacentHTML("beforeend", not_added_song.innerHTML); } - } - if(full_playlist.length < 2){ - List.empty = true; - Helper.setHtml("#wrapper", "The playlist is empty."); - } - Helper.removeElement("#suggested-"+deleted); - if(List.page + List.can_fit < document.querySelector("#wrapper").children.length + 1){ - //$(".next_page_hide").css("display", "none"); - //$(".next_page").css("display", "flex"); - } - if(List.page >= document.querySelector("#wrapper").children.length){ - List.dynamicContentPage(-1); - } - Suggestions.checkUserEmpty(); - }, + Helper.addClass(".current_number", "hide"); + Helper.addClass("#playlist_loader_export", "hide"); + Helper.addClass(".exported-list-container", "hide"); + document + .querySelector(".exported-list") + .insertAdjacentHTML( + "beforeend", + "" + + result.title + + "" + ); + Helper.removeClass(".not-exported", "hide"); + toast("List exported!"); + List.found = []; + List.not_found = []; + }) + .catch(function(error) { + console.log(error); + }); + } + } else if (thisSong == undefined) { + ga("send", "event", "export", "soundcloud"); + if (full_playlist.length > 0) { + List.exportToSoundCloud(full_playlist[0], 0); + } + } else if (thisSong != undefined && i != undefined) { + var isFound = false; + Helper.removeClass(".current_number", "hide"); + document.querySelector(".current_number").innerText = + i + " of " + full_playlist.length; + if (thisSong.source == "soundcloud") { + List.found.push({ id: parseInt(thisSong.id) }); + List.exportToSoundCloud(full_playlist[i + 1], i + 1); + } else { + var _title = thisSong.title; + _title = Helper.replaceForFind(_title); + SC_player.get("/tracks", { + q: _title + }) + .then(function(tracks) { + //$("#results").append(result_html); + //Helper.css(document.querySelector(".search_results .col.s12"), "display", "block"); + for (var y = 0; y < tracks.length; y++) { + var song = tracks[y]; + if (!song.streamable) continue; + var duration = Math.floor(song.duration / 1000); + //var secs=Search.durationToSeconds(duration); + var secs = duration; + if (longsongs == undefined) longsongs = true; + if ((longsongs != undefined && !longsongs) || secs < 720) { + var title = song.title; + if (title.indexOf(song.user.username) == -1) { + title = song.user.username + " - " + title; + } + title = title.toLowerCase(); + var id = song.id; + if (similarity(title, _title) > 0.6) { + List.found.push({ id: parseInt(song.id) }); + isFound = true; + break; + } + } + } + if (!isFound) { + List.not_found.push(full_playlist[i].title); + } + List.exportToSoundCloud(full_playlist[i + 1], i + 1); + }) + .catch(function(e) { + List.not_found.push(full_playlist[i].title); + List.exportToSoundCloud(full_playlist[i + 1], i + 1); + }); + } + } + }, - voted_song: function(voted, time) { - var index_of_song = List.getIndexOfSong(voted); - if(index_of_song == -1) return; - var song_voted_on = full_playlist[index_of_song]; + exportToSpotify: function() { + ga("send", "event", "export", "spotify"); - full_playlist[index_of_song].votes += 1; - full_playlist[index_of_song].added = time; - - if(intelligentList) { - document.getElementById(voted).querySelector(".list-votes").innerText = full_playlist[index_of_song].votes; - intelligentQueue.push({ - type: "vote", - element: song_voted_on + Helper.ajax({ + type: "GET", + url: "https://api.spotify.com/v1/me", + headers: { + Authorization: "Bearer " + access_token_data.access_token + }, + success: function(response) { + response = JSON.parse(response); + var user_id = response.id; + Helper.removeClass("#playlist_loader_export", "hide"); + Helper.removeClass(".exported-list-container", "hide"); + Helper.ajax({ + type: "POST", + url: "https://api.spotify.com/v1/users/" + user_id + "/playlists", + headers: { + Authorization: "Bearer " + access_token_data.access_token, + "Content-Type": "application/json" + }, + data: JSON.stringify({ + name: chan.toLowerCase() + " - Zoff", + description: + "Playlist exported from Zoff (https://zoff.me/" + + chan.toLowerCase() + + "/)", + public: true + }), + success: function(response) { + response = JSON.parse(response); + var playlist_id = response.id; + Helper.ajax({ + type: "GET", + url: + window.location.protocol + + "//" + + window.location.hostname + + "/assets/images/small-square.base64.txt", + success: function(base64image) { + var image = base64image.substring(0, base64image.length - 1); + Helper.ajax({ + type: "PUT", + url: + "https://api.spotify.com/v1/users/" + + user_id + + "/playlists/" + + playlist_id + + "/images", + headers: { + Authorization: "Bearer " + access_token_data.access_token, + "Content-Type": "image/jpeg" + }, + contentType: "image/jpeg", + data: image, + success: function(resp) {}, + error: function(error) { + console.error(error); + } + }); + } }); - List.sortList(); - if(Helper.mobilecheck()) { - say_updated(); + var i = 0; + List.searchSpotify( + full_playlist[i], + playlist_id, + user_id, + full_playlist, + i + ); + //}); + }, + error: function(e) {} + }); + }, + error: function(e) { + console.error(e); + } + }); + }, + + searchSpotify: function( + curr_song, + playlist_id, + user_id, + full_playlist, + current_element + ) { + var original_track = curr_song.title; + var track = curr_song.title.toLowerCase().replace("-", " "); + track = Helper.replaceForFind(track); + track = encodeURIComponent(track); + + Helper.removeClass(".current_number", "hide"); + document.querySelector(".current_number").innerText = + current_element + 1 + " of " + full_playlist.length; + Helper.ajax({ + type: "GET", + url: "https://api.spotify.com/v1/search?q=" + track + "&type=track", + headers: { + Authorization: "Bearer " + access_token_data.access_token + }, + async: true, + error: function(err) { + if (err.status == 429 || err.status == 502) { + Helper.log([err.getAllResponseHeaders()]); + var retryAfter = err.getResponseHeader("Retry-After"); + Helper.log([retryAfter]); + if (!retryAfter) retryAfter = 5; + retryAfter = parseInt(retryAfter, 10); + Helper.log(["Retry-After", retryAfter]); + setTimeout(function() { + List.searchSpotify( + curr_song, + playlist_id, + user_id, + full_playlist, + current_element + ); + }, retryAfter * 1000); + } + }, + success: function(response) { + response = JSON.parse(response); + var found = false; + for (var i = 0; i < response.tracks.items.length; i++) { + var data = response.tracks.items[i]; + data.name = Helper.replaceForFind(data.name); + data.artists[0].name = Helper.replaceForFind(data.artists[0].name); + if (data.name.substring(data.name.length - 1) == " ") + data.name = data.name.substring(0, data.name.length - 1); + if ( + data.name.substring(data.name.length - 1) == "." && + track.substring(track.length - 1) != "." + ) { + data.name = data.name.substring(0, data.name.length - 1); + } + if ( + similarity( + data.artists[0].name + " - " + data.name, + decodeURIComponent(track) + ) > 0.6 || + (data.artists.length > 1 && + similarity( + data.artists[0].name + + " " + + data.artists[1].name + + " - " + + data.name, + decodeURIComponent(track) + )) + ) { + found = true; + List.uris.push(data.uri); + Helper.log(["Found", track]); + //List.num_songs = List.num_songs + 1; + break; + } else if ( + decodeURIComponent(track).indexOf( + data.artists[0].name.toLowerCase() + ) >= 0 && + decodeURIComponent(track).indexOf(data.name.toLowerCase()) >= 0 + ) { + found = true; + List.uris.push(data.uri); + Helper.log(["Found", track]); + //List.num_songs = List.num_songs + 1; + break; + } else { + var splitted = data.name.split(" "); + var toBreak = false; + for (var i = 0; i < splitted.length; i++) { + if ( + (splitted[i] == "and" && track.indexOf("&") >= 0) || + (splitted[i] == "&" && track.indexOf("and") >= 0) + ) { + continue; + } else if (track.indexOf(splitted[i]) < 0) { + toBreak = true; + break; + } } + if (toBreak) break; + found = true; + List.uris.push(data.uri); + Helper.log(["Found", track]); + //List.num_songs = List.num_songs + 1; + break; + } + } + if (!found) { + List.not_found.push(original_track); + List.num_songs = List.num_songs + 1; + Helper.log(["Didn't find", original_track]); + } + if (List.num_songs + List.uris.length == full_playlist.length) { + if (List.uris.length > 100) { + while (List.uris.length > 100) { + List.addToSpotifyPlaylist( + List.uris.slice(0, 100), + playlist_id, + user_id + ); + List.uris = List.uris.slice(100, List.uris.length); + } + List.addToSpotifyPlaylist(List.uris, playlist_id, user_id); + Helper.addClass("#playlist_loader_export", "hide"); + } else { + List.addToSpotifyPlaylist(List.uris, playlist_id, user_id); + Helper.addClass("#playlist_loader_export", "hide"); + } + if (document.querySelectorAll(".exported-spotify-list").length == 0) { + document + .querySelector(".exported-list") + .insertAdjacentHTML( + "beforeend", + "" + + chan + + "" + ); + } + for (var i = 0; i < List.not_found.length; i++) { + var data = List.not_found[i]; + var not_added_song = document.createElement("div"); + not_added_song.innerHTML = not_export_html; + not_added_song + .querySelector(".extra-add-text") + .setAttribute("value", data); + not_added_song + .querySelector(".extra-add-text") + .setAttribute("title", data); + document + .querySelector(".not-exported-container") + .insertAdjacentHTML("beforeend", not_added_song.innerHTML); + } + Helper.addClass(".current_number", "hide"); + Helper.removeClass(".not-exported", "hide"); + Helper.css(".spotify_export_button", "display", "block"); } else { - List.sortList(); - Helper.removeElement("#"+voted); - List.insertAtIndex(song_voted_on, false); + List.searchSpotify( + full_playlist[current_element + 1], + playlist_id, + user_id, + full_playlist, + current_element + 1 + ); } - }, + } + }); + }, - song_change_prev: function(time) { - full_playlist[full_playlist.length - 1].now_playing = false; - full_playlist[full_playlist.length - 1].votes = full_playlist[0].votes; - full_playlist[full_playlist.length - 1].guids = []; - full_playlist[full_playlist.length - 1].added = full_playlist[0].added - 1; + addToSpotifyPlaylist: function(uris, playlist_id, user_id) { + Helper.ajax({ + type: "POST", + url: + "https://api.spotify.com/v1/users/" + + user_id + + "/playlists/" + + playlist_id + + "/tracks", + headers: { + Authorization: "Bearer " + access_token_data.access_token, + "Content-Type": "application/json" + }, + data: JSON.stringify({ + uris: uris + }), + error: function(response) { + var temp_playlist_id = playlist_id; + var temp_uris = uris; + var temp_user_id = user_id; + setTimeout(function() { + List.addToSpotifyPlaylist(temp_uris, temp_playlist_id, temp_user_id); + }, 3000); + }, + success: function(response) { + Helper.log(["Added songs"]); + } + }); + }, - full_playlist.unshift(full_playlist.pop()); + exportToYoutube: function() { + ga("send", "event", "export", "youtube"); - full_playlist[full_playlist.length - 1].now_playing = true; - - if(full_playlist.length == 1) return; - document.querySelector("#wrapper").children[document.querySelector("#wrapper").children.length - 1].remove(); - - var length = full_playlist.length - 2; - if(length < 0) { - length = 0; + var request_url = + "https://www.googleapis.com/youtube/v3/playlists?part=snippet&key=" + + api_key.youtube; + Helper.removeClass(".exported-list-container", "hide"); + Helper.removeClass("#playlist_loader_export", "hide"); + Helper.ajax({ + type: "POST", + url: request_url, + headers: { + Authorization: "Bearer " + access_token_data_youtube.access_token, + "Content-Type": "application/json" + }, + data: JSON.stringify({ + snippet: { + title: Helper.upperFirst(chan.toLowerCase()), + description: "Playlist exported from zoff" } + }), + success: function(response) { + response = JSON.parse(response); + var number_added = 0; + var playlist_id = response.id; + var request_url = + "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&key=" + + api_key.youtube; + List.addToYoutubePlaylist( + playlist_id, + full_playlist, + number_added, + request_url + ); + }, + error: function(response) { + console.error(response); + toast( + "Couldn't export to YouTube for some reason.. Try again later", + "red lighten" + ); + Helper.addClass(".exported-list-container", "hide"); + Helper.addClass("#playlist_loader_export", "hide"); + Helper.removeClass(".youtube_export_button", "hide"); + response = response.responseText; + Helper.log(["export to youtube response", response]); + } + }); + }, - List.insertAtIndex(full_playlist[0], false, true); - }, - - song_change: function(time, remove, id) { - try{ - var length = full_playlist.length - 1; - if(full_playlist.length <= 1) { - List.empty = true; - Helper.setHtml("#wrapper", "The playlist is empty."); - } - if(id != full_playlist[0].id) { - return; - } - var newLast = full_playlist[0]; - full_playlist[0].now_playing = true; - full_playlist[0].votes = 0; - full_playlist[0].guids = []; - full_playlist[0].added = time; - var i = intelligentQueue.length - - while (i--) { - var current = intelligentQueue[i]; - if (current.type == "delete") { - intelligentQueue.splice(i, 1); - Helper.removeElement("#" + current.element.id); - deleted_elements += 1; - } - } - try { - document.getElementById(full_playlist[0].id).remove(); - } catch(e) {}; - if(!remove){ - full_playlist[length].now_playing = false; - } else { - delete full_playlist[length]; - } - Helper.log([ - "SONG ON FIRST INDEX", - full_playlist[0] - ]); - - full_playlist.push(full_playlist.shift()); - if(!remove){ - if(full_playlist.length >= 2) { - var index = full_playlist.length - 2; - List.insertAtIndex(full_playlist[index], false, true); - } - } - var wrapperChildren = [].slice.call(document.querySelector("#wrapper").children); - if(wrapperChildren.length >= List.can_fit && deleted_elements > 0) { - for(var i = 0; i < deleted_elements + 1; i++) { - //Helper.css(wrapperChildren[List.can_fit - 2], "display", "inline-flex"); - Helper.css(wrapperChildren[List.page + List.can_fit - 1 - i], "display", "inline-flex"); - } - } - deleted_elements = 0; - } catch(e) { + insertInYouTubePlaylist: function(playlist_id, _videoId, num, request_url) { + var _data = JSON.stringify({ + snippet: { + playlistId: playlist_id, + resourceId: { + kind: "youtube#video", + videoId: _videoId } - }, - - vote: function(id, vote) { + } + }); + Helper.ajax({ + type: "POST", + url: request_url, + headers: { + Authorization: "Bearer " + access_token_data_youtube.access_token, + "Content-Type": "application/json" + }, + data: _data, + success: function(response) { + response = JSON.parse(response); Helper.log([ - "Voting on video", - "client " + client, - "socket_connected " + socket_connected + "Added video: " + + full_playlist[num].id + + " to playlist id " + + playlist_id ]); - if((client || Helper.mobilecheck()) && !socket_connected) { - if(vote != "del") { - vote_ajax(id); - } else { - del_ajax(id); - } - return; - } - - if(!offline || (vote == "del" && (hasadmin && (!w_p && adminpass != "")))){ - /*var u = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); - if(u == undefined) u = "";*/ - emit('vote', {channel: chan, id: id, type: vote}); + if (num == full_playlist.length - 1) { + Helper.log(["All videoes added!"]); + Helper.log([ + "url: https://www.youtube.com/playlist?list=" + playlist_id + ]); + document + .querySelector(".exported-list") + .insertAdjacentHTML( + "beforeend", + "" + + chan + + "" + ); + Helper.addClass("#playlist_loader_export", "hide"); + Helper.addClass(".current_number", "hide"); + //$(".youtube_export_button").removeClass("hide"); } else { - if(vote == "pos"){ - List.voted_song(id, (new Date()).getTime()/1000); - } else { - List.deleted_song(id); - } + //setTimeout(function(){ + Helper.removeClass(".current_number", "hide"); + document.querySelector(".current_number").innerText = + num + 1 + " of " + full_playlist.length; + List.addToYoutubePlaylist( + playlist_id, + full_playlist, + num + 1, + request_url + ); + //}, 50); } - return true; - }, + }, + error: function(response) { + console.error(response); + } + }); + }, - skip: function(way) { - if(!offline){ - /*var u = Crypt.crypt_pass(Crypt.get_userpass(chan.toLowerCase()), true); - if(u == undefined) u = "";*/ - emit('skip', {id:video_id, channel: chan.toLowerCase()}); - } else { - if(way) { - Player.playNext(); + addToYoutubePlaylist: function(playlist_id, full_playlist, num, request_url) { + if (num == full_playlist.length) { + Helper.log(["All videoes added!"]); + Helper.log(["url: https://www.youtube.com/playlist?list=" + playlist_id]); + document + .querySelector(".exported-list") + .insertAdjacentHTML( + "beforeend", + "" + + chan + + "" + ); + Helper.addClass("#playlist_loader_export", "hide"); + Helper.addClass(".current_number", "hide"); + return; + //$(".youtube_export_button").removeClass("hide"); + } + if ( + full_playlist[num].hasOwnProperty("source") && + full_playlist[num].source != "soundcloud" + ) { + List.insertInYouTubePlaylist( + playlist_id, + full_playlist[num].id, + num, + request_url + ); + } else { + var yt_url = + "https://www.googleapis.com/youtube/v3/search?key=" + + api_key.youtube + + "&videoEmbeddable=true&part=id,snippet&fields=items(id,snippet)&type=video&order=relevance&safeSearch=none&maxResults=10&videoCategoryId=10"; + yt_url += "&q=" + full_playlist[num].title; + var title = full_playlist[num].title; + var temptitle = title.split("-"); + temptitle = temptitle.join(" ").split(" "); + var vid_url = + "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id&key=" + + api_key.youtube + + "&id="; + Helper.ajax({ + type: "GET", + url: yt_url, + dataType: "jsonp", + success: function(response) { + response = JSON.parse(response); + //Helper.log(response); + if (response.items.length === 0) { + Helper.log([ + "NO MATCH FOR:", + "Spotify title: " + title, + "Spotify length: " + length + ]); + var not_added_song = document.createElement("div"); + not_added_song.innerHTML = not_export_html; + + not_added_song.querySelector(".extra-add-text").innerText = title; + not_added_song + .querySelector(".extra-add-text") + .setAttribute("title", title); + not_added_song + .querySelector(".extra-button-search") + .setAttribute("data-text", title); + document + .querySelector(".not-exported-container") + .insertAdjacentHTML("beforeend", not_added_song.innerHTML); + Helper.removeClass(".not-exported", "hide"); + if (num == full_playlist.length) { + Helper.log(["All videoes added!"]); + Helper.log([ + "url: https://www.youtube.com/playlist?list=" + playlist_id + ]); + document + .querySelector(".exported-list") + .insertAdjacentHTML( + "beforeend", + "" + + chan + + "" + ); + Helper.addClass("#playlist_loader_export", "hide"); + Helper.addClass(".current_number", "hide"); + //$(".youtube_export_button").removeClass("hide"); } else { - Player.playPrev(); + //setTimeout(function(){ + Helper.removeClass(".current_number", "hide"); + document.querySelector(".current_number").innerText = + num + 1 + " of " + full_playlist.length; + List.addToYoutubePlaylist( + playlist_id, + full_playlist, + num + 1, + request_url + ); + //}, 50); + } + } else if (response.items.length > 0) { + for (var i = 0; i < response.items.length; i++) { + var data = response.items[i]; + vid_url += data.id.videoId + ","; } - } - return true; - }, - exportToSoundCloud: function(thisSong, i) { - if(i >= full_playlist.length) { - if(List.found.length == 0) { - for(var x = 0; x < List.not_found.length; x++) { - var data = List.not_found[x]; + Helper.ajax({ + type: "GET", + url: vid_url, + dataType: "jsonp", + success: function(response) { + response = JSON.parse(response); + if (response.items.length > 0) { + var matched = false; + for (var y = 0; y < response.items.length; y++) { + var data = response.items[y]; + //Helper.log(data); + //var title = data.snippet.title; + var duration = Search.durationToSeconds( + data.contentDetails.duration + ); + var not_matched = false; + if (similarity(data.snippet.title, title) > 0.75) { + not_matched = false; + } else { + for (var i = 0; i < temptitle.length; i++) { + var data_title = temptitle[i]; + + if ( + data.snippet.title + .toLowerCase() + .indexOf(data_title.toLowerCase()) == -1 || + !( + data.snippet.title.toLowerCase().indexOf("cover") == + -1 && + title.toLowerCase().indexOf("cover") == -1 && + ((data.snippet.title + .toLowerCase() + .indexOf("remix") == -1 && + title.toLowerCase().indexOf("remix") == -1) || + (data.snippet.title + .toLowerCase() + .indexOf("remix") != -1 && + title.toLowerCase().indexOf("remix") != -1) || + !( + data.snippet.title + .toLowerCase() + .indexOf(data_title.toLowerCase()) == -1 && + data.snippet.channelTitle + .toLowerCase() + .indexOf("vevo") == -1 + )) + ) + ) + not_matched = true; + else if (duration > 1800) not_matched = true; + } + } + + if (!not_matched) { + matched = true; + List.insertInYouTubePlaylist( + playlist_id, + data.id, + num, + request_url + ); + break; + } + } + if (!matched) { + if (num == full_playlist.length - 1) { + Helper.log(["All videoes added!"]); + Helper.log([ + "url: https://www.youtube.com/playlist?list=" + + playlist_id + ]); + document + .querySelector(".exported-list") + .insertAdjacentHTML( + "beforeend", + "" + + chan + + "" + ); + Helper.addClass("#playlist_loader_export", "hide"); + Helper.addClass(".current_number", "hide"); + //$(".youtube_export_button").removeClass("hide"); + } else { + //setTimeout(function(){ + Helper.removeClass(".current_number", "hide"); + document.querySelector(".current_number").innerText = + num + 1 + " of " + full_playlist.length; + //}, 50); + } + Helper.log([ + "NO MATCH FOR:", + "Spotify title: " + title, + "Spotify length: " + length + ]); + var not_added_song = document.createElement("div"); not_added_song.innerHTML = not_export_html; - not_added_song.querySelector(".extra-add-text").setAttribute("value", data); - not_added_song.querySelector(".extra-add-text").setAttribute("title", data); - document.querySelector(".not-exported-container").insertAdjacentHTML("beforeend", not_added_song.innerHTML); - } - Helper.removeClass(".not-exported", "hide"); - Helper.addClass(".current_number", "hide"); - Helper.addClass("#playlist_loader_export", "hide"); - Helper.addClass(".exported-list-container", "hide"); - List.found = []; - List.not_found = []; - } else { - SC_player.post('/playlists', { - playlist: { - title: chan.toLowerCase() + " - Zoff", - tracks: List.found, - description: "Playlist exported from https://zoff.me/" + Helper.encodeChannelName(chan.toLowerCase()), - } - }).then(function(result) { - for(var x = 0; x < List.not_found.length; x++) { - var data = List.not_found[x]; - var not_added_song = document.createElement("div"); - not_added_song.innerHTML = not_export_html; - not_added_song.querySelector(".extra-add-text").setAttribute("value", data); - not_added_song.querySelector(".extra-add-text").setAttribute("title", data); - document.querySelector(".not-exported-container").insertAdjacentHTML("beforeend", not_added_song.innerHTML); - } - Helper.addClass(".current_number", "hide"); - Helper.addClass("#playlist_loader_export", "hide"); - Helper.addClass(".exported-list-container", "hide"); - document.querySelector(".exported-list").insertAdjacentHTML("beforeend", "" + result.title + ""); + not_added_song.querySelector( + ".extra-add-text" + ).value = title; + not_added_song + .querySelector(".extra-add-text") + .setAttribute("value", title); + not_added_song + .querySelector(".extra-add-text") + .setAttribute("title", title); + //not_added_song.querySelector(".extra-button-search").setAttribute("data-text", title); + document + .querySelector(".not-exported-container") + .insertAdjacentHTML( + "beforeend", + not_added_song.innerHTML + ); Helper.removeClass(".not-exported", "hide"); - toast("List exported!"); - List.found = []; - List.not_found = []; - }).catch(function(error) { - console.log(error); - }); - } - } else if(thisSong == undefined) { - ga('send', 'event', "export", "soundcloud"); - if(full_playlist.length > 0) { - List.exportToSoundCloud(full_playlist[0], 0); - } - } else if(thisSong != undefined && i != undefined) { - var isFound = false; - Helper.removeClass(".current_number", "hide"); - document.querySelector(".current_number").innerText = (i) + " of " + (full_playlist.length); - if(thisSong.source == "soundcloud") { - List.found.push({id: parseInt(thisSong.id)}); - List.exportToSoundCloud(full_playlist[i+1], i+1); - } else { - var _title = thisSong.title; - _title = Helper.replaceForFind(_title); - SC_player.get('/tracks', { - q: _title - }).then(function(tracks) { - //$("#results").append(result_html); - //Helper.css(document.querySelector(".search_results .col.s12"), "display", "block"); - for(var y = 0; y < tracks.length; y++) { - var song = tracks[y]; - if(!song.streamable) continue; - var duration=Math.floor(song.duration / 1000); - //var secs=Search.durationToSeconds(duration); - var secs = duration; - if(longsongs == undefined) longsongs = true; - if((longsongs != undefined && !longsongs) || secs<720){ - var title=song.title; - if(title.indexOf(song.user.username) == -1) { - title = song.user.username + " - " + title; - } - title = title.toLowerCase(); - var id=song.id; - if(similarity(title, _title) > 0.60) { - List.found.push({id: parseInt(song.id)}); - isFound = true; - break; - } - } - } - if(!isFound) { - List.not_found.push(full_playlist[i].title); - } - List.exportToSoundCloud(full_playlist[i+1], i+1); - }).catch(function(e) { - List.not_found.push(full_playlist[i].title); - List.exportToSoundCloud(full_playlist[i+1], i+1); - }); - } - } - - }, - - exportToSpotify: function() { - ga('send', 'event', "export", "spotify"); - - Helper.ajax({ - type: "GET", - url: "https://api.spotify.com/v1/me", - headers: { - 'Authorization': 'Bearer ' + access_token_data.access_token - }, - success: function(response){ - response = JSON.parse(response); - var user_id = response.id; - Helper.removeClass("#playlist_loader_export", "hide"); - Helper.removeClass(".exported-list-container", "hide"); - Helper.ajax({ - type: "POST", - url: "https://api.spotify.com/v1/users/" + user_id + "/playlists", - headers: { - 'Authorization': 'Bearer ' + access_token_data.access_token, - 'Content-Type': 'application/json' - }, - data: JSON.stringify({ - name: chan.toLowerCase() + " - Zoff", - description: "Playlist exported from Zoff (https://zoff.me/" + chan.toLowerCase() + "/)", - public: true - }), - success: function(response){ - response = JSON.parse(response); - var playlist_id = response.id; - Helper.ajax({ - type: "GET", - url: window.location.protocol + "//" + window.location.hostname + "/assets/images/small-square.base64.txt", - success: function(base64image) { - var image = base64image.substring(0, base64image.length - 1); - Helper.ajax({ - type: "PUT", - url: "https://api.spotify.com/v1/users/" + user_id + "/playlists/" + playlist_id + "/images", - headers: { - 'Authorization': 'Bearer ' + access_token_data.access_token, - 'Content-Type': 'image/jpeg' - }, - contentType: "image/jpeg", - data: image, - success: function(resp) { - }, - error: function(error) { - console.error(error); - } - }); - } - }); - var i = 0; - List.searchSpotify(full_playlist[i], playlist_id, user_id, full_playlist, i); - //}); - }, error: function(e) { - } - }); - }, error: function(e) { + List.addToYoutubePlaylist( + playlist_id, + full_playlist, + num + 1, + request_url + ); + } + } + }, + error: function(e) { console.error(e); - } - }) - }, - - searchSpotify: function(curr_song, playlist_id, user_id, full_playlist, current_element) { - var original_track = curr_song.title; - var track = (curr_song.title.toLowerCase().replace("-", " ")); - track = Helper.replaceForFind(track); - track = encodeURIComponent(track); - - Helper.removeClass(".current_number", "hide"); - document.querySelector(".current_number").innerText = (current_element + 1) + " of " + (full_playlist.length); - Helper.ajax({ - type: "GET", - url: "https://api.spotify.com/v1/search?q=" + track + "&type=track", - headers: { - 'Authorization': 'Bearer ' + access_token_data.access_token - }, - async: true, - error: function(err){ - if(err.status == 429 || err.status == 502){ - Helper.log([err.getAllResponseHeaders()]); - var retryAfter = err.getResponseHeader("Retry-After"); - Helper.log([retryAfter]); - if (!retryAfter) retryAfter = 5; - retryAfter = parseInt(retryAfter, 10); - Helper.log(["Retry-After", retryAfter]); - setTimeout(function(){ - List.searchSpotify(curr_song, playlist_id, user_id, full_playlist, current_element); - }, retryAfter * 1000); - } - }, - success: function(response){ - response = JSON.parse(response); - var found = false; - for(var i = 0; i < response.tracks.items.length; i++) { - var data = response.tracks.items[i]; - data.name = Helper.replaceForFind(data.name); - data.artists[0].name = Helper.replaceForFind(data.artists[0].name); - if(data.name.substring(data.name.length-1) == " ") data.name = data.name.substring(0,data.name.length-1); - if(data.name.substring(data.name.length-1) == "." && track.substring(track.length-1) != "."){ - data.name = data.name.substring(0,data.name.length-1); - } - if(similarity(data.artists[0].name + " - " + data.name, decodeURIComponent(track)) > 0.60 || (data.artists.length > 1 && similarity(data.artists[0].name + " " + data.artists[1].name + " - " + data.name, decodeURIComponent(track)))) { - found = true; - List.uris.push(data.uri); - Helper.log([ - "Found", - track - ]); - //List.num_songs = List.num_songs + 1; - break; - } else if(decodeURIComponent(track).indexOf(data.artists[0].name.toLowerCase()) >= 0 && decodeURIComponent(track).indexOf(data.name.toLowerCase()) >= 0){ - found = true; - List.uris.push(data.uri); - Helper.log([ - "Found", - track - ]); - //List.num_songs = List.num_songs + 1; - break; - } else { - var splitted = data.name.split(" "); - var toBreak = false; - for(var i = 0; i < splitted.length; i++) { - if((splitted[i] == "and" && track.indexOf("&") >= 0) || (splitted[i] == "&" && track.indexOf("and") >= 0)){ - continue; - } else if(track.indexOf(splitted[i]) < 0){ - toBreak = true; - break; - } - } - if(toBreak) break; - found = true; - List.uris.push(data.uri); - Helper.log([ - "Found", - track - ]); - //List.num_songs = List.num_songs + 1; - break; - } - } - if(!found){ - List.not_found.push(original_track); - List.num_songs = List.num_songs + 1; - Helper.log([ - "Didn't find", - original_track - ]); - } - if(List.num_songs + List.uris.length == full_playlist.length){ - if(List.uris.length > 100){ - while(List.uris.length > 100){ - List.addToSpotifyPlaylist(List.uris.slice(0, 100), playlist_id, user_id); - List.uris = List.uris.slice(100, List.uris.length); - } - List.addToSpotifyPlaylist(List.uris, playlist_id, user_id); - Helper.addClass("#playlist_loader_export", "hide"); - } else { - List.addToSpotifyPlaylist(List.uris, playlist_id, user_id); - Helper.addClass("#playlist_loader_export", "hide"); - } - if(document.querySelectorAll(".exported-spotify-list").length == 0) { - document.querySelector(".exported-list").insertAdjacentHTML("beforeend", "" + chan + ""); - } - for(var i = 0; i < List.not_found.length; i++) { - var data = List.not_found[i]; - var not_added_song = document.createElement("div"); - not_added_song.innerHTML = not_export_html; - not_added_song.querySelector(".extra-add-text").setAttribute("value", data); - not_added_song.querySelector(".extra-add-text").setAttribute("title", data); - document.querySelector(".not-exported-container").insertAdjacentHTML("beforeend", not_added_song.innerHTML); - } - Helper.addClass(".current_number", "hide"); - Helper.removeClass(".not-exported", "hide"); - Helper.css(".spotify_export_button", "display", "block"); - } else { - List.searchSpotify(full_playlist[current_element + 1], playlist_id, user_id, full_playlist, current_element + 1); - } - } - }); - }, - - addToSpotifyPlaylist: function(uris, playlist_id, user_id) { - Helper.ajax({ - type: "POST", - url: "https://api.spotify.com/v1/users/" + user_id + "/playlists/" + playlist_id + "/tracks", - headers: { - 'Authorization': 'Bearer ' + access_token_data.access_token, - 'Content-Type': 'application/json' - }, - data: JSON.stringify({ - uris: uris - }), - error: function(response){ - var temp_playlist_id = playlist_id; - var temp_uris = uris; - var temp_user_id = user_id; - setTimeout(function(){ - List.addToSpotifyPlaylist(temp_uris, temp_playlist_id, temp_user_id); - }, 3000); - }, - success: function(response){ - Helper.log(["Added songs"]); - } - }) - }, - - exportToYoutube: function() { - ga('send', 'event', "export", "youtube"); - - var request_url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&key=" + api_key.youtube; - Helper.removeClass(".exported-list-container", "hide"); - Helper.removeClass("#playlist_loader_export", "hide"); - Helper.ajax({ - type: "POST", - url: request_url, - headers: { - 'Authorization': 'Bearer ' + access_token_data_youtube.access_token, - 'Content-Type': 'application/json' - }, - data: JSON.stringify({ - snippet: { - title: Helper.upperFirst(chan.toLowerCase()), - description: 'Playlist exported from zoff', - } - }), - success: function(response){ - response = JSON.parse(response); - var number_added = 0; - var playlist_id = response.id; - var request_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&key=" + api_key.youtube; - List.addToYoutubePlaylist(playlist_id, full_playlist, number_added, request_url) - }, - error: function(response){ - console.error(response); - toast("Couldn't export to YouTube for some reason.. Try again later", "red lighten"); - Helper.addClass(".exported-list-container", "hide"); - Helper.addClass("#playlist_loader_export", "hide"); - Helper.removeClass(".youtube_export_button", "hide"); - response = response.responseText; - Helper.log([ - "export to youtube response", - response - ]); - } - }); - }, - - insertInYouTubePlaylist: function(playlist_id, _videoId, num, request_url) { - var _data = JSON.stringify({ - 'snippet': { - 'playlistId': playlist_id, - 'resourceId': { - 'kind': 'youtube#video', - 'videoId': _videoId - } - } - }); - Helper.ajax({ - type: "POST", - url: request_url, - headers: { - 'Authorization': 'Bearer ' + access_token_data_youtube.access_token, - 'Content-Type': 'application/json' - }, - data: _data, - success: function(response){ - response = JSON.parse(response); - Helper.log(["Added video: " + full_playlist[num].id + " to playlist id " + playlist_id]); - if(num == full_playlist.length - 1){ - Helper.log(["All videoes added!"]); - Helper.log(["url: https://www.youtube.com/playlist?list=" + playlist_id]); - document.querySelector(".exported-list").insertAdjacentHTML("beforeend", "" + chan + ""); - Helper.addClass("#playlist_loader_export", "hide"); - Helper.addClass(".current_number", "hide"); - //$(".youtube_export_button").removeClass("hide"); - } else { - //setTimeout(function(){ - Helper.removeClass(".current_number", "hide"); - document.querySelector(".current_number").innerText = (num + 1) + " of " + (full_playlist.length); - List.addToYoutubePlaylist(playlist_id, full_playlist, num + 1, request_url); - //}, 50); - } - }, error: function(response) { - console.error(response); - } - - }); - }, - - addToYoutubePlaylist: function(playlist_id, full_playlist, num, request_url) { - if(num == full_playlist.length){ - Helper.log(["All videoes added!"]); - Helper.log(["url: https://www.youtube.com/playlist?list=" + playlist_id]); - document.querySelector(".exported-list").insertAdjacentHTML("beforeend", "" + chan + ""); - Helper.addClass("#playlist_loader_export", "hide"); - Helper.addClass(".current_number", "hide"); - return; - //$(".youtube_export_button").removeClass("hide"); - } - if(full_playlist[num].hasOwnProperty("source") && full_playlist[num].source != "soundcloud") { - List.insertInYouTubePlaylist(playlist_id, full_playlist[num].id, num, request_url) - } else { - var yt_url = "https://www.googleapis.com/youtube/v3/search?key="+api_key.youtube+"&videoEmbeddable=true&part=id,snippet&fields=items(id,snippet)&type=video&order=relevance&safeSearch=none&maxResults=10&videoCategoryId=10"; - yt_url+="&q="+full_playlist[num].title; - var title = full_playlist[num].title; - var temptitle = title.split("-"); - temptitle = temptitle.join(" ").split(" "); - var vid_url = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet,id&key="+api_key.youtube+"&id="; - Helper.ajax({ - type: "GET", - url: yt_url, - dataType:"jsonp", - success: function(response){ - response = JSON.parse(response); - //Helper.log(response); - if(response.items.length === 0){ - Helper.log([ - "NO MATCH FOR:", - "Spotify title: " + title, - "Spotify length: " + length - ]); - var not_added_song = document.createElement("div"); - not_added_song.innerHTML = not_export_html; - - not_added_song.querySelector(".extra-add-text").innerText = title; - not_added_song.querySelector(".extra-add-text").setAttribute("title", title); - not_added_song.querySelector(".extra-button-search").setAttribute("data-text", title); - document.querySelector(".not-exported-container").insertAdjacentHTML("beforeend", not_added_song.innerHTML); - Helper.removeClass(".not-exported", "hide"); - if(num == full_playlist.length){ - Helper.log(["All videoes added!"]); - Helper.log(["url: https://www.youtube.com/playlist?list=" + playlist_id]); - document.querySelector(".exported-list").insertAdjacentHTML("beforeend", "" + chan + ""); - Helper.addClass("#playlist_loader_export", "hide"); - Helper.addClass(".current_number", "hide"); - //$(".youtube_export_button").removeClass("hide"); - } else { - //setTimeout(function(){ - Helper.removeClass(".current_number", "hide"); - document.querySelector(".current_number").innerText = (num + 1) + " of " + (full_playlist.length); - List.addToYoutubePlaylist(playlist_id, full_playlist, num + 1, request_url); - //}, 50); - } - } else if(response.items.length > 0) { - for(var i = 0; i < response.items.length; i++) { - var data = response.items[i]; - vid_url += data.id.videoId+","; - } - - Helper.ajax({ - type: "GET", - url: vid_url, - dataType:"jsonp", - success: function(response){ - response = JSON.parse(response); - if(response.items.length > 0) { - var matched = false; - for(var y = 0; y < response.items.length; y++) { - var data = response.items[y]; - //Helper.log(data); - //var title = data.snippet.title; - var duration = Search.durationToSeconds(data.contentDetails.duration); - var not_matched = false; - if(similarity(data.snippet.title,title) > 0.75) { - not_matched = false; - } else { - for(var i = 0; i < temptitle.length; i++) { - var data_title = temptitle[i]; - - if(data.snippet.title.toLowerCase().indexOf(data_title.toLowerCase()) == -1 || !( - data.snippet.title.toLowerCase().indexOf("cover") == -1 && - title.toLowerCase().indexOf("cover") == -1 && - ((data.snippet.title.toLowerCase().indexOf("remix") == -1 && - title.toLowerCase().indexOf("remix") == -1) || - (data.snippet.title.toLowerCase().indexOf("remix") != -1 && - title.toLowerCase().indexOf("remix") != -1) || !(data.snippet.title.toLowerCase().indexOf(data_title.toLowerCase()) == -1 && - data.snippet.channelTitle.toLowerCase().indexOf("vevo") == -1))) - ) - not_matched = true; - else if(duration > 1800) not_matched = true; - } - } - - if((!not_matched)){ - matched = true; - List.insertInYouTubePlaylist(playlist_id, data.id, num, request_url); - break; - } - } - if(!matched){ - if(num == full_playlist.length - 1){ - Helper.log(["All videoes added!"]); - Helper.log(["url: https://www.youtube.com/playlist?list=" + playlist_id]); - document.querySelector(".exported-list").insertAdjacentHTML("beforeend", "" + chan + ""); - Helper.addClass("#playlist_loader_export", "hide"); - Helper.addClass(".current_number", "hide"); - //$(".youtube_export_button").removeClass("hide"); - } else { - //setTimeout(function(){ - Helper.removeClass(".current_number", "hide"); - document.querySelector(".current_number").innerText = (num + 1) + " of " + (full_playlist.length); - //}, 50); - } - Helper.log([ - "NO MATCH FOR:", - "Spotify title: " + title, - "Spotify length: " + length - ]); - - var not_added_song = document.createElement("div"); - not_added_song.innerHTML = not_export_html; - not_added_song.querySelector(".extra-add-text").value = title; - not_added_song.querySelector(".extra-add-text").setAttribute("value", title); - not_added_song.querySelector(".extra-add-text").setAttribute("title", title); - //not_added_song.querySelector(".extra-button-search").setAttribute("data-text", title); - document.querySelector(".not-exported-container").insertAdjacentHTML("beforeend", not_added_song.innerHTML); - Helper.removeClass(".not-exported", "hide"); - List.addToYoutubePlaylist(playlist_id, full_playlist, num + 1, request_url); - - } - } - }, - error: function(e) { - console.error(e); - } - }); - - } - }, error: function(e) { - console.error(e); - } + } }); - + } + }, + error: function(e) { + console.error(e); } - }, - - sortList: function() { - full_playlist.sort(Helper.predicate({ - name: 'votes', - reverse: true - }, { - name: 'added', - reverse: false - }, { - name: 'title', - reverse: false - })); - }, - - show: function() { - if(!Helper.mobilecheck() && !chromecastAvailable) { - M.Modal.getInstance(document.getElementById("channel-share-modal")).open(); - } - if(chromecastAvailable) { - castSession.sendMessage("urn:x-cast:zoff.me", {type: "showJoinInfo"}); - } - }, - - generateSong: function(_song_info, transition, lazy, list, user, display, initial, filtered) { - if(list_html === undefined) list_html = Helper.html("#list-song-html"); - var video_id = _song_info.id; - var video_title = _song_info.title; - var video_votes = _song_info.votes; - var video_thumb_url = "//img.youtube.com/vi/"+video_id+"/mqdefault.jpg"; - if(_song_info.source == "soundcloud") { - video_thumb_url = _song_info.thumbnail; - } - var video_thumb = "background-image:url('" + video_thumb_url + "');"; - var song = document.createElement("div"); - song.innerHTML = list_html; - song = song.cloneNode(true); - var image_attr = "style"; - if(_song_info.hasOwnProperty("start") && _song_info.hasOwnProperty("end")) { - _song_info.duration = _song_info.end - _song_info.start; - } - var attr; - var del_attr; - //song.find(".list-song"); - if(transition) { - Helper.css(song.querySelector(".list-song"), "transform", "translateX(100%)"); - Helper.addClass(song.querySelector(".list-song"), "side_away"); - } - Helper.css(song.querySelector(".list-song"), "height", List.element_height + "px"); - if(!w_p) Helper.removeClass(song.querySelector(".card-action"), "hide"); - if(video_votes == 1)song.querySelector(".vote-text").innerText = "vote"; - if(lazy){ - video_thumb = "//img.youtube.com/vi/"+video_id+"/mqdefault.jpg"; - image_attr = "data-original"; - } - - song.querySelector(".list-image").setAttribute(image_attr,video_thumb); - if(list && !filtered){ - //song.querySelector("#list-song") - song.querySelector(".list-votes").innerText = video_votes; - song.querySelector("#list-song").setAttribute("data-video-id", video_id); - song.querySelector("#list-song").setAttribute("data-video-type", "song"); - song.querySelector("#list-song").setAttribute("data-video-source", _song_info.source); - song.querySelector("#list-song").setAttribute("id", video_id); - song.classList.remove("hide"); - song.querySelector(".vote-container").setAttribute("title", video_title); - if(((document.querySelector("#wrapper").children.length >= List.can_fit) && initial) || display == "none"){ - Helper.css(song.querySelector(".card"), "display", "none"); - } - attr = ".vote-container"; - del_attr = "delete_button"; - - var _temp_duration = Helper.secondsToOther(_song_info.duration); - song.querySelector(".card-duration").innerText = Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); - }else if(!list && !filtered){ - - //song.querySelector(".card-duration").remove(); - //song.querySelector(".list-song").removeClass("playlist-element"); - //song.querySelector(".more_button").addClass("hide"); - Helper.removeClass(song.querySelector(".suggested_remove"), "hide"); - song.querySelector(".vote-text").innerText = ""; - song.querySelector(".card-duration").innerText = Helper.pad(_song_info.duration[0]) + ":" + Helper.pad(_song_info.duration[1]); - var added_by = "user"; - attr = ".add-suggested"; - if(user){ - del_attr = "del_user_suggested"; - } else{ - del_attr = "del_suggested"; - added_by = "system"; - } - song.querySelector(".vote-container").setAttribute("class", "clickable add-suggested"); - song.querySelector(".add-suggested").setAttribute("title", video_title); - //Helper.addClass(song.querySelector(".delete_button"), del_attr); - song.querySelector(".list-votes").innerText = _song_info.extra; - song.querySelector(".vote-text").innerText = video_votes; - song.querySelector(attr).setAttribute("data-video-title", video_title); - song.querySelector(attr).setAttribute("data-video-length", _song_info.length); - song.querySelector(attr).setAttribute("data-added-by", added_by); - song.querySelector(attr).setAttribute("data-video-type", "suggested"); - if(_song_info.source == "soundcloud") { - song.querySelector(attr).setAttribute("data-type-thumbnail", _song_info.thumbnail); - - } - song.querySelector(attr).setAttribute("data-video-source", _song_info.source); - song.querySelector("#list-song").setAttribute("data-video-id", video_id); - Helper.css(song.querySelector("#list-song"), "display", "inline-flex"); - song.querySelector("#list-song").setAttribute("id", "suggested-" + video_id); - var list_image = song.querySelector(".list-image"); - list_image.classList.remove("list-image"); - list_image.className += " list-suggested-image"; - //song.querySelector(".list-image").setAttribute("class", song.querySelector(".list-image").getAttribute("class").replace("list-image", "list-suggested-image")); - } else if(filtered) { - song.querySelector("#list-song").className += " filtered-search-element"; - song.querySelector(".list-votes").innerText = _song_info.tags.join(", "); - song.querySelector(".vote-text").remove(); - song.querySelector("#list-song").setAttribute("data-video-id", video_id); - song.querySelector("#list-song").setAttribute("data-video-type", "song"); - song.querySelector("#list-song").setAttribute("data-video-source", _song_info.source); - song.querySelector("#list-song").setAttribute("id", "filtered-" + video_id); - song.classList.remove("hide"); - song.className += " filtered-search-element"; - song.querySelector(".vote-container").setAttribute("title", video_title); - attr = ".vote-container"; - del_attr = "delete_button"; - - var _temp_duration = Helper.secondsToOther(_song_info.duration); - song.querySelector(".card-duration").innerText = Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); - } - if(!embed) { - song.querySelector(".mobile-delete").remove(); - } - if(hostMode) { - song.querySelector(".list-remove").style.display = "none"; - } - song.querySelector(".list-title").innerText = video_title; - song.querySelector(".list-title").setAttribute("title", video_title); - song.querySelector(attr).setAttribute("data-video-id", video_id); - //song.querySelector(".list-image-placeholder").setAttribute("src", video_thumb_url); - if(song.querySelectorAll(".list-suggested-image").length > 0) { - song.querySelector(".list-suggested-image").setAttribute(image_attr,video_thumb); - } - //song.querySelector("."+del_attr).setAttribute("data-video-id", video_id); - return song.innerHTML; - }, - - getIndexOfSong: function(id) { - try { - for(var i = 0; i < full_playlist.length; i++) { - if(full_playlist[i].id == id) return i; - } - return -1; - } catch(e) {return -1;} + }); } + }, + + sortList: function() { + full_playlist.sort( + Helper.predicate( + { + name: "votes", + reverse: true + }, + { + name: "added", + reverse: false + }, + { + name: "title", + reverse: false + } + ) + ); + }, + + show: function() { + if (!Helper.mobilecheck() && !chromecastAvailable) { + M.Modal.getInstance( + document.getElementById("channel-share-modal") + ).open(); + } + if (chromecastAvailable) { + castSession.sendMessage("urn:x-cast:zoff.me", { type: "showJoinInfo" }); + } + }, + + generateSong: function( + _song_info, + transition, + lazy, + list, + user, + display, + initial, + filtered + ) { + if (list_html === undefined) list_html = Helper.html("#list-song-html"); + var video_id = _song_info.id; + var video_title = _song_info.title; + var video_votes = _song_info.votes; + var video_thumb_url = "//img.youtube.com/vi/" + video_id + "/mqdefault.jpg"; + if (_song_info.source == "soundcloud") { + video_thumb_url = _song_info.thumbnail; + } + var video_thumb = "background-image:url('" + video_thumb_url + "');"; + var song = document.createElement("div"); + song.innerHTML = list_html; + song = song.cloneNode(true); + var image_attr = "style"; + if ( + _song_info.hasOwnProperty("start") && + _song_info.hasOwnProperty("end") + ) { + _song_info.duration = _song_info.end - _song_info.start; + } + var attr; + var del_attr; + //song.find(".list-song"); + if (transition) { + Helper.css( + song.querySelector(".list-song"), + "transform", + "translateX(100%)" + ); + Helper.addClass(song.querySelector(".list-song"), "side_away"); + } + Helper.css( + song.querySelector(".list-song"), + "height", + List.element_height + "px" + ); + if (!w_p) Helper.removeClass(song.querySelector(".card-action"), "hide"); + if (video_votes == 1) song.querySelector(".vote-text").innerText = "vote"; + if (lazy) { + video_thumb = "//img.youtube.com/vi/" + video_id + "/mqdefault.jpg"; + image_attr = "data-original"; + } + + song.querySelector(".list-image").setAttribute(image_attr, video_thumb); + if (list && !filtered) { + //song.querySelector("#list-song") + song.querySelector(".list-votes").innerText = video_votes; + song.querySelector("#list-song").setAttribute("data-video-id", video_id); + song.querySelector("#list-song").setAttribute("data-video-type", "song"); + song + .querySelector("#list-song") + .setAttribute("data-video-source", _song_info.source); + song.querySelector("#list-song").setAttribute("id", video_id); + song.classList.remove("hide"); + song.querySelector(".vote-container").setAttribute("title", video_title); + if ( + (document.querySelector("#wrapper").children.length >= List.can_fit && + initial) || + display == "none" + ) { + Helper.css(song.querySelector(".card"), "display", "none"); + } + attr = ".vote-container"; + del_attr = "delete_button"; + + var _temp_duration = Helper.secondsToOther(_song_info.duration); + song.querySelector(".card-duration").innerText = + Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); + } else if (!list && !filtered) { + //song.querySelector(".card-duration").remove(); + //song.querySelector(".list-song").removeClass("playlist-element"); + //song.querySelector(".more_button").addClass("hide"); + Helper.removeClass(song.querySelector(".suggested_remove"), "hide"); + song.querySelector(".vote-text").innerText = ""; + song.querySelector(".card-duration").innerText = + Helper.pad(_song_info.duration[0]) + + ":" + + Helper.pad(_song_info.duration[1]); + var added_by = "user"; + attr = ".add-suggested"; + if (user) { + del_attr = "del_user_suggested"; + } else { + del_attr = "del_suggested"; + added_by = "system"; + } + song + .querySelector(".vote-container") + .setAttribute("class", "clickable add-suggested"); + song.querySelector(".add-suggested").setAttribute("title", video_title); + //Helper.addClass(song.querySelector(".delete_button"), del_attr); + song.querySelector(".list-votes").innerText = _song_info.extra; + song.querySelector(".vote-text").innerText = video_votes; + song.querySelector(attr).setAttribute("data-video-title", video_title); + song + .querySelector(attr) + .setAttribute("data-video-length", _song_info.length); + song.querySelector(attr).setAttribute("data-added-by", added_by); + song.querySelector(attr).setAttribute("data-video-type", "suggested"); + if (_song_info.source == "soundcloud") { + song + .querySelector(attr) + .setAttribute("data-type-thumbnail", _song_info.thumbnail); + } + song + .querySelector(attr) + .setAttribute("data-video-source", _song_info.source); + song.querySelector("#list-song").setAttribute("data-video-id", video_id); + Helper.css(song.querySelector("#list-song"), "display", "inline-flex"); + song + .querySelector("#list-song") + .setAttribute("id", "suggested-" + video_id); + var list_image = song.querySelector(".list-image"); + list_image.classList.remove("list-image"); + list_image.className += " list-suggested-image"; + //song.querySelector(".list-image").setAttribute("class", song.querySelector(".list-image").getAttribute("class").replace("list-image", "list-suggested-image")); + } else if (filtered) { + song.querySelector("#list-song").className += " filtered-search-element"; + song.querySelector(".list-votes").innerText = _song_info.tags.join(", "); + song.querySelector(".vote-text").remove(); + song.querySelector("#list-song").setAttribute("data-video-id", video_id); + song.querySelector("#list-song").setAttribute("data-video-type", "song"); + song + .querySelector("#list-song") + .setAttribute("data-video-source", _song_info.source); + song + .querySelector("#list-song") + .setAttribute("id", "filtered-" + video_id); + song.classList.remove("hide"); + song.className += " filtered-search-element"; + song.querySelector(".vote-container").setAttribute("title", video_title); + attr = ".vote-container"; + del_attr = "delete_button"; + + var _temp_duration = Helper.secondsToOther(_song_info.duration); + song.querySelector(".card-duration").innerText = + Helper.pad(_temp_duration[0]) + ":" + Helper.pad(_temp_duration[1]); + } + if (!embed) { + song.querySelector(".mobile-delete").remove(); + } + if (hostMode) { + song.querySelector(".list-remove").style.display = "none"; + } + song.querySelector(".list-title").innerText = video_title; + song.querySelector(".list-title").setAttribute("title", video_title); + song.querySelector(attr).setAttribute("data-video-id", video_id); + //song.querySelector(".list-image-placeholder").setAttribute("src", video_thumb_url); + if (song.querySelectorAll(".list-suggested-image").length > 0) { + song + .querySelector(".list-suggested-image") + .setAttribute(image_attr, video_thumb); + } + //song.querySelector("."+del_attr).setAttribute("data-video-id", video_id); + return song.innerHTML; + }, + + getIndexOfSong: function(id) { + try { + for (var i = 0; i < full_playlist.length; i++) { + if (full_playlist[i].id == id) return i; + } + return -1; + } catch (e) { + return -1; + } + } }; diff --git a/server/public/assets/js/listeners.js b/server/public/assets/js/listeners.js index fbcdf55a..aab85416 100755 --- a/server/public/assets/js/listeners.js +++ b/server/public/assets/js/listeners.js @@ -1,16 +1,19 @@ -var chan = window.chan === undefined && document.querySelectorAll("#chan").length > 0 ? document.querySelector("#chan").innerText : window.chan; +var chan = + window.chan === undefined && document.querySelectorAll("#chan").length > 0 + ? document.querySelector("#chan").innerText + : window.chan; var w_p = true; var domain = window.location.host.split("."); var client = false; -if(domain.length > 0 && domain[0] == "client") { - client = true; +if (domain.length > 0 && domain[0] == "client") { + client = true; } var _VERSION; try { - _VERSION = localStorage.getItem("VERSION"); - if(_VERSION == null || _VERSION == undefined) throw "Some error"; -} catch(e) { - _VERSION = 6; + _VERSION = localStorage.getItem("VERSION"); + if (_VERSION == null || _VERSION == undefined) throw "Some error"; +} catch (e) { + _VERSION = 6; } var SC_widget; var scUsingWidget = false; @@ -33,7 +36,10 @@ var hasadmin = 0; var hostMode = false; var soundcloud_loading = false; var buffering = false; -var list_html = document.querySelectorAll("#list-song-html").length > 0 ? document.querySelector("#list-song-html").innerHTML : undefined; +var list_html = + document.querySelectorAll("#list-song-html").length > 0 + ? document.querySelector("#list-song-html").innerHTML + : undefined; var unseen = false; var searching = false; var time_regex = /P((([0-9]*\.?[0-9]*)Y)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)W)?(([0-9]*\.?[0-9]*)D)?)?(T(([0-9]*\.?[0-9]*)H)?(([0-9]*\.?[0-9]*)M)?(([0-9]*\.?[0-9]*)S)?)?/; @@ -49,7 +55,7 @@ var programscroll = false; var lastCommand; var tried_again = false; var userscroll = false; -var gotten_np = false; +var gotten_np = false; var frontpage = 1; var adminpass = ""; var showDiscovery = false; @@ -58,8 +64,11 @@ var toggleChat = true; var viewers = 1; var temp_user_pass = ""; var zoff_api_token = "DwpnKVkaMH2HdcpJT2YPy783SY33byF5/32rbs0+xdU="; -if(window.location.hostname == "localhost" || window.location.hostname == "client.localhost") { - var zoff_api_token = "AhmC4Yg2BhaWPZBXeoWK96DAiAVfbou8TUG2IXtD3ZQ="; +if ( + window.location.hostname == "localhost" || + window.location.hostname == "client.localhost" +) { + var zoff_api_token = "AhmC4Yg2BhaWPZBXeoWK96DAiAVfbou8TUG2IXtD3ZQ="; } var retry_frontpage; var previousSoundcloud; @@ -71,7 +80,7 @@ var empty_clear = false; var user_auth_avoid = false; var user_change_password = false; var paused = false; -var currently_showing_channels = 1; +var currently_showing_channels = 1; var playing = false; var SAMPLE_RATE = 6000; // 6 seconds var lastSample = Date.now(); @@ -124,11 +133,13 @@ var width_timeout; var tap_target_timeout; var debug; try { - if(localStorage.debug === undefined){ - debug = false; - localStorage.debug = debug; - } -}catch(e){debug = false;} + if (localStorage.debug === undefined) { + debug = false; + localStorage.debug = debug; + } +} catch (e) { + debug = false; +} var image_timeout; var result_html; @@ -147,39 +158,39 @@ var seekTo; var song_title; var socket; var connection_options = { - 'sync disconnect on unload':true, - 'secure': true, - 'force new connection': true + "sync disconnect on unload": true, + secure: true, + "force new connection": true }; var fromFront = false; var fromChannel = false; -try{ - if (navigator.serviceWorker && window.location.host != "zoff.dev") { - navigator.serviceWorker.register('/service-worker.js', {scope: '/'}) - .then(function (registration) { - Helper.log(registration); - }) - .catch(function (event) { - console.error(event); - }); - } else { - Helper.log('Service Worker is not supported in this browser.'); - } - /* +try { + if (navigator.serviceWorker && window.location.host != "zoff.dev") { + navigator.serviceWorker + .register("/service-worker.js", { scope: "/" }) + .then(function(registration) { + Helper.log(registration); + }) + .catch(function(event) { + console.error(event); + }); + } else { + Helper.log("Service Worker is not supported in this browser."); + } + /* navigator.serviceWorker.getRegistration('/').then(function(registration) { if(registration) { registration.unregister(); } });*/ - -} catch(event) {} +} catch (event) {} window.zoff = { - enable_debug: enable_debug, - disable_debug: disable_debug, - list_last_logs: list_last_logs -} + enable_debug: enable_debug, + disable_debug: disable_debug, + list_last_logs: list_last_logs +}; /*if(!Helper.mobilecheck() && (window.location.host != "localhost" && window.location.host != "client.localhost")) { window.onerror = function(e, source, lineno, colno, error) { @@ -226,19 +237,21 @@ window.zoff = { }; }*/ -window.addEventListener("DOMContentLoaded", function() { +window.addEventListener( + "DOMContentLoaded", + function() { addDynamicListeners(); - if(!_VERSION || parseInt(_VERSION) != VERSION) { - try { - localStorage.setItem("VERSION", VERSION); - } catch(e){} + if (!_VERSION || parseInt(_VERSION) != VERSION) { + try { + localStorage.setItem("VERSION", VERSION); + } catch (e) {} } - if(!fromFront && window.location.pathname != "/") Channel.init(); - else if(!fromChannel && window.location.pathname == "/"){ - Frontpage.init(); + if (!fromFront && window.location.pathname != "/") Channel.init(); + else if (!fromChannel && window.location.pathname == "/") { + Frontpage.init(); } - var okCookie = true;; + var okCookie = true; /*try { okCookie = localStorage.ok_cookie; } catch(e) { @@ -248,44 +261,50 @@ window.addEventListener("DOMContentLoaded", function() { before_toast(); //M.toast({html: "This website uses cookies! ok info", displayLength: 10000000}); }*/ - if(window.location.hash == "#cookies") { - M.Modal.init(document.getElementById("cookie")); - M.Modal.getInstance(document.getElementById("cookie")).open(); + if (window.location.hash == "#cookies") { + M.Modal.init(document.getElementById("cookie")); + M.Modal.getInstance(document.getElementById("cookie")).open(); } - if(window.location.pathname == "/" && !client) { - if(document.querySelectorAll("script[src='https://www.youtube.com/iframe_api']").length == 1){ - - } else { - tag = document.createElement('script'); - tag.src = "https://www.youtube.com/iframe_api"; - firstScriptTag = document.getElementsByTagName('script')[0]; - firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); - } - Player.loadSoundCloudPlayer(); - Player.loadSoundCloudIframe(); - } else if(window.location.pathname == "/" && client) { - //Player.loadSoundCloudPlayer(); + if (window.location.pathname == "/" && !client) { + if ( + document.querySelectorAll( + "script[src='https://www.youtube.com/iframe_api']" + ).length == 1 + ) { + } else { + tag = document.createElement("script"); + tag.src = "https://www.youtube.com/iframe_api"; + firstScriptTag = document.getElementsByTagName("script")[0]; + firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); + } + Player.loadSoundCloudPlayer(); + Player.loadSoundCloudIframe(); + } else if (window.location.pathname == "/" && client) { + //Player.loadSoundCloudPlayer(); } - if(Helper.mobilecheck()) { - socket.on("guid", function(msg) { - guid = msg; - }); + if (Helper.mobilecheck()) { + socket.on("guid", function(msg) { + guid = msg; + }); } M.Modal.init(document.getElementById("donate")); - socket.on("connect", function(){ - if(chromecastAvailable) { - socket.emit("get_id"); + socket.on("connect", function() { + if (chromecastAvailable) { + socket.emit("get_id"); + } + if (connect_error) { + connect_error = false; + if (offline) { + socket.emit("offline", { + status: true, + channel: chan != undefined ? chan.toLowerCase() : "" + }); } - if(connect_error){ - connect_error = false; - if(offline) { - socket.emit("offline", {status: true, channel: chan != undefined ? chan.toLowerCase() : ""}); - } - /*if(chan != undefined && (Crypt.get_pass(chan.toLowerCase()) !== undefined && Crypt.get_pass(chan.toLowerCase()) !== "")){ + /*if(chan != undefined && (Crypt.get_pass(chan.toLowerCase()) !== undefined && Crypt.get_pass(chan.toLowerCase()) !== "")){ emit("password", {password: Crypt.crypt_pass(Crypt.get_pass(chan.toLowerCase())), channel: chan.toLowerCase()}); }*/ /*$(".connect_error").fadeOut(function(){ @@ -293,17 +312,21 @@ window.addEventListener("DOMContentLoaded", function() { M.toast({ html: "Connected!", displayLength: 2000, classes: "green lighten"}); });*/ var to_remove = document.querySelector(".connect_error"); - if(to_remove != null) { - var instance = M.Toast.getInstance(to_remove); - instance.dismiss(); + if (to_remove != null) { + var instance = M.Toast.getInstance(to_remove); + instance.dismiss(); } - M.toast({ html: "Connected!", displayLength: 2000, classes: "green lighten"}); + M.toast({ + html: "Connected!", + displayLength: 2000, + classes: "green lighten" + }); //before_toast(); - } - //Chat.namechange("", true, true); -}); + } + //Chat.namechange("", true, true); + }); -/*socket.on("name", function(data) { + /*socket.on("name", function(data) { if(data.type == "name" && data.accepted) { Crypt.set_name(temp_name, temp_pass); temp_name = ""; @@ -314,103 +337,136 @@ temp_pass = ""; } });*/ -socket.on("self_ping", function() { - if(chan != undefined && chan.toLowerCase() != "") { - socket.emit("self_ping", {channel: chan.toLowerCase()}); - } -}); + socket.on("self_ping", function() { + if (chan != undefined && chan.toLowerCase() != "") { + socket.emit("self_ping", { channel: chan.toLowerCase() }); + } + }); -setup_no_connection_listener(); -}, false); + setup_no_connection_listener(); + }, + false +); initializeCastApi = function() { - try { - if(cast == undefined) return; - } catch(event) { - return; + try { + if (cast == undefined) return; + } catch (event) { + return; + } + cast.framework.CastContext.getInstance().setOptions({ + receiverApplicationId: "E6856E24", + autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED + }); + var context = cast.framework.CastContext.getInstance(); + chromecastReady = true; + context.addEventListener( + cast.framework.CastContextEventType.SESSION_STATE_CHANGED, + function(event) { + Helper.log(["session state", event.sessionState]); + switch (event.sessionState) { + case cast.framework.SessionState.SESSION_STARTED: + castSession = cast.framework.CastContext.getInstance().getCurrentSession(); + castSession.addMessageListener( + "urn:x-cast:zoff.me", + chromecastListener + ); + updateChromecastMetadata(); + //chrome.cast.Image('https://img.youtube.com/vi/'+video_id+'/mqdefault.jpg'); + chromecastAvailable = true; + paused = false; + mobile_beginning = false; + + //castSession.sendMessage("urn:x-cast:zoff.me", {type: "loadVideo", start: Player.np.start, end: Player.np.end, videoId: video_id, seekTo: _seekTo, channel: chan.toLowerCase(), source: videoSource, thumbnail: Player.np.thumbnail}) + castSession.sendMessage("urn:x-cast:zoff.me", { + type: "nextVideo", + videoId: full_playlist[0].id, + title: full_playlist[0].title, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + castSession.sendMessage("urn:x-cast:zoff.me", { + type: "chromecastInfoShow", + value: chromecastInfoShow + }); + loadChromecastVideo(); + if ( + window.location.hostname.indexOf("zoff.me") > -1 && + !offline && + window.location.hostname.indexOf("localhost") == -1 + ) { + socket.emit("get_id"); + } + hide_native(1); + if (Helper.mobilecheck()) { + Player.playVideo(); + } + Helper.css("#channel-load", "display", "none"); + Helper.addClass(".castButton", "castButton-white-active"); + Helper.css("#playpause", "visibility", "visible"); + Helper.css("#playpause", "pointer-events", "all"); + break; + case cast.framework.SessionState.SESSION_RESUMED: + castSession = cast.framework.CastContext.getInstance().getCurrentSession(); + castSession.addMessageListener( + "urn:x-cast:zoff.me", + chromecastListener + ); + updateChromecastMetadata(); + //chrome.cast.Image('https://img.youtube.com/vi/'+video_id+'/mqdefault.jpg'); + chromecastAvailable = true; + paused = false; + mobile_beginning = false; + + if ( + window.location.hostname.indexOf("zoff.me") > -1 && + !offline && + window.location.hostname.indexOf("localhost") == -1 + ) { + socket.emit("get_id"); + } + castSession.sendMessage("urn:x-cast:zoff.me", { + type: "chromecastInfoShow", + value: chromecastInfoShow + }); + loadChromecastVideo(); + //castSession.sendMessage("urn:x-cast:zoff.me", {type: "loadVideo", start: Player.np.start, end: Player.np.end, videoId: video_id, seekTo: _seekTo, channel: chan.toLowerCase(), source: videoSource, thumbnail: Player.np.thumbnail}) + castSession.sendMessage("urn:x-cast:zoff.me", { + type: "nextVideo", + videoId: full_playlist[0].id, + title: full_playlist[0].title, + source: full_playlist[0].source, + thumbnail: full_playlist[0].thumbnail + }); + hide_native(1); + Helper.css("#channel-load", "display", "none"); + Helper.addClass(".castButton", "castButton-white-active"); + Helper.css("#playpause", "visibility", "visible"); + Helper.css("#playpause", "pointer-events", "all"); + break; + case cast.framework.SessionState.SESSION_ENDED: + chromecastAvailable = false; + hide_native(0); + break; + } } - cast.framework.CastContext.getInstance().setOptions({ - receiverApplicationId: "E6856E24", - autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED - }); - var context = cast.framework.CastContext.getInstance(); - chromecastReady = true; - context.addEventListener(cast.framework.CastContextEventType.SESSION_STATE_CHANGED, function(event) { - Helper.log([ - "session state", - event.sessionState - ]); - switch (event.sessionState) { - case cast.framework.SessionState.SESSION_STARTED: - castSession = cast.framework.CastContext.getInstance().getCurrentSession(); - castSession.addMessageListener("urn:x-cast:zoff.me", chromecastListener) - updateChromecastMetadata(); - //chrome.cast.Image('https://img.youtube.com/vi/'+video_id+'/mqdefault.jpg'); - chromecastAvailable = true; - paused = false; - mobile_beginning = false; + ); - //castSession.sendMessage("urn:x-cast:zoff.me", {type: "loadVideo", start: Player.np.start, end: Player.np.end, videoId: video_id, seekTo: _seekTo, channel: chan.toLowerCase(), source: videoSource, thumbnail: Player.np.thumbnail}) - castSession.sendMessage("urn:x-cast:zoff.me", {type: "nextVideo", videoId: full_playlist[0].id, title: full_playlist[0].title, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}); - castSession.sendMessage("urn:x-cast:zoff.me", {type: "chromecastInfoShow", value: chromecastInfoShow}); - loadChromecastVideo(); - if(window.location.hostname.indexOf("zoff.me") > -1 && !offline && window.location.hostname.indexOf("localhost") == -1) { - socket.emit("get_id"); - } - hide_native(1); - if(Helper.mobilecheck()) { - Player.playVideo(); - } - Helper.css("#channel-load", "display", "none"); - Helper.addClass('.castButton', 'castButton-white-active'); - Helper.css("#playpause", "visibility", "visible"); - Helper.css("#playpause", "pointer-events", "all"); - break; - case cast.framework.SessionState.SESSION_RESUMED: - castSession = cast.framework.CastContext.getInstance().getCurrentSession(); - castSession.addMessageListener("urn:x-cast:zoff.me", chromecastListener); - updateChromecastMetadata(); - //chrome.cast.Image('https://img.youtube.com/vi/'+video_id+'/mqdefault.jpg'); - chromecastAvailable = true; - paused = false; - mobile_beginning = false; - - if(window.location.hostname.indexOf("zoff.me") > -1 && !offline && window.location.hostname.indexOf("localhost") == -1) { - socket.emit("get_id"); - } - castSession.sendMessage("urn:x-cast:zoff.me", {type: "chromecastInfoShow", value: chromecastInfoShow}); - loadChromecastVideo(); - //castSession.sendMessage("urn:x-cast:zoff.me", {type: "loadVideo", start: Player.np.start, end: Player.np.end, videoId: video_id, seekTo: _seekTo, channel: chan.toLowerCase(), source: videoSource, thumbnail: Player.np.thumbnail}) - castSession.sendMessage("urn:x-cast:zoff.me", {type: "nextVideo", videoId: full_playlist[0].id, title: full_playlist[0].title, source: full_playlist[0].source, thumbnail: full_playlist[0].thumbnail}) - hide_native(1); - Helper.css("#channel-load", "display", "none"); - Helper.addClass('.castButton', 'castButton-white-active'); - Helper.css("#playpause", "visibility", "visible"); - Helper.css("#playpause", "pointer-events", "all"); - break; - case cast.framework.SessionState.SESSION_ENDED: - chromecastAvailable = false; - hide_native(0); - break; + context.addEventListener( + cast.framework.CastContextEventType.CAST_STATE_CHANGED, + function(event) { + Helper.log(["cast state", event.castState]); + if (event.castState == "NOT_CONNECTED") { + Helper.css(".castButton", "display", "block"); + Helper.addClass(".volume-container", "volume-container-cast"); + cast_ready_connect = true; + var _chSeen; + try { + _chSeen = localStorage.getItem("_chSeen"); + } catch (e) { + _chSeen = false; } - }); - - context.addEventListener(cast.framework.CastContextEventType.CAST_STATE_CHANGED, function(event){ - Helper.log([ - "cast state", - event.castState - ]); - if(event.castState == "NOT_CONNECTED"){ - Helper.css(".castButton", "display", "block"); - Helper.addClass(".volume-container", "volume-container-cast"); - cast_ready_connect = true; - var _chSeen; - try { - _chSeen = localStorage.getItem("_chSeen"); - } catch(e){ - _chSeen = false; - } - /*if((!_chSeen || _chSeen != "seen") && !client) { + /*if((!_chSeen || _chSeen != "seen") && !client) { Helper.css(".castButton", "display", "block"); showDiscovery = true; var elem = document.querySelector('.tap-target'); @@ -424,398 +480,478 @@ initializeCastApi = function() { } catch(e){} Helper.removeClass('.castButton', 'castButton-white-active'); }*/ - Helper.removeClass('.castButton', 'castButton-white-active'); - } else if(event.castState == "NO_DEVICES_AVAILABLE"){ - cast_ready_connect = false; - Helper.removeClass(".volume-container", "volume-container-cast"); - } - }); - - if(context.getCastState() == "NOT_CONNECTED") { - Helper.css(".castButton", "display", "block"); - Helper.removeClass('.castButton', 'castButton-white-active'); - cast_ready_connect = true; + Helper.removeClass(".castButton", "castButton-white-active"); + } else if (event.castState == "NO_DEVICES_AVAILABLE") { + cast_ready_connect = false; + Helper.removeClass(".volume-container", "volume-container-cast"); + } } + ); + + if (context.getCastState() == "NOT_CONNECTED") { + Helper.css(".castButton", "display", "block"); + Helper.removeClass(".castButton", "castButton-white-active"); + cast_ready_connect = true; + } }; function addDynamicListeners() { - addListener("click", ".preview-embed", function(event) { - this.preventDefault(); - if(document.querySelector(".embed-preview").innerHTML == "") { - document.querySelector(".preview-embed").innerText = "Stop"; - previewing = true; - document.querySelector(".embed-preview").innerHTML = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - } else { - previewing = false; - document.querySelector(".preview-embed").innerText = "Preview"; - document.querySelector(".embed-preview").innerHTML = ""; - } + addListener("click", ".preview-embed", function(event) { + this.preventDefault(); + if (document.querySelector(".embed-preview").innerHTML == "") { + document.querySelector(".preview-embed").innerText = "Stop"; + previewing = true; + document.querySelector(".embed-preview").innerHTML = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + } else { + previewing = false; + document.querySelector(".preview-embed").innerText = "Preview"; + document.querySelector(".embed-preview").innerHTML = ""; + } + }); + + if (Helper.mobilecheck()) { + addListener("click", "#refresh_mobile", function(event) { + this.preventDefault(); + clearIntelligentQueue(); + before_toast(); }); - if(Helper.mobilecheck()) { - addListener("click", "#refresh_mobile", function(event) { - this.preventDefault(); - clearIntelligentQueue(); - before_toast(); - }); + addListener("click", "#dont_refresh_list", function(event) { + this.preventDefault(); + before_toast(); + }); + } - addListener("click", "#dont_refresh_list", function(event) { - this.preventDefault(); - before_toast(); + addListener("click", "#player_overlay", function(event) { + if (chromecastAvailable) { + Player.playPauseVideo(); + } + }); + + addListener("click", ".info_change_button", function(event) { + this.preventDefault(); + M.Modal.getInstance(document.querySelector("#channel_info")).open(); + }); + + addListener("click", "#hide-playlist", function(event) { + this.preventDefault(); + fullVideo(!hiddenPlaylist); + }); + + addListener("click", "#bitcoin-address", function(event) { + var copyTextarea = document.querySelector("#bitcoin-address"); + copyTextarea.select(); + var successful = document.execCommand("copy"); + if (successful) { + M.toast({ + html: "Copied!", + displayLength: 2000, + classes: "green lighten" + }); + } else { + M.toast({ + html: "Error copying..", + displayLength: 2000, + classes: "red lighten" + }); + } + }); + + addListener("click", "#ethereum-address", function(event) { + var copyTextarea = document.querySelector("#ethereum-address"); + copyTextarea.select(); + var successful = document.execCommand("copy"); + if (successful) { + M.toast({ + html: "Copied!", + displayLength: 2000, + classes: "green lighten" + }); + } else { + M.toast({ + html: "Error copying..", + displayLength: 2000, + classes: "red lighten" + }); + } + }); + + addListener("click", ".prev-results-button", pagination_results); + addListener("click", ".next-results-button", pagination_results); + + addListener("click", "#settings", function(event) { + var sidenavElem = document.getElementsByClassName("sidenav")[0]; + if (!M.Sidenav.getInstance(document.querySelector(".sidenav")).isOpen) { + M.Sidenav.getInstance(sidenavElem).open(); + } else { + M.Sidenav.getInstance(sidenavElem).close(); + } + }); + + addListener("click", ".accept-delete", function(event) { + this.preventDefault(); + emit("delete_all", { channel: chan.toLowerCase() }); + M.Modal.getInstance(document.getElementById("delete_song_alert")).close(); + }); + + addListener("click", "#chat_submit", function(event) { + this.preventDefault(); + this.stopPropagation(); + Chat.chat(document.getElementById("chatForm").input); + document.getElementById("chat_submit").focus(); + //return true; + //document.getElementById("chatForm").submit(); + }); + + addListener("click", "#chat_help", function(event) { + this.preventDefault(), this.stopPropagation(); + document.getElementById("text-chat-input").value = "/help"; + Chat.chat(document.getElementById("chatForm").input); + document.getElementById("chat_submit").focus(); + }); + + addListener("click", "#offline-mode", function(event) { + this.preventDefault(); + if (!Crypt.get_offline()) { + change_offline(true, offline); + } else { + change_offline(false, offline); + } + }); + + addListener("click", ".description_input_send", function(event) { + this.preventDefault(); + sendDescription(); + }); + + addListener("click", ".rules_input_send", function(event) { + this.preventDefault(); + sendRules(); + }); + + addListener("click", ".thumbnail_input_send", function(event) { + this.preventDefault(); + sendThumbnail(); + }); + + addListener("submit", "#thumbnail_input_form", function(event) { + this.preventDefault(); + sendThumbnail(); + }); + + addListener("submit", "#description_input_form", function(event) { + this.preventDefault(); + sendDescription(); + }); + + addListener("submit", "#rules_input_form", function(event) { + this.preventDefault(); + sendRules(); + }); + + addListener("click", "#playpause-overlay", function() { + if (document.getElementById("play-overlay").classList.contains("hide")) { + Player.pauseVideo(); + Helper.toggleClass("#play-overlay", "hide"); + Helper.toggleClass("#pause-overlay", "hide"); + } else if ( + document.getElementById("pause-overlay").classList.contains("hide") + ) { + Player.playVideo(); + Helper.toggleClass("#play-overlay", "hide"); + Helper.toggleClass("#pause-overlay", "hide"); + } + }); + + addListener("click", "#cookieok", function(e) { + this.preventDefault(); + M.Toast.getInstance(e.parentElement).dismiss(); + try { + localStorage.ok_cookie = true; + } catch (e) {} + }); + + addListener("click", "#cookieinfo", function(e) { + this.preventDefault(); + M.Modal.init(document.getElementById("cookie")); + M.Modal.getInstance(document.getElementById("cookie")).open(); + }); + + addListener("click", ".connect_error", function(event) { + this.preventDefault(); + M.Toast.getInstance(this.parentElement).dismiss(); + }); + + addListener("click", ".extra-button-search", function(e) { + this.preventDefault(); + document.getElementById("search").value = e.getAttribute("data-text"); + document.querySelector(".song-title").click(); + Search.soundcloudSearch(e.getAttribute("data-text")); + Search.search(e.getAttribute("data-text")); + document.getElementById("search").focus(); + }); + + addListener("click", ".extra-button-delete", function(e) { + this.preventDefault(); + e.parentElement.remove(); + if ( + document.querySelector(".not-imported-container").children.length === 0 + ) { + Helper.toggleClass(".not-imported", "hide"); + } + }); + + addListener("click", "#context-menu-overlay", function(event) { + Helper.addClass(".context-menu-root", "hide"); + Helper.addClass("#context-menu-overlay", "hide"); + Helper.addClass(".context-menu-root", "data-id", ""); + }); + + addListener("click", ".copy-context-menu", function(e) { + this.preventDefault(); + var that = e; + var parent = that.parentElement; + var id = parent.getAttribute("data-id"); + if (id != "") { + Helper.css(".copy_video_id", "display", "block"); + if (parent.getAttribute("data-source") == "soundcloud") { + Helper.setHtml( + ".copy_video_id", + "https://api.soundcloud.com/tracks/" + id + ); + } else if (parent.getAttribute("data-source") == "youtube") { + Helper.setHtml( + ".copy_video_id", + "https://www.youtube.com/watch?v=" + id + ); + } + var copyTextarea = document.querySelector(".copy_video_id"); + copyTextarea.select(); + var successful = document.execCommand("copy"); + if (successful) { + M.toast({ + html: "Copied!", + displayLength: 2000, + classes: "green lighten" }); + } else { + M.toast({ + html: "Error copying..", + displayLength: 2000, + classes: "red lighten" + }); + } + Helper.css(".copy_video_id", "display", "none"); } - addListener("click", "#player_overlay", function(event) { - if(chromecastAvailable) { - Player.playPauseVideo(); - } - }); + Helper.addClass(".context-menu-root", "hide"); + Helper.addClass("#context-menu-overlay", "hide"); + document + .getElementsByClassName("context-menu-root")[0] + .setAttribute("data-id", ""); + }); - addListener("click", ".info_change_button", function(event) { - this.preventDefault(); - M.Modal.getInstance(document.querySelector("#channel_info")).open(); - }); + addListener("click", ".find-context-menu", function(e) { + this.preventDefault(); + var that = e; + if (that.classList.contains("context-menu-disabled")) { + return; + } + var parent = that.parentElement; + var id = parent.getAttribute("data-id"); + var thisTitle = document.getElementById(id).children[0].title; + document.querySelector(".song-title").click(); + Search.soundcloudSearch(thisTitle); + Search.search(id, false, true); + document.getElementById("search").focus(); + Helper.addClass(".context-menu-root", "hide"); + Helper.addClass("#context-menu-overlay", "hide"); + document + .getElementsByClassName("context-menu-root")[0] + .setAttribute("data-id", ""); + }); - addListener("click", "#hide-playlist", function(event) { - this.preventDefault(); - fullVideo(!hiddenPlaylist); - }); + addListener("click", ".playlist-search-button", function(e) { + this.preventDefault(); + Helper.toggleClass("#find_div", "hide"); + document.getElementById("find_input").value = ""; + document.getElementById("find_input").focus(); + Helper.removeClass(".highlight", "highlight"); + found_array = []; + found_array_index = 0; + find_word = ""; + }); + addListener("click", "#open_advanced_filter", function(e) { + this.preventDefault(); + M.Modal.getInstance(document.getElementById("advanced_filter")).open(); + ga("send", "event", "button-click", "advanced_filter"); + }); - addListener("click", "#bitcoin-address", function(event) { - var copyTextarea = document.querySelector('#bitcoin-address'); - copyTextarea.select(); - var successful = document.execCommand('copy'); - if(successful) { - M.toast({html: "Copied!", displayLength: 2000, classes: "green lighten"}); - } else { - M.toast({html: "Error copying..", displayLength: 2000, classes: "red lighten"}); - } - }); + addListener("submit", "#filter-form", function(e) { + this.preventDefault(); + filterPlaylistElements(1); + }); - addListener("click", "#ethereum-address", function(event) { - var copyTextarea = document.querySelector('#ethereum-address'); - copyTextarea.select(); - var successful = document.execCommand('copy'); - if(successful) { - M.toast({html: "Copied!", displayLength: 2000, classes: "green lighten"}); - } else { - M.toast({html: "Error copying..",displayLength: 2000, classes: "red lighten"}); - } - }); + addListener("click", ".submit-filter-search", function(e) { + this.preventDefault(); + filterPlaylistElements(1); + }); - addListener("click", ".prev-results-button", pagination_results); - addListener("click", ".next-results-button", pagination_results); + addListener("click", ".next-filter", function(e) { + this.preventDefault(); + var page = e.getAttribute("data-page"); + page = parseInt(page); + if (page == undefined || isNaN(page)) return; + e.classList.remove("next-filter"); + e.classList.remove("orange"); + e.className += " disabled"; + filterPlaylistElements(page); + }); - addListener("click", "#settings", function(event) { - var sidenavElem = document.getElementsByClassName("sidenav")[0]; - if(!M.Sidenav.getInstance(document.querySelector(".sidenav")).isOpen) { - M.Sidenav.getInstance(sidenavElem).open(); - } else { - M.Sidenav.getInstance(sidenavElem).close(); - } - }); + addListener("click", ".prev-filter", function(e) { + this.preventDefault(); + var page = e.getAttribute("data-page"); + page = parseInt(page); + if (page == undefined || isNaN(page)) return; + e.classList.remove("prev-filter"); + e.classList.remove("orange"); + e.className += " disabled"; + filterPlaylistElements(page); + }); - addListener("click", ".accept-delete", function(event) { - this.preventDefault(); - emit("delete_all", {channel: chan.toLowerCase()}); - M.Modal.getInstance(document.getElementById("delete_song_alert")).close(); - }); + addListener("click", ".delete-context-menu", function(e) { + var that = e; + if (that.classList.contains("context-menu-disabled")) { + return; + } + var parent = that.parentElement; + var id = parent.getAttribute("data-id"); + var suggested = parent.getAttribute("data-suggested"); + if (suggested == "true") { + number_suggested = number_suggested - 1; + if (number_suggested < 0) number_suggested = 0; - addListener("click", "#chat_submit", function(event){ - this.preventDefault(); - this.stopPropagation(); - Chat.chat(document.getElementById("chatForm").input); - document.getElementById("chat_submit").focus(); - //return true; - //document.getElementById("chatForm").submit(); - }); + var to_display = number_suggested > 9 ? "9+" : number_suggested; + if (to_display == 0) { + Helper.addClass( + document.querySelector(".suggested-link span.badge.new.white"), + "hide" + ); + } - addListener("click", "#chat_help", function(event) { - this.preventDefault(), - this.stopPropagation(); - document.getElementById("text-chat-input").value = "/help"; - Chat.chat(document.getElementById("chatForm").input); - document.getElementById("chat_submit").focus(); - }); + Helper.setHtml( + document.querySelector(".suggested-link span.badge.new.white"), + to_display + ); + } - addListener("click", "#offline-mode", function(event){ - this.preventDefault(); - if(!Crypt.get_offline()){ - change_offline(true, offline); - } else{ - change_offline(false, offline); - } - }); + List.vote(id, "del"); + Helper.addClass(".context-menu-root", "hide"); + Helper.addClass("#context-menu-overlay", "hide"); + document + .getElementsByClassName("context-menu-root")[0] + .setAttribute("data-id", ""); + }); - addListener("click", ".description_input_send", function(event) { - this.preventDefault(); - sendDescription(); - }); + addListener("click", "#closePlayer", function(event) { + this.preventDefault(); + socket.emit("change_channel"); + try { + if (chromecastAvailable) { + var castSession = cast.framework.CastContext.getInstance().getCurrentSession(); + castSession.endSession(true); + } + Player.player.destroy(); + Helper.toggleClass("#player_bottom_overlay", "hide"); + Helper.removeElement("#player"); + Player.soundcloud_player.unbind("finish", Player.soundcloudFinish); + Player.soundcloud_player.unbind("pause", Player.soundcloudPause); + Player.soundcloud_player.unbind("play", Player.soundcloudPlay); + Player.soundcloud_player.kill(); + } catch (error) {} + if (scUsingWidget) document.querySelector("#sc_player").innerHTML = ""; + socket.removeEventListener("np"); + socket.removeEventListener("id"); + socket.removeEventListener(id); + previousSoundcloud = null; + Helper.removeElement("#soundcloud_container"); + Helper.removeElement("#alreadychannel"); + Player.player = ""; + document.title = "Zoff - the shared YouTube based radio"; + Helper.removeElement("#closePlayer"); + Helper.removeElement("#main-row"); + }); - addListener("click", ".rules_input_send", function(event) { - this.preventDefault(); - sendRules(); - }); + addListener("change", "#width_embed", function(event) { + var that = this.target; + embed_width = that.value; + if (previewing) + document.querySelector(".embed-preview").innerHTML = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + document.getElementById("embed-area").value = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + }); - addListener("click", ".thumbnail_input_send", function(event) { - this.preventDefault(); - sendThumbnail(); - }); + addListener("change", "#height_embed", function(event) { + var that = this.target; + embed_height = that.value; + if (previewing) + document.querySelector(".embed-preview").innerHTML = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + document.getElementById("embed-area").value = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + }); - addListener("submit", "#thumbnail_input_form", function(event){ - this.preventDefault(); - sendThumbnail(); - }); + addListener("click", ".prev_page", function(event) { + //addListener("click", ".prev_page", function(event){ + this.preventDefault(); + List.dynamicContentPage(-1); + }); - addListener("submit", "#description_input_form", function(event){ - this.preventDefault(); - sendDescription(); - }); + addListener("click", ".modal-close", function(event) { + this.preventDefault(); + }); - addListener("submit", "#rules_input_form", function(event){ - this.preventDefault(); - sendRules(); - }); + addListener("click", "#player_overlay", function(event) { + if (videoSource == "soundcloud") { + Playercontrols.play_pause(); + } + }); - addListener("click", "#playpause-overlay", function(){ - if(document.getElementById("play-overlay").classList.contains("hide")){ - Player.pauseVideo(); - Helper.toggleClass("#play-overlay", "hide"); - Helper.toggleClass("#pause-overlay", "hide"); - } else if(document.getElementById("pause-overlay").classList.contains("hide")){ - Player.playVideo(); - Helper.toggleClass("#play-overlay", "hide"); - Helper.toggleClass("#pause-overlay", "hide"); - } - }); - - addListener("click", '#cookieok', function(e) { - this.preventDefault(); - M.Toast.getInstance(e.parentElement).dismiss(); - try { - localStorage.ok_cookie = true; - } catch(e){} - }); - - addListener("click", "#cookieinfo", function(e) { - this.preventDefault(); - M.Modal.init(document.getElementById("cookie")); - M.Modal.getInstance(document.getElementById("cookie")).open(); - }); - - addListener("click", ".connect_error", function(event){ - this.preventDefault(); - M.Toast.getInstance(this.parentElement).dismiss(); - }); - - addListener("click", ".extra-button-search", function(e){ - this.preventDefault(); - document.getElementById("search").value = e.getAttribute("data-text"); - document.querySelector(".song-title").click(); - Search.soundcloudSearch(e.getAttribute("data-text")); - Search.search(e.getAttribute("data-text")); - document.getElementById("search").focus(); - }); - - addListener("click", ".extra-button-delete", function(e){ - this.preventDefault(); - e.parentElement.remove(); - if(document.querySelector(".not-imported-container").children.length === 0){ - Helper.toggleClass(".not-imported", "hide"); - } - }); - - addListener("click", "#context-menu-overlay", function(event) { - Helper.addClass(".context-menu-root", "hide"); - Helper.addClass("#context-menu-overlay", "hide"); - Helper.addClass(".context-menu-root", "data-id", ""); - }); - - addListener("click", ".copy-context-menu", function(e) { - this.preventDefault(); - var that = e; - var parent = that.parentElement; - var id = parent.getAttribute("data-id"); - if(id != "") { - Helper.css(".copy_video_id", "display", "block"); - if(parent.getAttribute("data-source") == "soundcloud") { - Helper.setHtml(".copy_video_id", "https://api.soundcloud.com/tracks/" + id); - } else if(parent.getAttribute("data-source") == "youtube") { - Helper.setHtml(".copy_video_id", "https://www.youtube.com/watch?v=" + id); - } - var copyTextarea = document.querySelector('.copy_video_id'); - copyTextarea.select(); - var successful = document.execCommand('copy'); - if(successful) { - M.toast({html: "Copied!", displayLength: 2000, classes: "green lighten"}); - } else { - M.toast({html: "Error copying..", displayLength: 2000, classes: "red lighten"}); - } - Helper.css(".copy_video_id", "display", "none"); - } - - Helper.addClass(".context-menu-root", "hide"); - Helper.addClass("#context-menu-overlay", "hide"); - document.getElementsByClassName("context-menu-root")[0].setAttribute("data-id", ""); - }); - - addListener("click", ".find-context-menu", function(e) { - this.preventDefault(); - var that = e; - if(that.classList.contains("context-menu-disabled")) { - return; - } - var parent = that.parentElement; - var id = parent.getAttribute("data-id"); - var thisTitle = document.getElementById(id).children[0].title; - document.querySelector(".song-title").click(); - Search.soundcloudSearch(thisTitle); - Search.search(id, false, true); - document.getElementById("search").focus(); - Helper.addClass(".context-menu-root", "hide"); - Helper.addClass("#context-menu-overlay", "hide"); - document.getElementsByClassName("context-menu-root")[0].setAttribute("data-id", ""); - }); - - addListener("click", ".playlist-search-button", function(e) { - this.preventDefault(); - Helper.toggleClass("#find_div", "hide"); - document.getElementById("find_input").value = ""; - document.getElementById("find_input").focus(); - Helper.removeClass(".highlight", "highlight"); - found_array = []; - found_array_index = 0; - find_word = ""; - }); - - addListener("click", "#open_advanced_filter", function(e) { - this.preventDefault(); - M.Modal.getInstance(document.getElementById("advanced_filter")).open(); - ga('send', 'event', "button-click", "advanced_filter"); - }); - - addListener("submit", "#filter-form", function(e) { - this.preventDefault(); - filterPlaylistElements(1); - }); - - addListener("click", ".submit-filter-search", function(e) { - this.preventDefault(); - filterPlaylistElements(1); - }); - - addListener("click", ".next-filter", function(e) { - this.preventDefault(); - var page = e.getAttribute("data-page"); - page = parseInt(page); - if(page == undefined || isNaN(page)) return; - e.classList.remove("next-filter"); - e.classList.remove("orange"); - e.className += " disabled"; - filterPlaylistElements(page); - }); - - addListener("click", ".prev-filter", function(e) { - this.preventDefault(); - var page = e.getAttribute("data-page"); - page = parseInt(page); - if(page == undefined || isNaN(page)) return; - e.classList.remove("prev-filter"); - e.classList.remove("orange"); - e.className += " disabled"; - filterPlaylistElements(page); - }); - - addListener("click", ".delete-context-menu", function(e) { - var that = e; - if(that.classList.contains("context-menu-disabled")) { - return; - } - var parent = that.parentElement; - var id = parent.getAttribute("data-id"); - var suggested = parent.getAttribute("data-suggested"); - - if(suggested == "true") { - number_suggested = number_suggested - 1; - if(number_suggested < 0) number_suggested = 0; - - var to_display = number_suggested > 9 ? "9+" : number_suggested; - if(to_display == 0){ - Helper.addClass(document.querySelector(".suggested-link span.badge.new.white"), "hide"); - } - - Helper.setHtml(document.querySelector(".suggested-link span.badge.new.white"), to_display); - } - - List.vote(id, "del"); - Helper.addClass(".context-menu-root", "hide"); - Helper.addClass("#context-menu-overlay", "hide"); - document.getElementsByClassName("context-menu-root")[0].setAttribute("data-id", ""); - }) - - addListener("click", "#closePlayer", function(event){ - this.preventDefault(); - socket.emit("change_channel"); - try{ - if(chromecastAvailable){ - var castSession = cast.framework.CastContext.getInstance().getCurrentSession(); - castSession.endSession(true); - } - Player.player.destroy(); - Helper.toggleClass("#player_bottom_overlay", "hide"); - Helper.removeElement("#player"); - Player.soundcloud_player.unbind("finish", Player.soundcloudFinish); - Player.soundcloud_player.unbind("pause", Player.soundcloudPause); - Player.soundcloud_player.unbind("play", Player.soundcloudPlay); - Player.soundcloud_player.kill(); - } catch(error){} - if(scUsingWidget) document.querySelector("#sc_player").innerHTML = ""; - socket.removeEventListener("np"); - socket.removeEventListener("id"); - socket.removeEventListener(id); - previousSoundcloud = null; - Helper.removeElement("#soundcloud_container"); - Helper.removeElement("#alreadychannel"); - Player.player = ""; - document.title = "Zoff - the shared YouTube based radio"; - Helper.removeElement("#closePlayer"); - Helper.removeElement("#main-row"); - }); - - - addListener("change", "#width_embed", function(event) { - var that = this.target; - embed_width = that.value; - if(previewing) document.querySelector(".embed-preview").innerHTML = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - document.getElementById("embed-area").value = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - }); - - addListener("change", "#height_embed", function(event) { - var that = this.target; - embed_height = that.value; - if(previewing) document.querySelector(".embed-preview").innerHTML = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - document.getElementById("embed-area").value = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - }); - - addListener("click", ".prev_page", function(event) { - //addListener("click", ".prev_page", function(event){ - this.preventDefault(); - List.dynamicContentPage(-1); - }); - - addListener("click", ".modal-close", function(event){ - this.preventDefault(); - }); - - addListener("click", "#player_overlay", function(event) { - if(videoSource == "soundcloud") { - Playercontrols.play_pause(); - } - }); - - /* + /* addListener("change", ".password_protected", function(event) { this.preventDefault(); if(this.checked) { @@ -828,916 +964,1159 @@ function addDynamicListeners() { } });*/ - addListener("submit", "#user-password-channel-form", function(event) { - this.preventDefault(); - if(user_auth_started) { - temp_user_pass = document.getElementById("user-pass-input").value; + addListener("submit", "#user-password-channel-form", function(event) { + this.preventDefault(); + if (user_auth_started) { + temp_user_pass = document.getElementById("user-pass-input").value; - document.getElementById("user-pass-input").value = ""; - socket.emit("list", {version: parseInt(_VERSION), channel: chan.toLowerCase(), pass: Crypt.crypt_pass(temp_user_pass)}); - } else { - M.Modal.getInstance(document.getElementById("user_password")).close(); - userpass = document.getElementById("user-pass-input").value; - user_change_password = false; - document.getElementById("user-pass-input").value = ""; - Admin.save(true); - } - }); + document.getElementById("user-pass-input").value = ""; + socket.emit("list", { + version: parseInt(_VERSION), + channel: chan.toLowerCase(), + pass: Crypt.crypt_pass(temp_user_pass) + }); + } else { + M.Modal.getInstance(document.getElementById("user_password")).close(); + userpass = document.getElementById("user-pass-input").value; + user_change_password = false; + document.getElementById("user-pass-input").value = ""; + Admin.save(true); + } + }); - addListener("click", ".change_user_pass_btn", function(event) { - this.preventDefault(); - user_change_password = true; + addListener("click", ".change_user_pass_btn", function(event) { + this.preventDefault(); + user_change_password = true; + M.Modal.getInstance(document.getElementById("user_password")).open(); + document.getElementById("user-pass-input").focus(); + }); + + addListener("contextmenu", "#context-menu-overlay", function(event) { + this.preventDefault(); + }); + + addListener("click", ".submit-user-password", function(event) { + this.preventDefault(); + if (user_auth_started) { + temp_user_pass = document.getElementById("user-pass-input").value; + document.getElementById("user-pass-input").value = ""; + socket.emit("list", { + version: parseInt(_VERSION), + channel: chan.toLowerCase(), + pass: Crypt.crypt_pass(temp_user_pass) + }); + } else { + M.Modal.getInstance(document.getElementById("user_password")).close(); + userpass = document.getElementById("user-pass-input").value; + user_change_password = false; + document.getElementById("user-pass-input").value = ""; + Admin.save(true); + } + }); + + addListener("click", "#abort-channel-login", function(event) { + this.preventDefault(); + if (user_auth_started) { + clearTimeout(durationTimeout); + Player.stopInterval = true; + user_auth_avoid = true; + if (!Helper.mobilecheck()) { + Helper.tooltip(".castButton", "destroy"); + Helper.tooltip("#viewers", "destroy"); + Helper.tooltip("#addToOtherList", "destroy"); + //$('.castButton-unactive').tooltip("destroy"); + Helper.tooltip("#offline-mode", "destroy"); + Helper.tooltip("#admin-lock", "destroy"); + } + window.history.pushState("to the frontpage!", "Title", "/"); + Channel.onepage_load(); + user_auth_started = false; + } else { + document.getElementById("user-pass-input").value = ""; + if (!user_change_password) { + document.getElementsByClassName( + "password_protected" + )[0].checked = false; + } + user_change_password = false; + } + }); + + addListener("click", ".delete-all-songs", function(event) { + this.preventDefault(); + M.Modal.getInstance(document.getElementById("delete_song_alert")).open(); + }); + + addListener("click", ".extra-add-text", function(e) { + try { + e.select(); + } catch (e) {} + }); + + addListener("click", ".next_page", function(event) { + this.preventDefault(); + List.dynamicContentPage(1); + }); + + addListener("click", ".last_page", function(event) { + this.preventDefault(); + List.dynamicContentPage(10); + }); + + addListener("click", ".first_page", function(event) { + this.preventDefault(); + List.dynamicContentPage(-10); + }); + + addListener("click", ".donate-button", function(event) { + this.preventDefault(); + M.Modal.init(document.getElementById("donate")); + ga("send", "event", "button-click", "donate"); + M.Modal.getInstance(document.getElementById("donate")).open(); + }); + + addListener("click", "#toast-container", function() { + before_toast(); + }); + + addListener("click", "#aprilfools", function() { + Helper.css(".mega", "-webkit-transform", "rotate(0deg)"); + Helper.css(".mega", "-moz-transform", "rotate(0deg)"); + }); + + addListener("change", "#view_channels_select", function(event) { + var that = this; + if (currently_showing_channels != parseInt(that.target.value)) { + Frontpage.populate_channels( + Frontpage.all_channels, + parseInt(that.target.value) == 1 ? true : false, + true + ); + } + currently_showing_channels = parseInt(that.target.value); + }); + + addListener("input", "#color_embed", function(e) { + var that = e; + color = "&color=" + that.value.substring(1); + document.getElementById("embed-area").value = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + }); + + addListener("click", ".chan-link", function(e) { + this.preventDefault(); + var href; + if (window.location.port != "") { + href = e.href.replace( + window.location.protocol + + "//" + + window.location.hostname + + ":" + + window.location.port + + "/", + "" + ); + } else { + href = e.href.replace( + window.location.protocol + "//" + window.location.hostname + "/", + "" + ); + } + Frontpage.to_channel(href, false); + }); + + addListener("click", ".listen-button", function(event) { + if (document.querySelector(".room-namer").value === "") { + this.preventDefault(); + Frontpage.to_channel( + Helper.encodeChannelName( + document.querySelector(".room-namer").getAttribute("placeholder") + ) + ); + } + }); + + addListener("submit", ".channel-finder", function(event) { + this.preventDefault(); + Frontpage.to_channel( + Helper.encodeChannelName(document.querySelector(".room-namer").value) + ); + return false; + }); + + addListener("change", ".backround_switch_class", function() { + if (document.getElementsByClassName("backround_switch_class")[0].checked) { + Crypt.set_background_color("dynamic"); + Helper.addClass(".background_color_container", "hide"); + } else { + Crypt.set_background_color( + document.querySelector("#background_color_choser").value + ); + Helper.removeClass(".background_color_container", "hide"); + } + ga("send", "event", "button-click", "color-change"); + }); + + addListener("change", "#background_color_choser", function() { + var _color = document.getElementById("background_color_choser").value; + if (!document.getElementsByClassName("backround_switch_class")[0].checked) { + Crypt.set_background_color(_color); + } + }); + + addListener("change", ".remote_switch_class", function() { + var enabled = document.getElementsByName("remote_switch")[0].checked; + Hostcontroller.change_enabled(enabled); + Crypt.set_remote(enabled); + }); + + addListener("change", ".intelligent_switch_class", function() { + var enabled = document.getElementsByName("intelligent_switch")[0].checked; + change_intelligent(enabled); + Crypt.set_intelligent_list_enabled(enabled); + if (enabled) { + toast("Enabled intelligent playlist!"); + } else { + toast("Disabled intelligent playlist."); + } + }); + + addListener("change", ".chromecast_info_display_class", function() { + chromecastInfoShow = document.getElementsByName( + "chromecast_info_display" + )[0].checked; + if (chromecastAvailable) { + castSession.sendMessage("urn:x-cast:zoff.me", { + type: "chromecastInfoShow", + value: chromecastInfoShow + }); + } + }); + + addListener("change", ".offline_switch_class", function() { + offline = document.getElementsByName("offline_switch")[0].checked; + change_offline(offline, !offline); + }); + + addListener("change", ".host_switch_class", function() { + var host = document.getElementsByName("host_switch")[0].checked; + enable_host_mode(host); + }); + + addListener("change", ".conf", function(e) { + this.preventDefault(); + if (e.classList.contains("password_protected")) { + if (e.checked) { M.Modal.getInstance(document.getElementById("user_password")).open(); document.getElementById("user-pass-input").focus(); - }); + } else { + userpass = ""; + Helper.addClass(".change_user_pass", "hide"); + Admin.save(true); + } + } else { + Admin.save(false); + } + }); - addListener("contextmenu", "#context-menu-overlay", function(event) { - this.preventDefault(); - }); + addListener("click", "#clickme", function() { + Player.playVideo(); + }); - addListener("click", ".submit-user-password", function(event) { - this.preventDefault(); - if(user_auth_started) { - temp_user_pass = document.getElementById("user-pass-input").value; - document.getElementById("user-pass-input").value = ""; - socket.emit("list", {version: parseInt(_VERSION), channel: chan.toLowerCase(), pass: Crypt.crypt_pass(temp_user_pass)}); + addListener("click", "#addToOtherList", function(event) { + this.preventDefault(); + Helper.toggleClass("#addToListInput", "hide"); + document.getElementById("other-list-name-add").focus(); + }); + + addListener("submit", "#addToOtherListForm", function(event) { + this.preventDefault(); + emit("add", { + offsiteAdd: true, + id: Player.np.id, + start: Player.np.start, + end: Player.np.end, + title: Player.np.title, + list: document.getElementById("other-list-name-add").value.toLowerCase(), + duration: Player.np.duration, + source: Player.np.source, + thumbnail: Player.np.thumbnail + }); + Helper.toggleClass("#addToListInput", "hide"); + document.getElementById("other-list-name-add").value = ""; + }); + + addListener("click", "#listExport", function(event) { + this.preventDefault(); + if (!youtube_authenticated) { + var nonce = Helper.randomString(29); + window.callback = function(data) { + access_token_data_youtube = data; + if (access_token_data_youtube.state == nonce) { + youtube_authenticated = true; + Helper.removeClass("#playlist_loader_export", "hide"); + Helper.addClass(".youtube_export_button", "hide"); + setTimeout(function() { + youtube_authenticated = false; + access_token_data_youtube = {}; + }, access_token_data_youtube.expires_in * 1000); + List.exportToYoutube(); } else { - M.Modal.getInstance(document.getElementById("user_password")).close(); - userpass = document.getElementById("user-pass-input").value; - user_change_password = false; - document.getElementById("user-pass-input").value = ""; - Admin.save(true); + access_token_data_youtube = ""; + console.error("Nonce doesn't match"); } - }); + youtube_window.close(); + window.callback = ""; + }; + youtube_window = window.open( + "/api/oauth#youtube=true&nonce=" + nonce, + "", + "width=600, height=600" + ); + } else { + List.exportToYoutube(); + } + }); - addListener("click", "#abort-channel-login", function(event) { - this.preventDefault(); - if(user_auth_started) { - clearTimeout(durationTimeout); - Player.stopInterval = true; - user_auth_avoid = true; - if(!Helper.mobilecheck()) { - Helper.tooltip('.castButton', "destroy"); - Helper.tooltip("#viewers", "destroy"); - Helper.tooltip('#addToOtherList', 'destroy'); - //$('.castButton-unactive').tooltip("destroy"); - Helper.tooltip("#offline-mode", "destroy"); - Helper.tooltip('#admin-lock', "destroy"); - } - window.history.pushState("to the frontpage!", "Title", "/"); - Channel.onepage_load(); - user_auth_started = false; - } else { - document.getElementById("user-pass-input").value = ""; - if(!user_change_password) { - document.getElementsByClassName("password_protected")[0].checked = false; - } - user_change_password = false; - } + addListener("click", ".export-soundcloud", function(event) { + this.preventDefault(); + window.SC_player = SC_player; + SC_player.connect({ display: "page" }).then(function() { + Helper.removeClass("#playlist_loader_export", "hide"); + Helper.addClass(".soundcloud-export-button", "hide"); + Helper.removeClass(".exported-list-container", "hide"); + List.exportToSoundCloud(); + delete window.SC_player; }); + }); - addListener("click", ".delete-all-songs", function(event){ - this.preventDefault(); - M.Modal.getInstance(document.getElementById("delete_song_alert")).open(); + addListener("click", ".export-spotify-auth", function(event) { + this.preventDefault(); + var nonce = Helper.randomString(29); + window.callback = function(data) { + access_token_data = data; + if (access_token_data.state == nonce) { + spotify_authenticated = true; + Channel.spotify_is_authenticated(true); + setTimeout(function() { + spotify_authenticated = false; + access_token_data = {}; + Channel.spotify_is_authenticated(false); + }, access_token_data.expires_in * 1000); + Helper.css(".spotify_export_button", "display", "none"); + List.exportToSpotify(); + } else { + access_token_data = {}; + console.error("States doesn't match"); + } + spotify_window.close(); + window.callback = ""; + }; + spotify_window = window.open( + "/api/oauth#spotify=true&nonce=" + nonce, + "", + "width=600, height=600" + ); + }); + + addListener("submit", "#listImport", function(event) { + this.preventDefault(); + var url = document + .getElementById("import") + .value.split("https://www.youtube.com/playlist?list="); + if (document.getElementById("import").value !== "" && url.length == 2) { + Search.importPlaylist(url[1]); + document.getElementById("import").value = ""; + document.getElementById("import").disabled = true; + Helper.addClass("#import", "hide"); + Helper.removeClass("#playlist_loader", "hide"); + + ga("send", "event", "import", "youtube"); + } else { + before_toast(); + M.toast({ + html: "It seems you've entered a invalid url.", + displayLength: 4000 + }); + } + document.getElementById("import").value = ""; + }); + + addListener("submit", "#listImportZoff", function(event) { + this.preventDefault(); + var new_channel = document.getElementById("import_zoff").value; + document.getElementById("import_zoff").value = ""; + ga("send", "event", "import", "zoff"); + if (new_channel == "") { + M.toast({ + html: "It seems you've entered a invalid channel-name.", + displayLength: 4000 + }); + return; + } + socket.emit("import_zoff", { + channel: chan.toLowerCase(), + new_channel: new_channel.toLowerCase() }); + }); - addListener("click", ".extra-add-text", function(e){ + addListener("click", ".import-zoff", function(event) { + this.preventDefault(); + Helper.addClass(".import-zoff-container", "hide"); + Helper.removeClass(".zoff_add_field", "hide"); + }); + + addListener("click", ".import-soundcloud", function(event) { + this.preventDefault(); + Helper.addClass(".soundcloud-import-button", "hide"); + Helper.removeClass(".soundcloud_authenticated", "hide"); + document.querySelector("#import_soundcloud").focus(); + }); + + addListener("submit", "#listImportSoundCloud", function(event) { + this.preventDefault(); + Helper.removeClass(".playlist_loader_soundcloud", "hide"); + Helper.addClass("#listImportSoundCloud", "hide"); + ga("send", "event", "import", "soundcloud"); + Helper.ajax({ + type: "POST", + headers: { + "Content-Type": "application/json" + }, + url: + "https://api.soundcloud.com/resolve/?url=" + + document.querySelector("#import_soundcloud").value + + "&limit=1&client_id=" + + api_key.soundcloud + + "&format=json&_status_code_map[200]=200", + success: function(data) { try { - e.select(); - } catch(e) {} - }); - - addListener("click", ".next_page", function(event){ - this.preventDefault(); - List.dynamicContentPage(1); - }); - - addListener("click", ".last_page", function(event){ - this.preventDefault(); - List.dynamicContentPage(10); - }); - - addListener("click", ".first_page", function(event){ - this.preventDefault(); - List.dynamicContentPage(-10); - }); - - addListener("click", ".donate-button", function(event) { - this.preventDefault(); - M.Modal.init(document.getElementById("donate")); - ga('send', 'event', "button-click", "donate"); - M.Modal.getInstance(document.getElementById("donate")).open(); - }); - - addListener("click", '#toast-container', function(){ - before_toast(); - }); - - - addListener("click", "#aprilfools", function(){ - Helper.css(".mega", "-webkit-transform", "rotate(0deg)"); - Helper.css(".mega", "-moz-transform", "rotate(0deg)"); - }); - - addListener("change", '#view_channels_select', function(event) { - var that = this; - if(currently_showing_channels != parseInt(that.target.value)) { - Frontpage.populate_channels(Frontpage.all_channels, (parseInt(that.target.value) == 1 ? true : false), true); - } - currently_showing_channels = parseInt(that.target.value); - }); - - addListener("input", '#color_embed', function(e){ - var that = e; - color = "&color=" + that.value.substring(1); - document.getElementById("embed-area").value = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - }); - - addListener("click", ".chan-link", function(e){ - this.preventDefault(); - var href = e.href.replace(window.location.protocol + "//" + window.location.hostname + "/", ""); - Frontpage.to_channel(href, false); - }); - - addListener("click", ".listen-button", function(event){ - if(document.querySelector(".room-namer").value === ""){ - this.preventDefault(); - Frontpage.to_channel(Helper.encodeChannelName(document.querySelector(".room-namer").getAttribute("placeholder"))); - } - }); - - addListener("submit", ".channel-finder", function(event){ - this.preventDefault(); - Frontpage.to_channel(Helper.encodeChannelName(document.querySelector(".room-namer").value)); - return false; - }); - - - addListener("change", '.backround_switch_class', function(){ - if(document.getElementsByClassName("backround_switch_class")[0].checked) { - Crypt.set_background_color("dynamic"); - Helper.addClass(".background_color_container", "hide"); - } else { - Crypt.set_background_color(document.querySelector("#background_color_choser").value); - Helper.removeClass(".background_color_container", "hide"); - } - ga('send', 'event', "button-click", "color-change"); - }); - - addListener("change", "#background_color_choser", function() { - var _color = document.getElementById("background_color_choser").value; - if(!document.getElementsByClassName("backround_switch_class")[0].checked) { - Crypt.set_background_color(_color); - } - }); - - addListener("change", '.remote_switch_class', function() - { - var enabled = document.getElementsByName("remote_switch")[0].checked; - Hostcontroller.change_enabled(enabled); - Crypt.set_remote(enabled); - }); - - addListener("change", '.intelligent_switch_class', function() - { - var enabled = document.getElementsByName("intelligent_switch")[0].checked; - change_intelligent(enabled); - Crypt.set_intelligent_list_enabled(enabled); - if(enabled) { - toast("Enabled intelligent playlist!"); - } else { - toast("Disabled intelligent playlist."); - } - }); - - addListener("change", '.chromecast_info_display_class', function() - { - chromecastInfoShow = document.getElementsByName("chromecast_info_display")[0].checked; - if(chromecastAvailable) { - castSession.sendMessage("urn:x-cast:zoff.me", {type: "chromecastInfoShow", value: chromecastInfoShow}); - } - }); - - addListener("change", '.offline_switch_class', function() - { - offline = document.getElementsByName("offline_switch")[0].checked; - change_offline(offline, !offline); - }); - - addListener("change", '.host_switch_class', function() - { - var host = document.getElementsByName("host_switch")[0].checked; - enable_host_mode(host); - }); - - addListener("change", '.conf', function(e) - { - this.preventDefault(); - if(e.classList.contains("password_protected")) { - if(e.checked) { - M.Modal.getInstance(document.getElementById("user_password")).open(); - document.getElementById("user-pass-input").focus(); - } else { - userpass = ""; - Helper.addClass(".change_user_pass", "hide"); - Admin.save(true); + var jsonData = JSON.parse(data); + var tracks = jsonData.tracks; + document.querySelector("#import_soundcloud").value = ""; + var addList = []; + for (var i = 0; i < tracks.length; i++) { + var song = tracks[i]; + var title = song.title; + if (title.indexOf(song.user.username) == -1) { + title = song.user.username + " - " + title; } - } else { - Admin.save(false); - } - }); + if (!song.streamable) { + var not_added_song = document.createElement("div"); + not_added_song.innerHTML = not_import_html; - addListener("click", "#clickme", function(){ - Player.playVideo(); - }); - - addListener("click", "#addToOtherList", function(event) { - this.preventDefault(); - Helper.toggleClass("#addToListInput", "hide"); - document.getElementById("other-list-name-add").focus(); - }); - - addListener("submit", "#addToOtherListForm", function(event) { - this.preventDefault(); - emit("add", {offsiteAdd: true, id: Player.np.id, start: Player.np.start, end: Player.np.end, title: Player.np.title, list: document.getElementById("other-list-name-add").value.toLowerCase(), duration: Player.np.duration, source: Player.np.source, thumbnail: Player.np.thumbnail}); - Helper.toggleClass("#addToListInput", "hide"); - document.getElementById("other-list-name-add").value = ""; - }); - - addListener("click", "#listExport", function(event){ - this.preventDefault(); - if(!youtube_authenticated){ - var nonce = Helper.randomString(29); - window.callback = function(data) { - access_token_data_youtube = data; - if(access_token_data_youtube.state == nonce){ - youtube_authenticated = true; - Helper.removeClass("#playlist_loader_export", "hide"); - Helper.addClass(".youtube_export_button", "hide"); - setTimeout(function(){ - youtube_authenticated = false; - access_token_data_youtube = {}; - }, access_token_data_youtube.expires_in * 1000); - List.exportToYoutube(); - - } else { - access_token_data_youtube = ""; - console.error("Nonce doesn't match"); - } - youtube_window.close(); - window.callback = ""; - }; - youtube_window = window.open("/api/oauth#youtube=true&nonce=" + nonce, "", "width=600, height=600"); - } else { - List.exportToYoutube(); - } - }); - - addListener("click", ".export-soundcloud", function(event) { - this.preventDefault(); - window.SC_player = SC_player; - SC_player.connect({"display":"page"}).then(function() { - Helper.removeClass("#playlist_loader_export", "hide"); - Helper.addClass(".soundcloud-export-button", "hide"); - Helper.removeClass(".exported-list-container", "hide"); - List.exportToSoundCloud(); - delete window.SC_player; - }); - }); - - addListener("click", ".export-spotify-auth", function(event){ - this.preventDefault(); - var nonce = Helper.randomString(29); - window.callback = function(data) { - access_token_data = data; - if(access_token_data.state == nonce){ - spotify_authenticated = true; - Channel.spotify_is_authenticated(true); - setTimeout(function(){ - spotify_authenticated = false; - access_token_data = {}; - Channel.spotify_is_authenticated(false); - }, access_token_data.expires_in * 1000); - Helper.css(".spotify_export_button", "display", "none"); - List.exportToSpotify(); - } else { - access_token_data = {}; - console.error("States doesn't match"); + not_added_song.querySelector(".extra-add-text").innerText = title; + not_added_song + .querySelector(".extra-add-text") + .setAttribute("title", title); + not_added_song + .querySelector(".extra-button-search") + .setAttribute("data-text", title); + document + .querySelector(".not-imported-container") + .insertAdjacentHTML("beforeend", not_added_song.innerHTML); + Helper.removeClass(".not-imported", "hide"); + continue; } - spotify_window.close(); - window.callback = ""; - }; - spotify_window = window.open("/api/oauth#spotify=true&nonce=" + nonce, "", "width=600, height=600"); - }); + var duration = Math.floor(song.duration / 1000); + //var secs=Search.durationToSeconds(duration); + var secs = duration; + if (longsongs == undefined) longsongs = true; + if ((longsongs != undefined && !longsongs) || secs < 720) { + var id = song.id; + //duration = duration.replace("PT","").replace("H","h ").replace("M","m ").replace("S","s"); + var thumb = song.artwork_url; + //var thumb = null; + if (thumb == null) thumb = song.waveform_url; - addListener("submit", "#listImport", function(event){ - this.preventDefault(); - var url = document.getElementById("import").value.split("https://www.youtube.com/playlist?list="); - if(document.getElementById("import").value !== "" && url.length == 2){ - Search.importPlaylist(url[1]); - document.getElementById("import").value = ""; - document.getElementById("import").disabled = true; - Helper.addClass("#import", "hide"); - Helper.removeClass("#playlist_loader", "hide"); + var songElement = { + id: song.id, + title: title, + duration: secs, + source: "soundcloud", + thumbnail: thumb + }; - ga('send', 'event', "import", "youtube"); - } else { - before_toast(); - M.toast({html: "It seems you've entered a invalid url.", displayLength: 4000}); - } - document.getElementById("import").value = ""; - }); - - addListener("submit", "#listImportZoff", function(event) { - this.preventDefault(); - var new_channel = document.getElementById("import_zoff").value; - document.getElementById("import_zoff").value = ""; - ga('send', 'event', "import", "zoff"); - if(new_channel == "") { - M.toast({html: "It seems you've entered a invalid channel-name.", displayLength: 4000}); - return; - } - socket.emit("import_zoff", {channel: chan.toLowerCase(), new_channel: new_channel.toLowerCase()}); - }); - - addListener("click", ".import-zoff", function(event) { - this.preventDefault(); - Helper.addClass(".import-zoff-container", "hide"); - Helper.removeClass(".zoff_add_field", "hide"); - }); - - addListener("click", ".import-soundcloud", function(event) { - this.preventDefault(); - Helper.addClass(".soundcloud-import-button", "hide"); - Helper.removeClass(".soundcloud_authenticated", "hide"); - document.querySelector("#import_soundcloud").focus(); - }); - - addListener("submit", "#listImportSoundCloud", function(event) { - this.preventDefault(); - Helper.removeClass(".playlist_loader_soundcloud", "hide"); - Helper.addClass("#listImportSoundCloud", "hide"); - ga('send', 'event', "import", "soundcloud"); - Helper.ajax({ - type: "POST", - headers: { - "Content-Type": "application/json" - }, - url: "https://api.soundcloud.com/resolve/?url=" + document.querySelector("#import_soundcloud").value + "&limit=1&client_id=" + api_key.soundcloud + "&format=json&_status_code_map[200]=200", - success: function(data){ - try { - var jsonData = JSON.parse(data); - var tracks = jsonData.tracks; - document.querySelector("#import_soundcloud").value = ""; - var addList = []; - for(var i = 0; i < tracks.length; i++) { - var song = tracks[i]; - var title=song.title; - if(title.indexOf(song.user.username) == -1) { - title = song.user.username + " - " + title; - } - if(!song.streamable) { - var not_added_song = document.createElement("div"); - not_added_song.innerHTML = not_import_html; - - not_added_song.querySelector(".extra-add-text").innerText = title; - not_added_song.querySelector(".extra-add-text").setAttribute("title", title); - not_added_song.querySelector(".extra-button-search").setAttribute("data-text", title); - document.querySelector(".not-imported-container").insertAdjacentHTML("beforeend", not_added_song.innerHTML); - Helper.removeClass(".not-imported", "hide"); - continue; - } - var duration=Math.floor(song.duration / 1000); - //var secs=Search.durationToSeconds(duration); - var secs = duration; - if(longsongs == undefined) longsongs = true; - if((longsongs != undefined && !longsongs) || secs<720){ - - var id=song.id; - //duration = duration.replace("PT","").replace("H","h ").replace("M","m ").replace("S","s"); - var thumb=song.artwork_url; - //var thumb = null; - if(thumb == null) thumb = song.waveform_url; - - var songElement = {id: song.id, title: title, duration: secs, source: "soundcloud", thumbnail: thumb}; - - addList.push(songElement); - } - } - if(addList.length > 0) { - socket.emit("addPlaylist", {channel: chan.toLowerCase(), songs: addList}); - } - Helper.addClass(".playlist_loader_soundcloud", "hide"); - Helper.removeClass("#listImportSoundCloud", "hide"); - } catch(e) { - Helper.addClass(".playlist_loader_soundcloud", "hide"); - Helper.removeClass("#listImportSoundCloud", "hide"); - } - }, - error: function(data) { - Helper.addClass(".playlist_loader_soundcloud", "hide"); - Helper.removeClass("#listImportSoundCloud", "hide"); - toast("If the list is private, you have to add the secret code at the end"); + addList.push(songElement); } - }); + } + if (addList.length > 0) { + socket.emit("addPlaylist", { + channel: chan.toLowerCase(), + songs: addList + }); + } + Helper.addClass(".playlist_loader_soundcloud", "hide"); + Helper.removeClass("#listImportSoundCloud", "hide"); + } catch (e) { + Helper.addClass(".playlist_loader_soundcloud", "hide"); + Helper.removeClass("#listImportSoundCloud", "hide"); + } + }, + error: function(data) { + Helper.addClass(".playlist_loader_soundcloud", "hide"); + Helper.removeClass("#listImportSoundCloud", "hide"); + toast( + "If the list is private, you have to add the secret code at the end" + ); + } }); + }); - addListener("submit", "#listImportSpotify", function(event){ - this.preventDefault(); - if(spotify_authenticated && document.getElementById("import_spotify").value !== ""){ - var url = document.getElementById("import_spotify").value.split("https://open.spotify.com/user/"); - if(url.length == 2) { - url = url[1].split("/"); - var user = url[0]; - var playlist_id = url[2]; - playlist_id = playlist_id.split("?")[0]; + addListener("submit", "#listImportSpotify", function(event) { + this.preventDefault(); + if ( + spotify_authenticated && + document.getElementById("import_spotify").value !== "" + ) { + var url = document + .getElementById("import_spotify") + .value.split("https://open.spotify.com/user/"); + if (url.length == 2) { + url = url[1].split("/"); + var user = url[0]; + var playlist_id = url[2]; + playlist_id = playlist_id.split("?")[0]; - document.getElementById("import_spotify").disabled = true; - Helper.addClass("#import_spotify", "hide"); - Helper.removeClass("#playlist_loader_spotify", "hide"); + document.getElementById("import_spotify").disabled = true; + Helper.addClass("#import_spotify", "hide"); + Helper.removeClass("#playlist_loader_spotify", "hide"); - ga('send', 'event', "import", "spotify"); + ga("send", "event", "import", "spotify"); - Search.importSpotifyPlaylist('https://api.spotify.com/v1/users/' + user + '/playlists/' + playlist_id + '/tracks'); - } else { - var url = document.getElementById("import_spotify").value.split("https://open.spotify.com/playlist/"); + Search.importSpotifyPlaylist( + "https://api.spotify.com/v1/users/" + + user + + "/playlists/" + + playlist_id + + "/tracks" + ); + } else { + var url = document + .getElementById("import_spotify") + .value.split("https://open.spotify.com/playlist/"); - if(url.length == 2) { - /*url = url[1].split("/"); + if (url.length == 2) { + /*url = url[1].split("/"); var user = url[0];*/ - var playlist_id = url[1]; - playlist_id = playlist_id.replace("?", ""); + var playlist_id = url[1]; + playlist_id = playlist_id.replace("?", ""); - document.getElementById("import_spotify").disabled = true; - Helper.addClass("#import_spotify", "hide"); - Helper.removeClass("#playlist_loader_spotify", "hide"); + document.getElementById("import_spotify").disabled = true; + Helper.addClass("#import_spotify", "hide"); + Helper.removeClass("#playlist_loader_spotify", "hide"); - ga('send', 'event', "import", "spotify"); + ga("send", "event", "import", "spotify"); - Search.importSpotifyPlaylist('https://api.spotify.com/v1/playlists/' + playlist_id + '/tracks'); - } else { - before_toast(); - M.toast({html: "It seems you've entered a invalid url.", displayLength: 4000}); - } - } - } - document.getElementById("import_spotify").value = ""; - }); - - addListener("change", "#autoplay", function(e) { - if(e.checked) embed_autoplay = "&autoplay=true"; - else embed_autoplay = "&autoplay=false"; - document.getElementById("embed-area").value = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - }); - - addListener("change", "#videoonly", function(e) { - if(e.checked) embed_videoonly = "&videoonly=true"; - else embed_videoonly = "&videoonly=false"; - if(previewing) document.querySelector(".embed-preview").innerHTML = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - document.getElementById("embed-area").value = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - }); - - addListener("change", "#localmode", function(e) { - if(e.checked) embed_localmode = "&localmode=true"; - else embed_localmode = "&localmode=false"; - if(previewing) document.querySelector(".embed-preview").innerHTML = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - document.getElementById("embed-area").value = embed_code(embed_autoplay, embed_width, embed_height, color, embed_videoonly, embed_localmode); - }); - - addListener("click", "#playbutton_remote", function(event) { - this.preventDefault(); - Mobile_remote.play_remote(); - }); - - addListener("click", "#pausebutton_remote", function(event) { - this.preventDefault(); - Mobile_remote.pause_remote(); - }); - - addListener("click", "#skipbutton_remote", function(event) { - this.preventDefault(); - Mobile_remote.skip_remote(); - }); - - addListener("click", ".skip_next_client", function(event) { - this.preventDefault(); - }); - - addListener("submit", "#remoteform", function(event) { - this.preventDefault(); - Mobile_remote.get_input(document.getElementById("remote_channel").value); - }); - - addListener("click", ".chat-tab-li", function() { - scrollChat(); - }); - - addListener("click", ".chat-tab", function(){ - document.getElementById("text-chat-input").focus(); - }); - - addListener("click", ".prev", function(event){ - this.preventDefault(); - List.skip(false); - }); - - addListener("click", ".skip", function(event){ - this.preventDefault(); - List.skip(true); - }); - - addListener("click", "#chan", function(event){ - this.preventDefault(); - List.show(); - }); - - addListener("submit", "#adminForm", function(event){ - this.preventDefault(); - Admin.pass_save(); - }); - - addListener("submit", "#strictSkipForm", function(event){ - this.preventDefault(); - Admin.update_strict_skip(document.getElementById("strict-input-number").value); - }); - - addListener("click", "#channel-share-modal", function(){ - M.Modal.getInstance(document.getElementById("channel-share-modal")).close(); - }); - - addListener("click", ".shareface", function(event) { - ga('send', 'event', "button-click", "share-facebook"); - }); - - addListener("click", ".android-image-link", function() { - ga('send', 'event', "button-click", "android-playstore-link"); - }); - - addListener("click", "#twitter-code-link", function() { - ga('send', 'event', "button-click", "share-twitter"); - }); - - addListener("click", ".help-button-footer", function() { - this.preventDefault(); - M.Modal.init(document.getElementById("help")); - ga('send', 'event', "button-click", "help-footer"); - M.Modal.getInstance(document.getElementById("help")).open(); - }); - - addListener("click", "#embed-button", function() { - this.preventDefault(); - M.Modal.init(document.getElementById("embed"), { - onCloseStart: function() { - document.querySelector(".embed-preview").innerHTML = ""; - } - }); - ga('send', 'event', "button-click", "embed-channel", "channel-name", chan.toLowerCase()); - M.Modal.getInstance(document.getElementById("embed")).open(); - }); - - addListener("click", "#contact-button", function() { - this.preventDefault(); - M.Modal.init(document.getElementById("contact")); - ga('send', 'event', "button-click", "contact-footer"); - M.Modal.getInstance(document.getElementById("contact")).open(); - }); - - addListener("click", ".about-button", function() { - this.preventDefault(); - M.Modal.init(document.getElementById("about")); - ga('send', 'event', "button-click", "contact-footer"); - M.Modal.getInstance(document.getElementById("about")).open(); - }); - - addListener("click", ".playlist-link", function(event){ - chat_active = false; - Helper.css("#chat-container", "display", "none"); - Helper.css("#wrapper", "display", "block"); - Helper.css("#suggestions", "display", "none"); - Helper.css("#pageButtons", "display", "flex"); - }); - - addListener("click", ".suggested-link", function(event){ - chat_active = false; - Helper.css("#chat-container", "display", "none"); - Helper.css("#wrapper", "display", "none"); - Helper.css("#suggestions", "display", "block"); - Helper.css("#pageButtons", "display", "none"); - }); - - addListener("click", ".import-spotify-auth", function(event){ - this.preventDefault(); - var nonce = Helper.randomString(29); - window.callback = function(data) { - access_token_data = data; - if(access_token_data.state == nonce){ - spotify_authenticated = true; - Channel.spotify_is_authenticated(true); - setTimeout(function(){ - spotify_authenticated = false; - access_token_data = {}; - Channel.spotify_is_authenticated(false); - Helper.css(".spotify_authenticated", "display", "none"); - Helper.css(".spotify_unauthenticated", "display", "flex"); - }, access_token_data.expires_in * 1000); - } else { - access_token_data = {}; - console.error("States doesn't match"); - } - spotify_window.close(); - window.callback = ""; - }; - spotify_window = window.open("/api/oauth#spotify=true&nonce=" + nonce, "", "width=600, height=600"); - }); - - addListener("click", ".import-youtube", function(event){ - this.preventDefault(); - Helper.css(".youtube_unclicked", "display", "none"); - Helper.css(".youtube_clicked", "display", "block"); - }); - - addListener("submit", "#chatForm", function(event){ - this.preventDefault(); - this.stopPropagation(); - Chat.chat(document.getElementById("chatForm").input); - return false; - }); - - addListener("click", "#shuffle", function(event) - { - this.preventDefault(); - Admin.shuffle(); - }); - - addListener("click", "#search-btn", function(event) - { - this.preventDefault(); - Search.showSearch(); - }); - - addListener("click", "#song-title", function(event) - { - this.preventDefault(); - Search.showSearch(); - }); - - addListener("click", "#admin-lock", function(event) - { - this.preventDefault(); - Admin.log_out(); - }); - - addListener("click", "#closeSettings", function(event) - { - //this.preventDefault(); - Admin.hide_settings(); - }); - - - addListener("click", ".result-object", function(e){ - var html = this.target; - var substr = this.target.outerHTML.substring(0,4); - if(substr != " original_length) { - end = original_length; - } - if(start > end) { - M.toast({html: "Start can't be before the end..", displayLength: 3000, classes: "red lighten"}); - } else if(start < 0) { - M.toast({html: "Start can't be less than 0..", displayLength: 3000, classes: "red lighten"}); - } else { - try { - var length = parseInt(end) - parseInt(start); - Search.submitAndClose(id, title, length, start, end, source, thumbnail); - } catch(err) { - M.toast({html: "Only numbers are accepted as song start and end parameters..", displayLength: 3000, classes: "red lighten"}); - } - } - } - }); - - addListener("click", ".result-get-more-info", function(event) { - this.preventDefault(); - var that = this.target; - var parent = that.parentElement.parentElement.parentElement.parentElement; - if(that.tagName == "I") parent = parent.parentElement; - - var videoId = parent.getAttribute("data-video-id"); - var to_toggle = document.getElementById("inner-results").querySelectorAll("[data-video-id='" + videoId + "']")[0]; - to_toggle = to_toggle.children[0]; - Helper.toggleClass(to_toggle, "result-object-slid"); - var elementToChange; - if(that.className.indexOf("material-icons") == 0) { - elementToChange = that; + Search.importSpotifyPlaylist( + "https://api.spotify.com/v1/playlists/" + playlist_id + "/tracks" + ); } else { - elementToChange = that.children[0]; + before_toast(); + M.toast({ + html: "It seems you've entered a invalid url.", + displayLength: 4000 + }); } - if(elementToChange.innerText == "keyboard_arrow_right") { - Helper.setHtml(elementToChange, "keyboard_arrow_left"); - } else { - Helper.setHtml(elementToChange, "keyboard_arrow_right"); - } - }) + } + } + document.getElementById("import_spotify").value = ""; + }); - addListener("click", '#submit-contact-form', function(event) { - this.preventDefault(); - var message = document.getElementById("contact-form-message").value; - var from = document.getElementById("contact-form-from").value; - Helper.send_mail(from, message); - //document.getElementById("contact-form").submit(); + addListener("change", "#autoplay", function(e) { + if (e.checked) embed_autoplay = "&autoplay=true"; + else embed_autoplay = "&autoplay=false"; + document.getElementById("embed-area").value = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + }); + + addListener("change", "#videoonly", function(e) { + if (e.checked) embed_videoonly = "&videoonly=true"; + else embed_videoonly = "&videoonly=false"; + if (previewing) + document.querySelector(".embed-preview").innerHTML = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + document.getElementById("embed-area").value = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + }); + + addListener("change", "#localmode", function(e) { + if (e.checked) embed_localmode = "&localmode=true"; + else embed_localmode = "&localmode=false"; + if (previewing) + document.querySelector(".embed-preview").innerHTML = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + document.getElementById("embed-area").value = embed_code( + embed_autoplay, + embed_width, + embed_height, + color, + embed_videoonly, + embed_localmode + ); + }); + + addListener("click", "#playbutton_remote", function(event) { + this.preventDefault(); + Mobile_remote.play_remote(); + }); + + addListener("click", "#pausebutton_remote", function(event) { + this.preventDefault(); + Mobile_remote.pause_remote(); + }); + + addListener("click", "#skipbutton_remote", function(event) { + this.preventDefault(); + Mobile_remote.skip_remote(); + }); + + addListener("click", ".skip_next_client", function(event) { + this.preventDefault(); + }); + + addListener("submit", "#remoteform", function(event) { + this.preventDefault(); + Mobile_remote.get_input(document.getElementById("remote_channel").value); + }); + + addListener("click", ".chat-tab-li", function() { + scrollChat(); + }); + + addListener("click", ".chat-tab", function() { + document.getElementById("text-chat-input").focus(); + }); + + addListener("click", ".prev", function(event) { + this.preventDefault(); + List.skip(false); + }); + + addListener("click", ".skip", function(event) { + this.preventDefault(); + List.skip(true); + }); + + addListener("click", "#chan", function(event) { + this.preventDefault(); + List.show(); + }); + + addListener("submit", "#adminForm", function(event) { + this.preventDefault(); + Admin.pass_save(); + }); + + addListener("submit", "#strictSkipForm", function(event) { + this.preventDefault(); + Admin.update_strict_skip( + document.getElementById("strict-input-number").value + ); + }); + + addListener("click", "#channel-share-modal", function() { + M.Modal.getInstance(document.getElementById("channel-share-modal")).close(); + }); + + addListener("click", ".shareface", function(event) { + ga("send", "event", "button-click", "share-facebook"); + }); + + addListener("click", ".android-image-link", function() { + ga("send", "event", "button-click", "android-playstore-link"); + }); + + addListener("click", "#twitter-code-link", function() { + ga("send", "event", "button-click", "share-twitter"); + }); + + addListener("click", ".help-button-footer", function() { + this.preventDefault(); + M.Modal.init(document.getElementById("help")); + ga("send", "event", "button-click", "help-footer"); + M.Modal.getInstance(document.getElementById("help")).open(); + }); + + addListener("click", "#embed-button", function() { + this.preventDefault(); + M.Modal.init(document.getElementById("embed"), { + onCloseStart: function() { + document.querySelector(".embed-preview").innerHTML = ""; + } }); + ga( + "send", + "event", + "button-click", + "embed-channel", + "channel-name", + chan.toLowerCase() + ); + M.Modal.getInstance(document.getElementById("embed")).open(); + }); - addListener("submit", '#contact-form', function(event){ - this.preventDefault(); - var message = document.getElementById("contact-form-message").value; - var from = document.getElementById("contact-form-from").value; + addListener("click", "#contact-button", function() { + this.preventDefault(); + M.Modal.init(document.getElementById("contact")); + ga("send", "event", "button-click", "contact-footer"); + M.Modal.getInstance(document.getElementById("contact")).open(); + }); - Helper.send_mail(from, message); - }); + addListener("click", ".about-button", function() { + this.preventDefault(); + M.Modal.init(document.getElementById("about")); + ga("send", "event", "button-click", "contact-footer"); + M.Modal.getInstance(document.getElementById("about")).open(); + }); - addListener("click", ".send-error-modal", function(event) { - this.preventDefault(); - var captcha_response = grecaptcha.getResponse(); + addListener("click", ".playlist-link", function(event) { + chat_active = false; + Helper.css("#chat-container", "display", "none"); + Helper.css("#wrapper", "display", "block"); + Helper.css("#suggestions", "display", "none"); + Helper.css("#pageButtons", "display", "flex"); + }); - Helper.removeClass("#send-loader", "hide"); - Helper.ajax({ - type: "POST", - headers: { - "Content-Type": "application/json" - }, - data: { - from: "no-reply@zoff.me", - message: Helper.html("#error-report-code"), - "g-recaptcha-response": captcha_response, - }, - url: "/api/mail", - success: function(data){ - if(data == "success"){ - Helper.removeElement(".send-error-modal"); - Helper.removeElement("#error-report-form"); - Helper.removeElement(".error-code-container"); - Helper.setHtml(".error-report-success", "Error report sent!"); - Helper.setHtml("#contact-container", "Mail has been sent, we'll be back with you shortly."); - window.location.reload(true); - }else{ - Helper.setHtml(".error-report-success", "Mail was not sent, try again"); - } - Helper.addClass("#send-loader", "hide"); - } + addListener("click", ".suggested-link", function(event) { + chat_active = false; + Helper.css("#chat-container", "display", "none"); + Helper.css("#wrapper", "display", "none"); + Helper.css("#suggestions", "display", "block"); + Helper.css("#pageButtons", "display", "none"); + }); + + addListener("click", ".import-spotify-auth", function(event) { + this.preventDefault(); + var nonce = Helper.randomString(29); + window.callback = function(data) { + access_token_data = data; + if (access_token_data.state == nonce) { + spotify_authenticated = true; + Channel.spotify_is_authenticated(true); + setTimeout(function() { + spotify_authenticated = false; + access_token_data = {}; + Channel.spotify_is_authenticated(false); + Helper.css(".spotify_authenticated", "display", "none"); + Helper.css(".spotify_unauthenticated", "display", "flex"); + }, access_token_data.expires_in * 1000); + } else { + access_token_data = {}; + console.error("States doesn't match"); + } + spotify_window.close(); + window.callback = ""; + }; + spotify_window = window.open( + "/api/oauth#spotify=true&nonce=" + nonce, + "", + "width=600, height=600" + ); + }); + + addListener("click", ".import-youtube", function(event) { + this.preventDefault(); + Helper.css(".youtube_unclicked", "display", "none"); + Helper.css(".youtube_clicked", "display", "block"); + }); + + addListener("submit", "#chatForm", function(event) { + this.preventDefault(); + this.stopPropagation(); + Chat.chat(document.getElementById("chatForm").input); + return false; + }); + + addListener("click", "#shuffle", function(event) { + this.preventDefault(); + Admin.shuffle(); + }); + + addListener("click", "#search-btn", function(event) { + this.preventDefault(); + Search.showSearch(); + }); + + addListener("click", "#song-title", function(event) { + this.preventDefault(); + Search.showSearch(); + }); + + addListener("click", "#admin-lock", function(event) { + this.preventDefault(); + Admin.log_out(); + }); + + addListener("click", "#closeSettings", function(event) { + //this.preventDefault(); + Admin.hide_settings(); + }); + + addListener("click", ".result-object", function(e) { + var html = this.target; + var substr = this.target.outerHTML.substring(0, 4); + if ( + substr != " original_length) { + end = original_length; + } + if (start > end) { + M.toast({ + html: "Start can't be before the end..", + displayLength: 3000, + classes: "red lighten" }); - return false; - //document.getElementById("error-report-form").submit(); - }) - - addListener("submit", "#error-report-form", function(event) { - this.preventDefault(); - //event.preventDefault(); - - var captcha_response = grecaptcha.getResponse(); - - Helper.removeClass("#send-loader", "hide"); - Helper.ajax({ - type: "POST", - headers: { - "Content-Type": "application/json" - }, - data: { - from: "no-reply@zoff.me", - message: Helper.html("#error-report-code"), - "g-recaptcha-response": captcha_response, - }, - url: "/api/mail", - success: function(data){ - if(data == "success"){ - Helper.removeElement(".send-error-modal"); - Helper.removeElement("#error-report-form"); - Helper.removeElement(".error-code-container"); - Helper.setHtml(".error-report-success", "Error report sent!"); - Helper.setHtml("#contact-container", "Mail has been sent, we'll be back with you shortly."); - window.location.reload(true); - }else{ - Helper.setHtml(".error-report-success", "Mail was not sent, try again"); - } - Helper.addClass("#send-loader", "hide"); - } + } else if (start < 0) { + M.toast({ + html: "Start can't be less than 0..", + displayLength: 3000, + classes: "red lighten" }); - }); - - addListener("click", "#add-many", function(e){ - this.preventDefault(); - this.stopPropagation(); - var id = e.getAttribute("data-video-id"); - var title = e.getAttribute("data-video-title"); - - var original_length = e.getAttribute("data-video-length"); - var parent = e.parentElement.parentElement; - var start = parseInt(parent.querySelectorAll(".result-start")[0].value); - var end = parseInt(parent.querySelectorAll(".result-end")[0].value); - if(end > original_length) { - end = original_length; + } else { + try { + var length = parseInt(end) - parseInt(start); + Search.submitAndClose( + id, + title, + length, + start, + end, + source, + thumbnail + ); + } catch (err) { + M.toast({ + html: + "Only numbers are accepted as song start and end parameters..", + displayLength: 3000, + classes: "red lighten" + }); } - var source = "youtube"; - var thumbnail; - if(e.getAttribute("data-type-source") != undefined) { + } + } + }); - source = "soundcloud"; - thumbnail = e.getAttribute("data-type-thumbnail"); - } - if(start > end) { - M.toast({html: "Start can't be before the end..", displayLength: 3000, classes: "red lighten"}); - } else if(start < 0) { - M.toast({html: "Start can't be less than 0..", displayLength: 3000, classes: "red lighten"}); + addListener("click", ".result-get-more-info", function(event) { + this.preventDefault(); + var that = this.target; + var parent = that.parentElement.parentElement.parentElement.parentElement; + if (that.tagName == "I") parent = parent.parentElement; + + var videoId = parent.getAttribute("data-video-id"); + var to_toggle = document + .getElementById("inner-results") + .querySelectorAll("[data-video-id='" + videoId + "']")[0]; + to_toggle = to_toggle.children[0]; + Helper.toggleClass(to_toggle, "result-object-slid"); + var elementToChange; + if (that.className.indexOf("material-icons") == 0) { + elementToChange = that; + } else { + elementToChange = that.children[0]; + } + if (elementToChange.innerText == "keyboard_arrow_right") { + Helper.setHtml(elementToChange, "keyboard_arrow_left"); + } else { + Helper.setHtml(elementToChange, "keyboard_arrow_right"); + } + }); + + addListener("click", "#submit-contact-form", function(event) { + this.preventDefault(); + var message = document.getElementById("contact-form-message").value; + var from = document.getElementById("contact-form-from").value; + Helper.send_mail(from, message); + //document.getElementById("contact-form").submit(); + }); + + addListener("submit", "#contact-form", function(event) { + this.preventDefault(); + var message = document.getElementById("contact-form-message").value; + var from = document.getElementById("contact-form-from").value; + + Helper.send_mail(from, message); + }); + + addListener("click", ".send-error-modal", function(event) { + this.preventDefault(); + var captcha_response = grecaptcha.getResponse(); + + Helper.removeClass("#send-loader", "hide"); + Helper.ajax({ + type: "POST", + headers: { + "Content-Type": "application/json" + }, + data: { + from: "no-reply@zoff.me", + message: Helper.html("#error-report-code"), + "g-recaptcha-response": captcha_response + }, + url: "/api/mail", + success: function(data) { + if (data == "success") { + Helper.removeElement(".send-error-modal"); + Helper.removeElement("#error-report-form"); + Helper.removeElement(".error-code-container"); + Helper.setHtml(".error-report-success", "Error report sent!"); + Helper.setHtml( + "#contact-container", + "Mail has been sent, we'll be back with you shortly." + ); + window.location.reload(true); } else { - try { - var length = parseInt(end) - parseInt(start); - - e.parentElement.parentElement.parentElement.remove(); - Search.submit(id, title, length, false, 0, 1, start, end, source, thumbnail); - } catch(event) { - M.toast({html: "Only numbers are accepted as song start and end parameters..", displayLength: 3000, classes: "red lighten"}); - } + Helper.setHtml( + ".error-report-success", + "Mail was not sent, try again" + ); } - + Helper.addClass("#send-loader", "hide"); + } }); + return false; + //document.getElementById("error-report-form").submit(); + }); - addListener("click", ".vote-container", function(e, target){ - if(hostMode) { - toast("Can't vote while in host mode!", "red lighten"); - document.querySelector("#toast-container").setAttribute("style", "z-index: 99999999999 !important"); - return; + addListener("submit", "#error-report-form", function(event) { + this.preventDefault(); + //event.preventDefault(); + + var captcha_response = grecaptcha.getResponse(); + + Helper.removeClass("#send-loader", "hide"); + Helper.ajax({ + type: "POST", + headers: { + "Content-Type": "application/json" + }, + data: { + from: "no-reply@zoff.me", + message: Helper.html("#error-report-code"), + "g-recaptcha-response": captcha_response + }, + url: "/api/mail", + success: function(data) { + if (data == "success") { + Helper.removeElement(".send-error-modal"); + Helper.removeElement("#error-report-form"); + Helper.removeElement(".error-code-container"); + Helper.setHtml(".error-report-success", "Error report sent!"); + Helper.setHtml( + "#contact-container", + "Mail has been sent, we'll be back with you shortly." + ); + window.location.reload(true); + } else { + Helper.setHtml( + ".error-report-success", + "Mail was not sent, try again" + ); } - var id = e.getAttribute("data-video-id"); - List.vote(id, "pos"); + Helper.addClass("#send-loader", "hide"); + } }); + }); - addListener("click", ".delete_button", function(e){ - var id = e.getAttribute("data-video-id"); - List.vote(id, "del"); - }); + addListener("click", "#add-many", function(e) { + this.preventDefault(); + this.stopPropagation(); + var id = e.getAttribute("data-video-id"); + var title = e.getAttribute("data-video-title"); - addListener("click", ".add-suggested", function(e){ - var id = e.getAttribute("data-video-id"); - var title = e.getAttribute("data-video-title"); - var length = e.getAttribute("data-video-length"); - var added_by = e.getAttribute("data-added-by"); - var source = "youtube"; - var thumbnail; - if(e.getAttribute("data-video-source") != "youtube") { - source = "soundcloud"; - thumbnail = e.getAttribute("data-type-thumbnail"); - } - Search.submit(id, title, parseInt(length), false, 0, 1, 0, parseInt(length), source, thumbnail); - if(added_by == "user") { - number_suggested = number_suggested - 1; - if(number_suggested < 0) number_suggested = 0; + var original_length = e.getAttribute("data-video-length"); + var parent = e.parentElement.parentElement; + var start = parseInt(parent.querySelectorAll(".result-start")[0].value); + var end = parseInt(parent.querySelectorAll(".result-end")[0].value); + if (end > original_length) { + end = original_length; + } + var source = "youtube"; + var thumbnail; + if (e.getAttribute("data-type-source") != undefined) { + source = "soundcloud"; + thumbnail = e.getAttribute("data-type-thumbnail"); + } + if (start > end) { + M.toast({ + html: "Start can't be before the end..", + displayLength: 3000, + classes: "red lighten" + }); + } else if (start < 0) { + M.toast({ + html: "Start can't be less than 0..", + displayLength: 3000, + classes: "red lighten" + }); + } else { + try { + var length = parseInt(end) - parseInt(start); - var to_display = number_suggested > 9 ? "9+" : number_suggested; - if(!document.querySelector(".suggested-link span.badge.new.white").classList.contains("hide") && to_display == 0){ - Helper.addClass(document.querySelector(".suggested-link span.badge.new.white"), "hide"); - Helper.addClass("#user_suggests", "hide"); - Helper.addClass("#suggest_bar", "hide"); - } + e.parentElement.parentElement.parentElement.remove(); + Search.submit( + id, + title, + length, + false, + 0, + 1, + start, + end, + source, + thumbnail + ); + } catch (event) { + M.toast({ + html: "Only numbers are accepted as song start and end parameters..", + displayLength: 3000, + classes: "red lighten" + }); + } + } + }); - document.querySelector(".suggested-link span.badge.new.white").innerText = to_display; - } - Helper.removeElement("#suggested-" + id); - }); + addListener("click", ".vote-container", function(e, target) { + if (hostMode) { + toast("Can't vote while in host mode!", "red lighten"); + document + .querySelector("#toast-container") + .setAttribute("style", "z-index: 99999999999 !important"); + return; + } + var id = e.getAttribute("data-video-id"); + List.vote(id, "pos"); + }); - addListener("click", ".del_suggested", function(e){ - var id = e.getAttribute("data-video-id"); + addListener("click", ".delete_button", function(e) { + var id = e.getAttribute("data-video-id"); + List.vote(id, "del"); + }); - Helper.removeElement("#suggested-" + id); - }); + addListener("click", ".add-suggested", function(e) { + var id = e.getAttribute("data-video-id"); + var title = e.getAttribute("data-video-title"); + var length = e.getAttribute("data-video-length"); + var added_by = e.getAttribute("data-added-by"); + var source = "youtube"; + var thumbnail; + if (e.getAttribute("data-video-source") != "youtube") { + source = "soundcloud"; + thumbnail = e.getAttribute("data-type-thumbnail"); + } + Search.submit( + id, + title, + parseInt(length), + false, + 0, + 1, + 0, + parseInt(length), + source, + thumbnail + ); + if (added_by == "user") { + number_suggested = number_suggested - 1; + if (number_suggested < 0) number_suggested = 0; - addListener("click", ".del_user_suggested", function(e){ - var id = e.getAttribute("data-video-id"); - Helper.removeElement("#suggested-" + id); + var to_display = number_suggested > 9 ? "9+" : number_suggested; + if ( + !document + .querySelector(".suggested-link span.badge.new.white") + .classList.contains("hide") && + to_display == 0 + ) { + Helper.addClass( + document.querySelector(".suggested-link span.badge.new.white"), + "hide" + ); + Helper.addClass("#user_suggests", "hide"); + Helper.addClass("#suggest_bar", "hide"); + } - number_suggested = number_suggested - 1; - if(number_suggested < 0) number_suggested = 0; + document.querySelector( + ".suggested-link span.badge.new.white" + ).innerText = to_display; + } + Helper.removeElement("#suggested-" + id); + }); - var to_display = number_suggested > 9 ? "9+" : number_suggested; - if(to_display == 0){ - Helper.addClass(document.querySelector(".suggested-link span.badge.new.white"), "hide"); - } + addListener("click", ".del_suggested", function(e) { + var id = e.getAttribute("data-video-id"); - docu.querySelector(".suggested-link span.badge.new.white").innerText = to_display; + Helper.removeElement("#suggested-" + id); + }); - List.vote(id, "del"); - }); + addListener("click", ".del_user_suggested", function(e) { + var id = e.getAttribute("data-video-id"); + Helper.removeElement("#suggested-" + id); - /* + number_suggested = number_suggested - 1; + if (number_suggested < 0) number_suggested = 0; + + var to_display = number_suggested > 9 ? "9+" : number_suggested; + if (to_display == 0) { + Helper.addClass( + document.querySelector(".suggested-link span.badge.new.white"), + "hide" + ); + } + + docu.querySelector( + ".suggested-link span.badge.new.white" + ).innerText = to_display; + + List.vote(id, "del"); + }); + + /* addListener("click", '#toast-container', function(){ var toastElement = document.querySelector('.toast'); var toastInstance = M.Toast.getInstance(toastElement); @@ -1745,319 +2124,444 @@ function addDynamicListeners() { }); */ - addListener("click", "#embed-area", function(e){ - e.select(); + addListener("click", "#embed-area", function(e) { + e.select(); + }); + + addListener("click", ".brand-logo-navigate", function(event) { + this.preventDefault(); + if (small_player) { + window.open(window.location.origin + window.location.pathname, "_blank"); + return; + } + window.history.pushState("to the frontpage!", "Title", "/"); + Channel.onepage_load(); + }); + + addListener("click", "#player_bottom_overlay", function(event) { + if (this.target.id == "closePlayer") return; + Frontpage.to_channel(this.target.getAttribute("data-channel"), false); + }); + + addListener("click", ".generate-channel-name", function(event) { + this.preventDefault(); + Helper.ajax({ + type: "GET", + url: "/api/generate_name", + success: function(response) { + document.getElementsByClassName("room-namer")[0].value = ""; + document.getElementsByClassName("room-namer")[0].value = response; + } }); - addListener("click", ".brand-logo-navigate", function(event){ - this.preventDefault(); - if(small_player) { - window.open(window.location.origin + window.location.pathname, "_blank"); - return; + ga("send", "event", "button-click", "generate-channel"); + }); + + addListener("click", "#close_find_form_button", function(event) { + this.preventDefault(); + find_start = false; + find_started = false; + Helper.toggleClass("#find_div", "hide"); + document.getElementById("find_input").value = ""; + document.getElementById("find_input").blur(); + Helper.removeClass(".highlight", "highlight"); + found_array = []; + found_array_index = 0; + find_word = ""; + }); + + addListener("submit", "#find_form", function(event) { + this.preventDefault(); + if (this.target.find_value.value != find_word) { + find_word = this.target.find_value.value; + found_array = []; + found_array_index = 0; + } + if (found_array.length == 0) { + var that = this.target; + found_array_index = 0; + found_array = []; + for (var i = 0; i < full_playlist.length; i++) { + var obj = full_playlist[i]; + if ( + obj.title + .toLowerCase() + .indexOf(that.find_value.value.toLowerCase()) >= 0 && + i != full_playlist.length - 1 + ) { + found_array.push(i); } - window.history.pushState("to the frontpage!", "Title", "/"); - Channel.onepage_load(); - }); - - addListener("click", "#player_bottom_overlay", function(event){ - if(this.target.id == "closePlayer") return; - Frontpage.to_channel(this.target.getAttribute("data-channel"), false); - }); - - addListener("click", ".generate-channel-name", function(event) { - this.preventDefault(); - Helper.ajax({ - type: "GET", - url: "/api/generate_name", - success: function(response) { - document.getElementsByClassName("room-namer")[0].value = ""; - document.getElementsByClassName("room-namer")[0].value = response; - } - }); - - ga('send', 'event', "button-click", "generate-channel"); - }); - - addListener("click", "#close_find_form_button", function(event) { - this.preventDefault(); - find_start = false; - find_started = false; - Helper.toggleClass("#find_div", "hide"); - document.getElementById("find_input").value = ""; - document.getElementById("find_input").blur(); - Helper.removeClass(".highlight", "highlight"); - found_array = []; + } + } else { + found_array_index = found_array_index + 1; + if (found_array.length - 1 < found_array_index) { found_array_index = 0; - find_word = ""; - }); + } + } + if (found_array.length == 0) { + document.getElementById("num_found").innerText = 0; + document.getElementById("of_total_found").innerText = found_array.length; + } else { + document.getElementById("num_found").innerText = found_array_index + 1; + document.getElementById("of_total_found").innerText = found_array.length; + } - addListener("submit", "#find_form", function(event){ - this.preventDefault(); - if(this.target.find_value.value != find_word) { - find_word = this.target.find_value.value; + if ( + found_array.length > 0 && + found_array[found_array_index] != full_playlist.length - 1 + ) { + Helper.removeClass(".highlight", "highlight"); + var jump_to_page = Math.floor( + found_array[found_array_index] / List.can_fit + ); + Helper.addClass( + document.querySelector("#wrapper").children[ + found_array[found_array_index] + ], + "highlight" + ); + List.dynamicContentPageJumpTo(jump_to_page); + } else { + Helper.removeClass(".highlight", "highlight"); + Helper.log(["none found"]); + } + }); + + document.addEventListener( + "keydown", + function(event) { + if (window.location.pathname != "/") { + if (event.keyCode == 91 || event.keyCode == 17) { + find_start = true; + } else if (find_start && event.keyCode == 70) { + find_start = false; + find_started = !find_started; + event.preventDefault(); + if (find_started) { + Helper.toggleClass("#find_div", "hide"); + document.getElementById("find_input").focus(); + find_word = ""; + } else { + Helper.toggleClass("#find_div", "hide"); + document.getElementById("find_input").value = ""; + document.getElementById("find_input").blur(); + Helper.removeClass(".highlight", "highlight"); found_array = []; found_array_index = 0; - } - if(found_array.length == 0){ - var that = this.target; - found_array_index = 0; - found_array = []; - for(var i = 0; i < full_playlist.length; i++) { - var obj = full_playlist[i]; - if(obj.title.toLowerCase().indexOf(that.find_value.value.toLowerCase()) >= 0 && i != full_playlist.length-1) { - found_array.push(i); - } + find_word = ""; + } + } else if ( + event.keyCode == 32 && + document + .querySelector(".search-container") + .classList.contains("hide") && + window.location.pathname != "/" && + document.querySelector("#text-chat-input") != + document.activeElement && + document.querySelector("#password") != document.activeElement && + document.querySelector("#other-list-name-add") != + document.activeElement && + document.querySelector("#user-pass-input") != + document.activeElement && + document.querySelector("#filtersearch_input") != + document.activeElement && + document.querySelector("#thumbnail_input") != + document.activeElement && + document.querySelector("#rules_input") != document.activeElement && + document.querySelector("#description_input") != + document.activeElement && + document.querySelector("#contact-form-from") != + document.activeElement && + document.querySelector("#contact-form-message") != + document.activeElement && + document.querySelector("#remote_channel") != document.activeElement && + document.querySelector("#import") != document.activeElement && + document.querySelector("#find_input") != document.activeElement && + document.querySelector("#import_spotify") != document.activeElement && + document.querySelector("#import_zoff") != document.activeElement && + document.querySelector("#import_soundcloud") != document.activeElement + ) { + if (chromecastAvailable) { + event.preventDefault(); + Player.playPauseVideo(); + return false; + } else { + if (videoSource == "soundcloud") { + event.preventDefault(); + Playercontrols.play_pause(); + return false; } - - } else { - found_array_index = found_array_index + 1; - if(found_array.length - 1 < found_array_index){ - found_array_index = 0; + if (Player.player.getPlayerState() == 1) { + event.preventDefault(); + Player.player.pauseVideo(); + return false; + } else if ( + Player.player.getPlayerState() == 2 || + Player.player.getPlayerState() == 5 + ) { + event.preventDefault(); + Player.player.playVideo(); + return false; } - - } - if(found_array.length == 0) { - document.getElementById("num_found").innerText = 0; - document.getElementById("of_total_found").innerText = found_array.length; + } } else { - document.getElementById("num_found").innerText = found_array_index + 1; - document.getElementById("of_total_found").innerText = found_array.length; + find_start = false; } + } + }, + false + ); - if(found_array.length > 0 && found_array[found_array_index] != full_playlist.length - 1){ - Helper.removeClass(".highlight", "highlight"); - var jump_to_page = Math.floor(found_array[found_array_index] / List.can_fit); - Helper.addClass(document.querySelector("#wrapper").children[found_array[found_array_index]], "highlight"); - List.dynamicContentPageJumpTo(jump_to_page); - } else { - Helper.removeClass(".highlight", "highlight"); - Helper.log(["none found"]); + document.addEventListener( + "keyup", + function(event) { + _kT += event.keyCode; + if (_kWay.substring(0, _kT.length) == _kT) { + if (_kWay == _kT && !_kDone) { + _kDone = true; + document.getElementById("main-container").style.transition = + "filter .5s"; + setTimeout(function() { + //document.getElementById("main-container").style.transform = "rotate(180deg)"; + document.getElementById("main-container").style.filter = + "invert(100%)"; + }, 10); + _kT = ""; + for (var i = 0; i < 4; i++) { + var c = "green"; + if (i % 2 == 0) c = "red"; + M.toast({ + html: "Congratulations!", + displayLength: 4000, + classes: c + }); + } + } else if (_kWay == _kT && _kDone) { + _kDone = false; + document.getElementById("main-container").style.filter = "invert(0%)"; + //document.getElementById("main-container").style.transform = "rotate(0deg)"; + _kT = ""; } - }); - - document.addEventListener("keydown", function(event) { - if(window.location.pathname != "/"){ - if(event.keyCode == 91 || event.keyCode == 17){ - find_start = true; - } else if(find_start && event.keyCode == 70){ - find_start = false; - find_started = !find_started; - event.preventDefault(); - if(find_started){ - Helper.toggleClass("#find_div", "hide"); - document.getElementById("find_input").focus(); - find_word = ""; - } else { - Helper.toggleClass("#find_div", "hide"); - document.getElementById("find_input").value = ""; - document.getElementById("find_input").blur(); - Helper.removeClass(".highlight", "highlight"); - found_array = []; - found_array_index = 0; - find_word = ""; - } - } else if(event.keyCode == 32 && document.querySelector(".search-container").classList.contains("hide") && window.location.pathname != "/" && - document.querySelector("#text-chat-input") != document.activeElement && - document.querySelector("#password") != document.activeElement && - document.querySelector("#other-list-name-add") != document.activeElement && - document.querySelector("#user-pass-input") != document.activeElement && - document.querySelector("#filtersearch_input") != document.activeElement && - document.querySelector("#thumbnail_input") != document.activeElement && - document.querySelector("#rules_input") != document.activeElement && - document.querySelector("#description_input") != document.activeElement && - document.querySelector("#contact-form-from") != document.activeElement && - document.querySelector("#contact-form-message") != document.activeElement && - document.querySelector("#remote_channel") != document.activeElement && - document.querySelector("#import") != document.activeElement && - document.querySelector("#find_input") != document.activeElement && - document.querySelector("#import_spotify") != document.activeElement && - document.querySelector("#import_zoff") != document.activeElement && - document.querySelector("#import_soundcloud") != document.activeElement) { - if(chromecastAvailable) { - event.preventDefault(); - Player.playPauseVideo(); - return false; - } else { - if(videoSource == "soundcloud") { - event.preventDefault(); - Playercontrols.play_pause(); - return false; - } - if(Player.player.getPlayerState() == 1) { - event.preventDefault(); - Player.player.pauseVideo(); - return false; - } else if(Player.player.getPlayerState() == 2 || Player.player.getPlayerState() == 5) { - event.preventDefault(); - Player.player.playVideo(); - return false; - } - } - } else { - find_start = false; - } - } - }, false); - - document.addEventListener("keyup", function(event) { - _kT += event.keyCode; - if(_kWay.substring(0, _kT.length) == _kT) { - if(_kWay == _kT && !_kDone) { - _kDone = true; - document.getElementById("main-container").style.transition = "filter .5s"; - setTimeout(function() { - //document.getElementById("main-container").style.transform = "rotate(180deg)"; - document.getElementById("main-container").style.filter = "invert(100%)"; - }, 10); - _kT = ""; - for(var i = 0; i < 4; i++) { - var c = "green"; - if(i%2 == 0) c = "red" - M.toast({ html: "Congratulations!", displayLength: 4000, classes: c}); - } - } else if(_kWay == _kT && _kDone){ - _kDone = false; - document.getElementById("main-container").style.filter = "invert(0%)"; - //document.getElementById("main-container").style.transform = "rotate(0deg)"; - _kT = ""; - } - } else { - _kT = ""; - } - if(event.keyCode == 27 && window.location.path != "/"){ - //$("#results").html(""); - Helper.addClass("#search-wrapper", "hide"); - Helper.css(".search_results", "display", "none"); - Helper.removeClass(".song-title", "hide"); - if(document.querySelector("#search-btn i").innerText == "close") - { - /*$("#results").slideUp({ + } else { + _kT = ""; + } + if (event.keyCode == 27 && window.location.path != "/") { + //$("#results").html(""); + Helper.addClass("#search-wrapper", "hide"); + Helper.css(".search_results", "display", "none"); + Helper.removeClass(".song-title", "hide"); + if (document.querySelector("#search-btn i").innerText == "close") { + /*$("#results").slideUp({ complete: function() { $("#results").empty(); } });*/ - document.querySelector("#results").innerHTML = ""; - document.querySelector("#results_soundcloud").innerHTML = ""; - document.getElementsByTagName("body")[0].setAttribute("style", "overflow-y:auto") - document.querySelector("#search-btn i").innerText = "search"; - document.querySelector(".search_input").value = ""; - } - if(find_started) { - Helper.toggleClass("#find_div", "hide"); - document.getElementById("find_input").value = ""; - document.getElementById("find_input").blur(); - Helper.removeClass(".highlight", "highlight"); - found_array = []; - found_array_index = 0; - find_word = ""; - find_start = false; - find_started = false; - } - if(document.querySelectorAll(".search-container").length != 0 && !document.querySelector(".search-container").classList.contains("hide")){ - Helper.toggleClass("#results", "hide"); - } - } else if(event.keyCode == 13 && window.location.path != "/" && document.querySelectorAll("#search").length > 0 && document.querySelector("#search").value == "fireplace" && !document.querySelector(".search-container").classList.contains("hide") && window.location.pathname != "/") { - clearTimeout(timeout_search); - Helper.setHtml("#results", ""); - document.querySelector("#search").value = ""; - Helper.addClass("#search-wrapper", "hide"); - Helper.removeClass("#song-title", "hide"); - document.querySelector("#search-btn i").innerText = "search"; - Helper.css(".search_results", "display", "none"); - if(fireplace_initiated) { - fireplace_initiated = false; - Player.fireplace.destroy(); - Helper.css("#fireplace_player", "display", "none"); - } else { - fireplace_initiated = true; - Helper.css("#fireplace_player", "display", "block"); - Player.createFireplacePlayer(); - } - } else if((event.keyCode == 91 || event.keyCode == 17) && !find_started){ - find_start = false; + document.querySelector("#results").innerHTML = ""; + document.querySelector("#results_soundcloud").innerHTML = ""; + document + .getElementsByTagName("body")[0] + .setAttribute("style", "overflow-y:auto"); + document.querySelector("#search-btn i").innerText = "search"; + document.querySelector(".search_input").value = ""; } - if(event.target.classList.contains("search_input")) { - searchTimeout(event); + if (find_started) { + Helper.toggleClass("#find_div", "hide"); + document.getElementById("find_input").value = ""; + document.getElementById("find_input").blur(); + Helper.removeClass(".highlight", "highlight"); + found_array = []; + found_array_index = 0; + find_word = ""; + find_start = false; + find_started = false; } - }, false); + if ( + document.querySelectorAll(".search-container").length != 0 && + !document + .querySelector(".search-container") + .classList.contains("hide") + ) { + Helper.toggleClass("#results", "hide"); + } + } else if ( + event.keyCode == 13 && + window.location.path != "/" && + document.querySelectorAll("#search").length > 0 && + document.querySelector("#search").value == "fireplace" && + !document + .querySelector(".search-container") + .classList.contains("hide") && + window.location.pathname != "/" + ) { + clearTimeout(timeout_search); + Helper.setHtml("#results", ""); + document.querySelector("#search").value = ""; + Helper.addClass("#search-wrapper", "hide"); + Helper.removeClass("#song-title", "hide"); + document.querySelector("#search-btn i").innerText = "search"; + Helper.css(".search_results", "display", "none"); + if (fireplace_initiated) { + fireplace_initiated = false; + Player.fireplace.destroy(); + Helper.css("#fireplace_player", "display", "none"); + } else { + fireplace_initiated = true; + Helper.css("#fireplace_player", "display", "block"); + Player.createFireplacePlayer(); + } + } else if ( + (event.keyCode == 91 || event.keyCode == 17) && + !find_started + ) { + find_start = false; + } + if (event.target.classList.contains("search_input")) { + searchTimeout(event); + } + }, + false + ); - document.addEventListener("click", function(event) { - handleEvent(event, event.target, false, "click"); - }, true); + document.addEventListener( + "click", + function(event) { + handleEvent(event, event.target, false, "click"); + }, + true + ); - document.addEventListener("mouseleave", function(event) { - if(event.target.className == "card sticky-action") { - var that = event.target; - if(that.querySelector(".card-reveal") == null) return; - that.querySelector(".card-reveal").setAttribute("style", "display: block;transform: translateY(0%);"); - clearTimeout(image_timeout); - image_timeout = setTimeout(function(){ - that.querySelector(".card-reveal").setAttribute("style", "display: none;"); - }, 100); - } else if(!Helper.mobilecheck() && Crypt.get_intelligent_list_enabled()){ - try { - if(event.target.id == "wrapper" && event.relatedTarget.id != "context-menu-overlay" && event.relatedTarget.className.indexOf("context-menu-list") == -1 && event.relatedTarget.className.indexOf("context-menu-item") == -1) { - clearIntelligentQueue(); - } else if(event.target.id == "context-menu-overlay" || event.relatedTarget.className.indexOf("context-menu-list") >= 0 || event.relatedTarget.className.indexOf("context-menu-item") >= 0) { - var related = event.relatedTarget; - if(related.id == "wrapper" || related.className.indexOf("context-menu-list") >= 0 || related.className.indexOf("context-menu-item") >= 0) { - enable_intelligent_list(); - return; - } - var parent = related.parentElement; - while(parent != null) { - try { - if(parent.id == "wrapper" || parent.className.indexOf("context-menu-list") >= 0 || parent.className.indexOf("context-menu-item") >= 0) { - enable_intelligent_list(); - return; - } - } catch(e){} - try { - parent = parent.parentElement; - } catch(e){break;} - } - clearIntelligentQueue(); + document.addEventListener( + "mouseleave", + function(event) { + if (event.target.className == "card sticky-action") { + var that = event.target; + if (that.querySelector(".card-reveal") == null) return; + that + .querySelector(".card-reveal") + .setAttribute("style", "display: block;transform: translateY(0%);"); + clearTimeout(image_timeout); + image_timeout = setTimeout(function() { + that + .querySelector(".card-reveal") + .setAttribute("style", "display: none;"); + }, 100); + } else if ( + !Helper.mobilecheck() && + Crypt.get_intelligent_list_enabled() + ) { + try { + if ( + event.target.id == "wrapper" && + event.relatedTarget.id != "context-menu-overlay" && + event.relatedTarget.className.indexOf("context-menu-list") == -1 && + event.relatedTarget.className.indexOf("context-menu-item") == -1 + ) { + clearIntelligentQueue(); + } else if ( + event.target.id == "context-menu-overlay" || + event.relatedTarget.className.indexOf("context-menu-list") >= 0 || + event.relatedTarget.className.indexOf("context-menu-item") >= 0 + ) { + var related = event.relatedTarget; + if ( + related.id == "wrapper" || + related.className.indexOf("context-menu-list") >= 0 || + related.className.indexOf("context-menu-item") >= 0 + ) { + enable_intelligent_list(); + return; + } + var parent = related.parentElement; + while (parent != null) { + try { + if ( + parent.id == "wrapper" || + parent.className.indexOf("context-menu-list") >= 0 || + parent.className.indexOf("context-menu-item") >= 0 + ) { + enable_intelligent_list(); + return; } - } catch(e) {} - } - }, true); + } catch (e) {} + try { + parent = parent.parentElement; + } catch (e) { + break; + } + } + clearIntelligentQueue(); + } + } catch (e) {} + } + }, + true + ); - document.addEventListener("mouseenter", function(event) { - if(event.target.className == "card sticky-action") { - var that = event.target; - if(that.querySelector(".card-reveal") == null) return; - that.querySelector(".card-reveal").setAttribute("style", "display: block;"); - clearTimeout(image_timeout); - image_timeout = setTimeout(function(){ - that.querySelector(".card-reveal").setAttribute("style", "display: block;transform: translateY(-100%);"); - }, 50); - } else if(event.target.id == "wrapper") { - enable_intelligent_list(); - } - }, true); + document.addEventListener( + "mouseenter", + function(event) { + if (event.target.className == "card sticky-action") { + var that = event.target; + if (that.querySelector(".card-reveal") == null) return; + that + .querySelector(".card-reveal") + .setAttribute("style", "display: block;"); + clearTimeout(image_timeout); + image_timeout = setTimeout(function() { + that + .querySelector(".card-reveal") + .setAttribute( + "style", + "display: block;transform: translateY(-100%);" + ); + }, 50); + } else if (event.target.id == "wrapper") { + enable_intelligent_list(); + } + }, + true + ); - document.addEventListener("contextmenu", function(event) { - handleEvent(event, event.target, false, "contextmenu"); - }, true); + document.addEventListener( + "contextmenu", + function(event) { + handleEvent(event, event.target, false, "contextmenu"); + }, + true + ); - document.addEventListener("input", function(event) { - handleEvent(event, event.target, false, "input"); - }, true); + document.addEventListener( + "input", + function(event) { + handleEvent(event, event.target, false, "input"); + }, + true + ); - document.addEventListener("change", function(event) { - handleEvent(event, event.target, false, "change"); - }, true); + document.addEventListener( + "change", + function(event) { + handleEvent(event, event.target, false, "change"); + }, + true + ); - document.addEventListener("submit", function(event) { - handleEvent(event, event.target, false, "submit"); - }, true); + document.addEventListener( + "submit", + function(event) { + handleEvent(event, event.target, false, "submit"); + }, + true + ); - window.addEventListener("focus", function(event) { - document.getElementById("favicon").setAttribute("href", "/assets/images/favicon.png"); - unseen = false; - }); + window.addEventListener("focus", function(event) { + document + .getElementById("favicon") + .setAttribute("href", "/assets/images/favicon.png"); + unseen = false; + }); - window.addEventListener("resize", function(){ - resizeFunction(); - }); + window.addEventListener("resize", function() { + resizeFunction(); + }); } diff --git a/server/routing/client/api.js b/server/routing/client/api.js index 6b8194ce..ceb8d0da 100644 --- a/server/routing/client/api.js +++ b/server/routing/client/api.js @@ -1,1704 +1,2511 @@ -var express = require('express'); +var express = require("express"); var router = express.Router(); -var path = require('path'); -var mongojs = require('mongojs'); +var path = require("path"); +var mongojs = require("mongojs"); var ObjectId = mongojs.ObjectId; var token_db = mongojs("tokens"); var cookieParser = require("cookie-parser"); -var db = require(pathThumbnails + '/handlers/db.js'); -var allowed_key = require(pathThumbnails + '/config/allowed_api.js'); -var crypto = require('crypto'); -var List = require(pathThumbnails + '/handlers/list.js'); -var Functions = require(pathThumbnails + '/handlers/functions.js'); -var Frontpage = require(pathThumbnails + '/handlers/frontpage.js'); -var Search = require(pathThumbnails + '/handlers/search.js'); -var uniqid = require('uniqid'); -var Filter = require('bad-words'); -var filter = new Filter({ placeHolder: 'x'}); -var paginate = require('mongojs-paginate'); +var db = require(pathThumbnails + "/handlers/db.js"); +var allowed_key; + +try { + allowed_key = require(pathThumbnails + "/config/allowed_api.js"); +} 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" + ); +} +var crypto = require("crypto"); +var List = require(pathThumbnails + "/handlers/list.js"); +var Functions = require(pathThumbnails + "/handlers/functions.js"); +var Frontpage = require(pathThumbnails + "/handlers/frontpage.js"); +var Search = require(pathThumbnails + "/handlers/search.js"); +var uniqid = require("uniqid"); +var Filter = require("bad-words"); +var filter = new Filter({ placeHolder: "x" }); +var paginate = require("mongojs-paginate"); var _exports = { - router: router, - sIO: {} -} + router: router, + sIO: {} +}; var projects = require(pathThumbnails + "/handlers/aggregates.js"); var error = { - not_found: { - youtube: { - status: 404, - error: "Couldn't find a song like that on YouTube.", - success: false, - results: [], - }, - local: { - status: 404, - error: "Couldn't find a song like that in the channel", - success: false, - results: [], - }, - list: { - status: 404, - error: "The list doesn't exist", - success: false, - results: [], - } + not_found: { + youtube: { + status: 404, + error: "Couldn't find a song like that on YouTube.", + success: false, + results: [] }, - not_authenticated: { - status: 403, - error: "Wrong adminpassword or userpassword.", - success: false, - results: [], + local: { + status: 404, + error: "Couldn't find a song like that in the channel", + success: false, + results: [] }, - formatting: { - status: 400, - error: "Malformed request parameters.", - success: false, - results: [], - }, - conflicting: { - status: 409, - error: "That element already exists.", - success: false, - results: [], - }, - wrong_token: { - status: 400, - error: "You're using a faulty token. Try getting a new token, or send the request without the token.", - success: false, - results: [], - }, - tooMany: { - status: 429, - error: "You're doing too many requests, check header-field Retry-After for the wait-time left.", - success: false, - results: [], - }, - settings: { - status: 409, - error: "The channel doesn't have strict skipping enabled.", - success: false, - results: [], - }, - already_skip: { - status: 206, - error: false, - success: true, - results: [], - }, - more_skip_needed: { - status: 202, - error: false, - success: true, - results: [], - }, - no_error: { - status: 200, - error: false, - success: true, - results: [], + list: { + status: 404, + error: "The list doesn't exist", + success: false, + results: [] } -} + }, + not_authenticated: { + status: 403, + error: "Wrong adminpassword or userpassword.", + success: false, + results: [] + }, + formatting: { + status: 400, + error: "Malformed request parameters.", + success: false, + results: [] + }, + conflicting: { + status: 409, + error: "That element already exists.", + success: false, + results: [] + }, + wrong_token: { + status: 400, + error: + "You're using a faulty token. Try getting a new token, or send the request without the token.", + success: false, + results: [] + }, + tooMany: { + status: 429, + error: + "You're doing too many requests, check header-field Retry-After for the wait-time left.", + success: false, + results: [] + }, + settings: { + status: 409, + error: "The channel doesn't have strict skipping enabled.", + success: false, + results: [] + }, + already_skip: { + status: 206, + error: false, + success: true, + results: [] + }, + more_skip_needed: { + status: 202, + error: false, + success: true, + results: [] + }, + no_error: { + status: 200, + error: false, + success: true, + results: [] + } +}; router.use(function(req, res, next) { - next(); // make sure we go to the next routes and don't stop here + next(); // make sure we go to the next routes and don't stop here }); -router.route('/api/help').get(function(req, res) { - res.redirect('https://github.com/zoff-music/zoff/blob/master/server/REST.md'); - return; -}) +router.route("/api/help").get(function(req, res) { + res.redirect("https://github.com/zoff-music/zoff/blob/master/server/REST.md"); + return; +}); -router.route('/api/frontpages').get(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); +router.route("/api/frontpages").get(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); - checkTimeout(guid, res, false, "GET", function() { - Frontpage.get_frontpage_lists(function(err, docs) { - //db.collection("frontpage_lists").find({frontpage: true, count: {$gt: 0}}, function(err, docs) { - db.collection("connected_users").find({"_id": "total_users"}, function(err, tot) { + checkTimeout(guid, res, false, "GET", function() { + Frontpage.get_frontpage_lists(function(err, docs) { + //db.collection("frontpage_lists").find({frontpage: true, count: {$gt: 0}}, function(err, docs) { + db.collection("connected_users").find({ _id: "total_users" }, function( + err, + tot + ) { + var to_return = error.no_error; + to_return.results = { + channels: docs, + viewers: tot[0].total_users.length + }; + res.status(200).send(to_return); + return; + }); + }); + }); +}); + +router.route("/api/frontpages").post(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "POST", function() { + Frontpage.get_frontpage_lists(function(err, docs) { + //db.collection("frontpage_lists").find({frontpage: true, count: {$gt: 0}}, function(err, docs) { + db.collection("connected_users").find( + { _id: "total_users" }, + function(err, tot) { var to_return = error.no_error; - to_return.results = {channels: docs, viewers: tot[0].total_users.length}; + to_return.results = { + channels: docs, + viewers: tot[0].total_users.length + }; res.status(200).send(to_return); return; - }); + } + ); + }); }); + }); }); }); -router.route('/api/frontpages').post(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); +router.route("/api/generate_name").get(function(req, res) { + Functions.generate_channel_name(res); +}); - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; +router.route("/api/list/:channel_name/:video_id").delete(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + if ( + !req.body.hasOwnProperty("adminpass") || + !req.body.hasOwnProperty("userpass") || + !req.params.hasOwnProperty("channel_name") || + !req.params.hasOwnProperty("video_id") + ) { + var result = { + adminpass: { + expected: "string", + got: req.body.hasOwnProperty("adminpass") + ? typeof req.body.adminpass + : undefined + }, + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + try { + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var adminpass = + req.body.adminpass == "" + ? "" + : Functions.hash_pass( + crypto + .createHash("sha256") + .update(req.body.adminpass, "utf8") + .digest("hex") + ); + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + var userpass = req.body.userpass; + var channel_name = cleanChannelName(req.params.channel_name); + var video_id = req.params.video_id; + if (typeof userpass != "string" || typeof adminpass != "string") { + throw "Wrong format"; } + } catch (e) { + var result = { + adminpass: { + expected: "string", + got: req.body.hasOwnProperty("adminpass") + ? typeof req.body.adminpass + : undefined + }, + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); + var cookie = req.cookies._uI; - token_db.collection("api_token").find({token: token}, function(err, token_docs) { + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.adminpass == "") { + adminpass = Functions.hash_pass(_a); + } + if (req.body.userpass == "") { + userpass = _u; + } + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { var authorized = false; var origin; try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; } checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "POST", function() { - Frontpage.get_frontpage_lists(function(err, docs) { - //db.collection("frontpage_lists").find({frontpage: true, count: {$gt: 0}}, function(err, docs) { - db.collection("connected_users").find({"_id": "total_users"}, function(err, tot) { - var to_return = error.no_error; - to_return.results = {channels: docs, viewers: tot[0].total_users.length}; - res.status(200).send(to_return); - return; - }); - }); - }); - }) - }); -}); - -router.route('/api/generate_name').get(function(req, res) { - Functions.generate_channel_name(res); -}); - -router.route('/api/list/:channel_name/:video_id').delete(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - if(!req.body.hasOwnProperty('adminpass') || !req.body.hasOwnProperty('userpass') || - !req.params.hasOwnProperty('channel_name') || !req.params.hasOwnProperty('video_id')) { - var result = { - adminpass: { - expected: "string", - got: req.body.hasOwnProperty("adminpass") ? typeof(req.body.adminpass) : undefined, - }, - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - try { - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var adminpass = req.body.adminpass == "" ? "" : Functions.hash_pass(crypto.createHash('sha256').update(req.body.adminpass, 'utf8').digest("hex")); - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - var userpass = req.body.userpass; - var channel_name = cleanChannelName(req.params.channel_name); - var video_id = req.params.video_id; - if(typeof(userpass) != "string" || typeof(adminpass) != "string") { - throw "Wrong format"; - } - } catch(e) { - var result = { - adminpass: { - expected: "string", - got: req.body.hasOwnProperty("adminpass") ? typeof(req.body.adminpass) : undefined, - }, - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - - var cookie = req.cookies._uI; - - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.adminpass == "") { - adminpass = Functions.hash_pass(_a); - } - if(req.body.userpass == "") { - userpass = _u; - } - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; - } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "DELETE", function() { - if(token != "" && !authorized) { - //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { - res.status(400).send(error.wrong_token); - return; - //}); - } else { - validateLogin(adminpass, userpass, channel_name, "delete", res, function(exists) { - if(!exists) { - res.status(404).send(error.not_found.list); - return; - } - db.collection(channel_name).find({id:video_id, now_playing: false}, function(err, docs){ - if(docs.length == 0) { - res.status(404).send(error.not_found.local); - return; - } - var dont_increment = false; - if(docs[0]){ - if(docs[0].type == "suggested"){ - dont_increment = true; - } - db.collection(channel_name).remove({id:video_id}, function(err, docs){ - if(authorized) { - incrementToken(token); - } - io.to(channel_name).emit("channel", {type:"deleted", value: video_id}); - if(!dont_increment) { - db.collection("frontpage_lists").update({_id: channel_name, count: {$gt: 0}}, {$inc: {count: -1}, $set:{accessed: Functions.get_time()}}, {upsert: true}, function(err, docs){ - //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { - res.status(200).send(error.no_error); - return; - //}); - }); - } else { - //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { - res.status(200).send(error.no_error); - return; - //}); - } - }); - } - }); - }); - } - }); - }); - }); - }); -}); - -router.route('/api/skip/:channel_name').post(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - - var api_key = req.body.api_key; - var guid = req.body.chat_name; - var channel_name = cleanChannelName(req.params.channel_name); - var userpass = ""; - if(req.body.userpass && req.body.userpass != "") userpass = crypto.createHash('sha256').update(Functions.decrypt_string(req.body.userpass)).digest("base64"); - if(allowed_key.indexOf(api_key) > -1) { - db.collection(channel_name + "_settings").find({"id": "config"}, function(err, settings) { - if(settings.length == 0) { - res.status(404).send(error.not_found.list); - return; - } - settings = settings[0]; - if(!settings.strictSkip) { - res.status(409).send(error.settings); - return; - } - if(settings.userpass == "" || (settings.userpass == userpass)) { - if(settings.skips.length+1 >= settings.strictSkipNumber && !Functions.contains(settings.skips, guid)) { - Functions.checkTimeout("skip", 1, channel_name, channel_name, false, true, undefined, function() { - db.collection(channel_name).find({now_playing: true}, function(err, np) { - if(np.length != 1) { - res.status(404).send(error.not_found.list); - return; - } - List.change_song(channel_name, false, np[0].id, [settings], function() { - res.status(200).send(error.no_error); - return; - }); - _exports.sIO.to(channel_name).emit('chat', {from: guid, icon: false, msg: " skipped via API."}); - }); - }, "", function() { - res.status(429).send(error.tooMany); - return; - }); - } else if(!Functions.contains(settings.skips, guid)) { - db.collection(channel_name + "_settings").update({ id: "config" }, {$push:{skips:guid}}, function(err, d){ - var to_skip = (settings.strictSkipNumber) - settings.skips.length-1; - _exports.sIO.to(channel_name).emit('chat', {from: guid, msg: " voted to skip via API."}); - // VOTED TO SKIP - var to_send = error.more_skip_needed; - to_send.results = [to_skip] - res.status(202).send(to_send); - return; - }); - } else { - //ALREADY SKIP - res.status(206).send(error.already_skip); - return; - } + checkTimeout(guid, res, authorized, "DELETE", function() { + if (token != "" && !authorized) { + //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { + res.status(400).send(error.wrong_token); + return; + //}); } else { - // NOT AUTHENTICATED - res.status(403).send(error.not_authenticated); - return; - } - }); - } else { - // WRONG API KEY - var toSend = error.not_authenticated; - toSend.status = 406; - res.status(406).send(toSend); - return; - } -}); - -router.route('/api/conf/:channel_name').put(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - - try { - if(!req.body.hasOwnProperty('adminpass') || !req.body.hasOwnProperty('userpass') || - !req.params.hasOwnProperty('channel_name') || !req.body.hasOwnProperty('vote') || - !req.body.hasOwnProperty('addsongs') || !req.body.hasOwnProperty('longsongs') || - !req.body.hasOwnProperty('frontpage') || !req.body.hasOwnProperty('allvideos') || - !req.body.hasOwnProperty('skip') || !req.body.hasOwnProperty('shuffle') || - !req.body.hasOwnProperty('userpass_changed')) { - throw "Wrong format"; - } - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var adminpass = req.body.adminpass == "" ? "" : Functions.hash_pass(crypto.createHash('sha256').update(req.body.adminpass, 'utf8').digest("hex")); - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - var userpass = req.body.userpass; - var voting = req.body.vote; - var addsongs = req.body.addsongs; - var longsongs = req.body.longsongs; - var frontpage = req.body.frontpage; - var allvideos = req.body.allvideos; - var removeplay = req.body.removeplay; - var skipping = req.body.skip; - var shuffling = req.body.shuffle; - var userpass_changed = req.body.userpass_changed; - var channel_name = cleanChannelName(req.params.channel_name); - if(typeof(userpass) != "string" || typeof(adminpass) != "string" || - typeof(voting) != "boolean" || typeof(addsongs) != "boolean" || - typeof(longsongs) != "boolean" || typeof(frontpage) != "boolean" || - typeof(allvideos) != "boolean" || typeof(removeplay) != "boolean" || - typeof(skipping) != "boolean" || typeof(shuffling) != "boolean" || - typeof(userpass_changed) != "boolean") { - throw "Wrong format"; - } - } catch(e) { - var result = { - adminpass: { - expected: "string", - got: req.body.hasOwnProperty("adminpass") ? typeof(req.body.adminpass) : undefined, - }, - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined, - }, - vote: { - expected: "boolean", - got: req.body.hasOwnProperty("vote") ? typeof(req.body.vote) : undefined, - }, - addsongs: { - expected: "boolean", - got: req.body.hasOwnProperty("addsongs") ? typeof(req.body.addsongs) : undefined, - }, - longsongs: { - expected: "boolean", - got: req.body.hasOwnProperty("longsongs") ? typeof(req.body.longsongs) : undefined, - }, - frontpage: { - expected: "boolean", - got: req.body.hasOwnProperty("frontpage") ? typeof(req.body.frontpage) : undefined, - }, - skip: { - expected: "boolean", - got: req.body.hasOwnProperty("skip") ? typeof(req.body.skip) : undefined, - }, - shuffle: { - expected: "boolean", - got: req.body.hasOwnProperty("shuffle") ? typeof(req.body.shuffle) : undefined, - }, - userpass_changed: { - expected: "boolean", - got: req.body.hasOwnProperty("userpass_changed") ? typeof(req.body.userpass_changed) : undefined, - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - var cookie = req.cookies._uI; - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.adminpass == "") { - adminpass = Functions.hash_pass(_a); - } - if(req.body.userpass == "") { - userpass = _u; - } - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; - } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "CONFIG", function() { - if(token != "" && !authorized) { - //updateTimeout(guid, res, authorized, "CONFIG", function(err, docs) { - res.status(400).send(error.wrong_token); - return; - //}); - } else { - validateLogin(adminpass, userpass, channel_name, "config", res, function(exists, conf) { - if(!exists && conf.length == 0) { - res.status(404).send(error.not_found.list); - return; - } - - if((!userpass_changed && frontpage) || (userpass_changed && userpass == "")) { - userpass = ""; - } else if(userpass_changed && userpass != "") { - frontpage = false; - } - var description = ""; - - var obj = { - addsongs:addsongs, - allvideos:allvideos, - frontpage:frontpage, - skip:skipping, - vote:voting, - removeplay:removeplay, - shuffle:shuffling, - longsongs:longsongs, - adminpass:adminpass, - desc: description, - }; - if(userpass_changed) { - obj["userpass"] = userpass; - } else if (frontpage) { - obj["userpass"] = ""; - } - db.collection(channel_name + "_settings").update({views:{$exists:true}}, { - $set:obj - }, function(err, docs){ - - if(obj.adminpass !== "") obj.adminpass = true; - if(obj.hasOwnProperty("userpass") && obj.userpass != "") obj.userpass = true; - else obj.userpass = false; - io.to(channel_name).emit("conf", [obj]); - - db.collection("frontpage_lists").update({_id: channel_name}, {$set:{ - frontpage:frontpage, accessed: Functions.get_time()} - }, - {upsert:true}, function(err, docs){ - if(authorized) { - incrementToken(token); - } - //updateTimeout(guid, res, authorized, "CONFIG", function(err, docs) { - var to_return = error.no_error; - to_return.results = [obj]; - res.status(200).send(to_return); - return; - //}); - }); - }); - }); - } - }); - }); - }); - }); -}); - -router.route('/api/list/:channel_name/:video_id').put(function(req,res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - try { - if(!req.body.hasOwnProperty('adminpass') || !req.body.hasOwnProperty('userpass') || - !req.params.hasOwnProperty('channel_name') || !req.params.hasOwnProperty('video_id')) { - throw "Wrong format"; - } - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var adminpass = req.body.adminpass == "" ? "" : Functions.hash_pass(crypto.createHash('sha256').update(req.body.adminpass, 'utf8').digest("hex")); - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - var userpass = req.body.userpass; - var channel_name = cleanChannelName(req.params.channel_name); - var video_id = req.params.video_id; - if(typeof(userpass) != "string" || typeof(adminpass) != "string") { - throw "Wrong format"; - } - } catch(e) { - var result = { - adminpass: { - expected: "string", - got: req.body.hasOwnProperty("adminpass") ? typeof(req.body.adminpass) : undefined, - }, - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - var cookie = req.cookies._uI; - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.adminpass == "") { - adminpass = Functions.hash_pass(_a); - } - if(req.body.userpass == "") { - userpass = _u; - } - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; - } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "PUT", function() { - if(token != "" && !authorized) { - //updateTimeout(guid, res, authorized, "PUT", function(err, docs) { - res.status(400).send(error.wrong_token); - return; - //}); - } else { - validateLogin(adminpass, userpass, channel_name, "vote", res, function(exists) { - if(!exists) { - res.status(404).send(error.not_found.list); - return; - } - db.collection(channel_name).find({id: video_id, now_playing: false}, function(err, song) { - if(song.length == 0 || (song.hasOwnProperty("type") && song.type == "suggested")) { - res.status(404).send(error.not_found.local); - return; - } else if(song[0].guids.indexOf(guid) > -1) { - res.status(409).send(error.conflicting); - return; - } else { - song[0].votes += 1; - song[0].guids.push(guid); - db.collection(channel_name).update({id: video_id}, {$inc:{votes:1}, $set:{added:Functions.get_time(), type: "video"}, $push :{guids: guid}}, function(err, success) { - if(authorized) { - incrementToken(token); - } - io.to(channel_name).emit("channel", {type: "vote", value: video_id, time: Functions.get_time()}); - List.getNextSong(channel_name, undefined, function() { - //updateTimeout(guid, res, authorized, "PUT", function(err, docs) { - var to_return = error.no_error; - to_return.results = song; - res.status(200).send(to_return); - return; - //}); - }); - }); - } - }) - }); - } - }); - }); - }); - }); -}); - -router.route('/api/list/:channel_name/__np__').post(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - try { - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var channel_name = cleanChannelName(req.params.channel_name); - var userpass; - if(req.body.hasOwnProperty("userpass")) { - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - userpass = req.body.userpass; - } else { - userpass = ""; - } - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - } catch(e) { - var result = { - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - var cookie = req.cookies._uI; - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.userpass == "") { - //userpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(_u))) - userpass = _u; - } - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; - } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "POST", function() { - if(token != "" && !authorized) { - //updateTimeout(guid, res, authorized, "POST", function(err, docs) { - res.status(400).send(error.wrong_token); - return; - //}); - } else { - db.collection(channel_name).find({now_playing: true}, projects.toShowChannel, function(err, list) { - if(list.length > 0) { - db.collection(channel_name + "_settings").find({ id: "config" }, function(err, conf) { - if(authorized) { - incrementToken(token); - } - if(conf.length == 0) { - res.status(404).send(error.not_found.list); - return; - } else if(conf[0].userpass != userpass && conf[0].userpass != "" && conf[0].userpass != undefined) { - res.status(403).send(error.not_authenticated); - return; - } - //updateTimeout(guid, res, authorized, "POST", function(err, docs) { - var to_return = error.no_error; - if(list[0].source == undefined) { - list[0].source = "youtube"; - } - if(list[0].thumbnail == undefined) { - list[0].thumbnail = "https://img.youtube.com/vi/" + list[0].id + "/mqdefault.jpg" - } - to_return.results = list; - res.status(200).send(to_return); - return; - //}); - }); - } else { - res.status(404).send(error.not_found.list); - return; - } - }); - } - }); - }); - }); - }); -}); - - -router.route('/api/search/:channel_name/').post(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - try { - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var channel_name = cleanChannelName(req.params.channel_name); - var userpass; - if(req.body.hasOwnProperty("userpass")) { - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - userpass = req.body.userpass; - } else { - userpass = ""; - } - var page = 1; - if(req.body.hasOwnProperty("page") && req.body.page > 0) { - page = req.body.page; - } - var searchQuery = ""; - var searchByCategory = true; - if(req.body.hasOwnProperty("type")) { - searchByCategory = req.body.type == "category"; - } - if(req.body.searchQuery == undefined || req.body.searchQuery == "") { - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - searchQuery = req.body.searchQuery.toLowerCase(); - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - } catch(e) { - var result = { - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - var cookie = req.cookies._uI; - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.userpass == "") { - //userpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(_u))) - userpass = _u; - } - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; - } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "POST", function() { - db.collection(channel_name + "_settings").find({ id: "config" }, function(err, conf) { - if(authorized) { - incrementToken(token); - } - if(conf.length == 0) { - res.status(404).send(error.not_found.list); - return; - } else if(conf[0].userpass != userpass && conf[0].userpass != "" && conf[0].userpass != undefined) { - res.status(403).send(error.not_authenticated); - return; - } - - var querySubObject = { - $regex : ".*" + searchQuery + ".*" - }; - var queryObject = {}; - if(searchByCategory) { - queryObject.tags = querySubObject; - } else { - queryObject.title = querySubObject; - queryObject.title.$regex = searchQuery; - queryObject.title.$options = 'i'; - } - var query = db.collection(channel_name).find(queryObject); - paginate(query, { limit : 30, page : page }, function(err, result) { - if(result.items.length == 0) { - res.status(404).send(error.not_found.local); - return; - } - var to_return = error.no_error - to_return.results = {}; - if(result.hasNext) { - to_return.results.next = result.page + 1; - } - if(result.hasPrevious) { - to_return.results.prev = result.page - 1; - } - to_return.results.search_results = result.items; - - res.status(200).send(to_return); - }); - }); - }); - }); - }); - }); -}); - -router.route('/api/list/:channel_name/:video_id').post(function(req,res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - var fetch_only = false; - if(req.body.hasOwnProperty('fetch_song')) { - fetch_only = true; - } - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - try { - if(!fetch_only && (!req.body.hasOwnProperty('adminpass') || !req.body.hasOwnProperty('userpass') || - !req.params.hasOwnProperty('channel_name') || !req.params.hasOwnProperty('video_id') || - !req.body.hasOwnProperty('duration') || !req.body.hasOwnProperty('start_time') || - !req.body.hasOwnProperty('end_time') || !req.body.hasOwnProperty('title') || - !req.body.hasOwnProperty('source'))) { - - throw "Wrong format"; - } - - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var userpass; - if(req.body.hasOwnProperty("userpass")) { - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - userpass = req.body.userpass; - } else { - userpass = ""; - } - var channel_name = cleanChannelName(req.params.channel_name); - var video_id = req.params.video_id; - if(!fetch_only) { - var adminpass = req.body.adminpass == "" ? "" : Functions.hash_pass(crypto.createHash('sha256').update(req.body.adminpass, 'utf8').digest("hex")); - var duration = parseInt(req.body.duration); - var start_time = parseInt(req.body.start_time); - var end_time = parseInt(req.body.end_time); - var tags = []; - if(req.body.tags != undefined) tags = req.body.tags.split(","); - var source = req.body.source; - if(source == "soundcloud" && !req.body.hasOwnProperty("thumbnail")) { - throw "Wrong format"; - } - if(duration != end_time - start_time) duration = end_time - start_time; - var title = req.body.title; - if(typeof(userpass) != "string" || typeof(adminpass) != "string" || - typeof(title) != "string" || isNaN(duration) || isNaN(start_time) || isNaN(end_time)) { - throw "Wrong format"; - } - } - } catch(e) { - var result = { - adminpass: { - expected: "string", - got: req.body.hasOwnProperty("adminpass") ? typeof(req.body.adminpass) : undefined, - }, - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - }, - title: { - expected: "string", - got: req.body.hasOwnProperty("title") ? typeof(req.body.title) : undefined - }, - start_time: { - expected: "number or string that can be cast to int", - got: !req.body.hasOwnProperty("start_time") ? undefined : isNaN(req.body.start_time) ? "uncastable string" : typeof(req.body.start_time) - }, - end_time: { - expected: "number or string that can be cast to int", - got: !req.body.hasOwnProperty("end_time") ? undefined : isNaN(req.body.end_time) ? "uncastable string" : typeof(req.body.end_time) - }, - duration: { - expected: "number or string that can be cast to int", - got: !req.body.hasOwnProperty("duration") ? undefined : isNaN(req.body.duration) ? "uncastable string" : typeof(req.body.duration) - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; - } - var cookie = req.cookies._uI; - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.adminpass == "") { - adminpass = Functions.hash_pass(_a); - } - if(req.body.userpass == "") { - userpass = _u; - } - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; - } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "POST", function() { - if(token != "" && !authorized) { - //updateTimeout(guid, res, authorized, "POST", function(err, docs) { - res.status(400).send(error.wrong_token); - return; - //}); - } else { - var type = fetch_only ? "fetch_song" : "add"; - validateLogin(adminpass, userpass, channel_name, type, res, function(exists, conf, authenticated) { - db.collection(channel_name).find({id: video_id}, function(err, result) { - if(result.length == 0 || result[0].type == "suggested") { - var song_type = authenticated ? "video" : "suggested"; - if(fetch_only && result.length == 0) { - res.status(404).send(error.not_found.local); - return; - } - db.collection(channel_name).find({now_playing: true}, function(err, now_playing) { - var set_np = false; - if(now_playing.length == 0 && authenticated) { - set_np = true; - } - var new_song = {"tags": tags, "added": Functions.get_time(),"guids":[guid],"id":video_id,"now_playing":set_np,"title":title,"votes":1, "duration":duration, "start": parseInt(start_time), "end": parseInt(end_time), "type": song_type, "source": source}; - var runFunction = Search.get_correct_info; - if(source == "soundcloud") { - if(req.body.thumbnail.indexOf("https://i1.sndcdn.com") > -1 || req.body.thumbnail.indexOf("https://w1.sndcdn.com") > -1) { - new_song.thumbnail = req.body.thumbnail; - } else { - new_song.thumbnail = "https://img.youtube.com/vi/404_notfound/mqdefault.jpg"; - } - runFunction = function(new_song, foo_2, foo_3, callback) { - callback(new_song, true); - } - } else if(source == "youtube") new_song.thumbnail = "https://img.youtube.com/vi/" + new_song.id + "/mqdefault.jpg"; - runFunction(new_song, channel_name, false, function(element, found) { - if(!found) { - res.status(404).send(error.not_found.youtube); - return; - } - new_song = element; - db.collection("frontpage_lists").find({"_id": channel_name}, function(err, count) { - var create_frontpage_lists = false; - if(count.length == 0) { - create_frontpage_lists = true; - } - if(!exists) { - var configs = {"addsongs":false, "adminpass":"", "allvideos":true, "frontpage":true, "longsongs":false, "removeplay": false, "shuffle": true, "skip": false, "skips": [], "startTime":Functions.get_time(), "views": [], "vote": false, "desc": ""}; - db.collection(channel_name + "_settings").insert(configs, function(err, docs){ - io.to(channel_name).emit("conf", configs); - }); - } - db.collection(channel_name).update({"id": new_song.id}, new_song, {upsert: true}, function(err, success) { - if(authorized) { - incrementToken(token); - } - if(create_frontpage_lists) { - db.collection("frontpage_lists").update({"_id": channel_name, "count" : (authenticated ? 1 : 0), "frontpage": true, "accessed": Functions.get_time(), "viewers": 1}, {upsert: true}, function(err, docs) { - if(authenticated) { - io.to(channel_name).emit("channel", {type: "added", value: new_song}); - } else { - io.to(channel_name).emit("suggested", new_song); - } - postEnd(channel_name, configs, new_song, guid, res, authenticated, authorized); - }); - } else if(set_np) { - var thumbnail = req.body.thumbnail != undefined ? req.body.thumbnail : undefined; - Frontpage.update_frontpage(channel_name, video_id, title, thumbnail, source, function() { - io.to(channel_name).emit("np", {np: [new_song], conf: [conf]}); - postEnd(channel_name, configs, new_song, guid, res, authenticated, authorized); - }); - } else { - db.collection("frontpage_lists").update({"_id": channel_name}, {$inc: {count: (authenticated ? 1 : 0)}}, function(err, docs) { - if(authenticated) { - io.to(channel_name).emit("channel", {type: "added", value: new_song}); - } else { - io.to(channel_name).emit("suggested", new_song); - } - postEnd(channel_name, configs, new_song, guid, res, authenticated, authorized); - }); - } - }); - }) - }); - }); - } else if(fetch_only) { - var to_return = error.no_error; - to_return.results = result; - res.status(200).send(to_return); - return; - } else { - res.status(409).send(error.conflicting); - return; - } - }); - }); - } - }); - }); - }); - }); -}); - -router.route('/api/list/:channel_name').get(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - var channel_name = cleanChannelName(req.params.channel_name); - db.collection(channel_name).aggregate([ - { - "$match": { - "type": { - "$ne": "suggested" - } - } - }, - { - "$project": projects.project_object - }, - { "$sort" : { "now_playing" : -1, "votes": -1, "added": 1, "title": 1 } } - ], function(err, docs) { - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - //db.collection(channel_name).find({views: {$exists: false}}, projects.toShowChannel, function(err, docs) { - checkTimeout(guid, res, false, "GET", function() { - if(docs.length > 0) { - db.collection(channel_name + "_settings").find({ id: "config" }, function(err, conf) { - if(conf.length == 0) { - res.status(404).send(error.not_found.list); - return; - } else if(conf[0].userpass != "" && conf[0].userpass != undefined) { - res.status(403).send(error.not_authenticated); - return; - } - var to_return = error.no_error; - to_return.results = docs; - res.status(200).send(to_return); - }); - } else { - res.status(404).send(error.not_found.list); - } - }); - }); -}); - -router.route('/api/list/:channel_name/:video_id').get(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - - checkTimeout(guid, res, false, "GET", function() { - var channel_name = cleanChannelName(req.params.channel_name); - var video_id = req.params.video_id; - var searchQuery = {id: video_id}; - if(video_id == "__np__") { - searchQuery = {now_playing: true}; - } - db.collection(channel_name).find(searchQuery, projects.toShowChannel, function(err, docs) { - db.collection(channel_name + "_settings").find({ id: "config" }, function(err, conf) { - if(conf.length == 0) { + validateLogin( + adminpass, + userpass, + channel_name, + "delete", + res, + function(exists) { + if (!exists) { res.status(404).send(error.not_found.list); return; - } else if(conf[0].userpass != "" && conf[0].userpass != undefined) { - res.status(403).send(error.not_authenticated); - return; + } + db.collection(channel_name).find( + { id: video_id, now_playing: false }, + function(err, docs) { + if (docs.length == 0) { + res.status(404).send(error.not_found.local); + return; + } + var dont_increment = false; + if (docs[0]) { + if (docs[0].type == "suggested") { + dont_increment = true; + } + db.collection(channel_name).remove( + { id: video_id }, + function(err, docs) { + if (authorized) { + incrementToken(token); + } + io.to(channel_name).emit("channel", { + type: "deleted", + value: video_id + }); + if (!dont_increment) { + db.collection("frontpage_lists").update( + { _id: channel_name, count: { $gt: 0 } }, + { + $inc: { count: -1 }, + $set: { accessed: Functions.get_time() } + }, + { upsert: true }, + function(err, docs) { + //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { + res.status(200).send(error.no_error); + return; + //}); + } + ); + } else { + //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { + res.status(200).send(error.no_error); + return; + //}); + } + } + ); + } + } + ); } - if(docs.length == 0) { + ); + } + }); + }); + }); + }); +}); + +router.route("/api/skip/:channel_name").post(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + + var api_key = req.body.api_key; + var guid = req.body.chat_name; + var channel_name = cleanChannelName(req.params.channel_name); + var userpass = ""; + if (req.body.userpass && req.body.userpass != "") + userpass = crypto + .createHash("sha256") + .update(Functions.decrypt_string(req.body.userpass)) + .digest("base64"); + if (allowed_key.indexOf(api_key) > -1 || allowed_key.indexOf("***") > -1) { + db.collection(channel_name + "_settings").find({ id: "config" }, function( + err, + settings + ) { + if (settings.length == 0) { + res.status(404).send(error.not_found.list); + return; + } + settings = settings[0]; + if (!settings.strictSkip) { + res.status(409).send(error.settings); + return; + } + if (settings.userpass == "" || settings.userpass == userpass) { + if ( + settings.skips.length + 1 >= settings.strictSkipNumber && + !Functions.contains(settings.skips, guid) + ) { + Functions.checkTimeout( + "skip", + 1, + channel_name, + channel_name, + false, + true, + undefined, + function() { + db.collection(channel_name).find({ now_playing: true }, function( + err, + np + ) { + if (np.length != 1) { + res.status(404).send(error.not_found.list); + return; + } + List.change_song( + channel_name, + false, + np[0].id, + [settings], + function() { + res.status(200).send(error.no_error); + return; + } + ); + _exports.sIO.to(channel_name).emit("chat", { + from: guid, + icon: false, + msg: " skipped via API." + }); + }); + }, + "", + function() { + res.status(429).send(error.tooMany); + return; + } + ); + } else if (!Functions.contains(settings.skips, guid)) { + db.collection(channel_name + "_settings").update( + { id: "config" }, + { $push: { skips: guid } }, + function(err, d) { + var to_skip = + settings.strictSkipNumber - settings.skips.length - 1; + _exports.sIO + .to(channel_name) + .emit("chat", { from: guid, msg: " voted to skip via API." }); + // VOTED TO SKIP + var to_send = error.more_skip_needed; + to_send.results = [to_skip]; + res.status(202).send(to_send); + return; + } + ); + } else { + //ALREADY SKIP + res.status(206).send(error.already_skip); + return; + } + } else { + // NOT AUTHENTICATED + res.status(403).send(error.not_authenticated); + return; + } + }); + } else { + // WRONG API KEY + var toSend = error.not_authenticated; + toSend.status = 406; + res.status(406).send(toSend); + return; + } +}); + +router.route("/api/conf/:channel_name").put(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + + try { + if ( + !req.body.hasOwnProperty("adminpass") || + !req.body.hasOwnProperty("userpass") || + !req.params.hasOwnProperty("channel_name") || + !req.body.hasOwnProperty("vote") || + !req.body.hasOwnProperty("addsongs") || + !req.body.hasOwnProperty("longsongs") || + !req.body.hasOwnProperty("frontpage") || + !req.body.hasOwnProperty("allvideos") || + !req.body.hasOwnProperty("skip") || + !req.body.hasOwnProperty("shuffle") || + !req.body.hasOwnProperty("userpass_changed") + ) { + throw "Wrong format"; + } + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var adminpass = + req.body.adminpass == "" + ? "" + : Functions.hash_pass( + crypto + .createHash("sha256") + .update(req.body.adminpass, "utf8") + .digest("hex") + ); + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + var userpass = req.body.userpass; + var voting = req.body.vote; + var addsongs = req.body.addsongs; + var longsongs = req.body.longsongs; + var frontpage = req.body.frontpage; + var allvideos = req.body.allvideos; + var removeplay = req.body.removeplay; + var skipping = req.body.skip; + var shuffling = req.body.shuffle; + var userpass_changed = req.body.userpass_changed; + var channel_name = cleanChannelName(req.params.channel_name); + if ( + typeof userpass != "string" || + typeof adminpass != "string" || + typeof voting != "boolean" || + typeof addsongs != "boolean" || + typeof longsongs != "boolean" || + typeof frontpage != "boolean" || + typeof allvideos != "boolean" || + typeof removeplay != "boolean" || + typeof skipping != "boolean" || + typeof shuffling != "boolean" || + typeof userpass_changed != "boolean" + ) { + throw "Wrong format"; + } + } catch (e) { + var result = { + adminpass: { + expected: "string", + got: req.body.hasOwnProperty("adminpass") + ? typeof req.body.adminpass + : undefined + }, + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + }, + vote: { + expected: "boolean", + got: req.body.hasOwnProperty("vote") ? typeof req.body.vote : undefined + }, + addsongs: { + expected: "boolean", + got: req.body.hasOwnProperty("addsongs") + ? typeof req.body.addsongs + : undefined + }, + longsongs: { + expected: "boolean", + got: req.body.hasOwnProperty("longsongs") + ? typeof req.body.longsongs + : undefined + }, + frontpage: { + expected: "boolean", + got: req.body.hasOwnProperty("frontpage") + ? typeof req.body.frontpage + : undefined + }, + skip: { + expected: "boolean", + got: req.body.hasOwnProperty("skip") ? typeof req.body.skip : undefined + }, + shuffle: { + expected: "boolean", + got: req.body.hasOwnProperty("shuffle") + ? typeof req.body.shuffle + : undefined + }, + userpass_changed: { + expected: "boolean", + got: req.body.hasOwnProperty("userpass_changed") + ? typeof req.body.userpass_changed + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + var cookie = req.cookies._uI; + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.adminpass == "") { + adminpass = Functions.hash_pass(_a); + } + if (req.body.userpass == "") { + userpass = _u; + } + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "CONFIG", function() { + if (token != "" && !authorized) { + //updateTimeout(guid, res, authorized, "CONFIG", function(err, docs) { + res.status(400).send(error.wrong_token); + return; + //}); + } else { + validateLogin( + adminpass, + userpass, + channel_name, + "config", + res, + function(exists, conf) { + if (!exists && conf.length == 0) { + res.status(404).send(error.not_found.list); + return; + } + + if ( + (!userpass_changed && frontpage) || + (userpass_changed && userpass == "") + ) { + userpass = ""; + } else if (userpass_changed && userpass != "") { + frontpage = false; + } + var description = ""; + + var obj = { + addsongs: addsongs, + allvideos: allvideos, + frontpage: frontpage, + skip: skipping, + vote: voting, + removeplay: removeplay, + shuffle: shuffling, + longsongs: longsongs, + adminpass: adminpass, + desc: description + }; + if (userpass_changed) { + obj["userpass"] = userpass; + } else if (frontpage) { + obj["userpass"] = ""; + } + db.collection(channel_name + "_settings").update( + { views: { $exists: true } }, + { + $set: obj + }, + function(err, docs) { + if (obj.adminpass !== "") obj.adminpass = true; + if (obj.hasOwnProperty("userpass") && obj.userpass != "") + obj.userpass = true; + else obj.userpass = false; + io.to(channel_name).emit("conf", [obj]); + + db.collection("frontpage_lists").update( + { _id: channel_name }, + { + $set: { + frontpage: frontpage, + accessed: Functions.get_time() + } + }, + { upsert: true }, + function(err, docs) { + if (authorized) { + incrementToken(token); + } + //updateTimeout(guid, res, authorized, "CONFIG", function(err, docs) { + var to_return = error.no_error; + to_return.results = [obj]; + res.status(200).send(to_return); + return; + //}); + } + ); + } + ); + } + ); + } + }); + }); + }); + }); +}); + +router.route("/api/list/:channel_name/:video_id").put(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + try { + if ( + !req.body.hasOwnProperty("adminpass") || + !req.body.hasOwnProperty("userpass") || + !req.params.hasOwnProperty("channel_name") || + !req.params.hasOwnProperty("video_id") + ) { + throw "Wrong format"; + } + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var adminpass = + req.body.adminpass == "" + ? "" + : Functions.hash_pass( + crypto + .createHash("sha256") + .update(req.body.adminpass, "utf8") + .digest("hex") + ); + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + var userpass = req.body.userpass; + var channel_name = cleanChannelName(req.params.channel_name); + var video_id = req.params.video_id; + if (typeof userpass != "string" || typeof adminpass != "string") { + throw "Wrong format"; + } + } catch (e) { + var result = { + adminpass: { + expected: "string", + got: req.body.hasOwnProperty("adminpass") + ? typeof req.body.adminpass + : undefined + }, + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + var cookie = req.cookies._uI; + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.adminpass == "") { + adminpass = Functions.hash_pass(_a); + } + if (req.body.userpass == "") { + userpass = _u; + } + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "PUT", function() { + if (token != "" && !authorized) { + //updateTimeout(guid, res, authorized, "PUT", function(err, docs) { + res.status(400).send(error.wrong_token); + return; + //}); + } else { + validateLogin( + adminpass, + userpass, + channel_name, + "vote", + res, + function(exists) { + if (!exists) { + res.status(404).send(error.not_found.list); + return; + } + db.collection(channel_name).find( + { id: video_id, now_playing: false }, + function(err, song) { + if ( + song.length == 0 || + (song.hasOwnProperty("type") && + song.type == "suggested") + ) { + res.status(404).send(error.not_found.local); + return; + } else if (song[0].guids.indexOf(guid) > -1) { + res.status(409).send(error.conflicting); + return; + } else { + song[0].votes += 1; + song[0].guids.push(guid); + db.collection(channel_name).update( + { id: video_id }, + { + $inc: { votes: 1 }, + $set: { + added: Functions.get_time(), + type: "video" + }, + $push: { guids: guid } + }, + function(err, success) { + if (authorized) { + incrementToken(token); + } + io.to(channel_name).emit("channel", { + type: "vote", + value: video_id, + time: Functions.get_time() + }); + List.getNextSong( + channel_name, + undefined, + function() { + //updateTimeout(guid, res, authorized, "PUT", function(err, docs) { + var to_return = error.no_error; + to_return.results = song; + res.status(200).send(to_return); + return; + //}); + } + ); + } + ); + } + } + ); + } + ); + } + }); + }); + }); + }); +}); + +router.route("/api/list/:channel_name/__np__").post(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + try { + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var channel_name = cleanChannelName(req.params.channel_name); + var userpass; + if (req.body.hasOwnProperty("userpass")) { + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + userpass = req.body.userpass; + } else { + userpass = ""; + } + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + } catch (e) { + var result = { + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + var cookie = req.cookies._uI; + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.userpass == "") { + //userpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(_u))) + userpass = _u; + } + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "POST", function() { + if (token != "" && !authorized) { + //updateTimeout(guid, res, authorized, "POST", function(err, docs) { + res.status(400).send(error.wrong_token); + return; + //}); + } else { + db.collection(channel_name).find( + { now_playing: true }, + projects.toShowChannel, + function(err, list) { + if (list.length > 0) { + db.collection(channel_name + "_settings").find( + { id: "config" }, + function(err, conf) { + if (authorized) { + incrementToken(token); + } + if (conf.length == 0) { + res.status(404).send(error.not_found.list); + return; + } else if ( + conf[0].userpass != userpass && + conf[0].userpass != "" && + conf[0].userpass != undefined + ) { + res.status(403).send(error.not_authenticated); + return; + } + //updateTimeout(guid, res, authorized, "POST", function(err, docs) { + var to_return = error.no_error; + if (list[0].source == undefined) { + list[0].source = "youtube"; + } + if (list[0].thumbnail == undefined) { + list[0].thumbnail = + "https://img.youtube.com/vi/" + + list[0].id + + "/mqdefault.jpg"; + } + to_return.results = list; + res.status(200).send(to_return); + return; + //}); + } + ); + } else { + res.status(404).send(error.not_found.list); + return; + } + } + ); + } + }); + }); + }); + }); +}); + +router.route("/api/search/:channel_name/").post(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + try { + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var channel_name = cleanChannelName(req.params.channel_name); + var userpass; + if (req.body.hasOwnProperty("userpass")) { + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + userpass = req.body.userpass; + } else { + userpass = ""; + } + var page = 1; + if (req.body.hasOwnProperty("page") && req.body.page > 0) { + page = req.body.page; + } + var searchQuery = ""; + var searchByCategory = true; + if (req.body.hasOwnProperty("type")) { + searchByCategory = req.body.type == "category"; + } + if (req.body.searchQuery == undefined || req.body.searchQuery == "") { + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + searchQuery = req.body.searchQuery.toLowerCase(); + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + } catch (e) { + var result = { + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + var cookie = req.cookies._uI; + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.userpass == "") { + //userpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(_u))) + userpass = _u; + } + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "POST", function() { + db.collection(channel_name + "_settings").find( + { id: "config" }, + function(err, conf) { + if (authorized) { + incrementToken(token); + } + if (conf.length == 0) { + res.status(404).send(error.not_found.list); + return; + } else if ( + conf[0].userpass != userpass && + conf[0].userpass != "" && + conf[0].userpass != undefined + ) { + res.status(403).send(error.not_authenticated); + return; + } + + var querySubObject = { + $regex: ".*" + searchQuery + ".*" + }; + var queryObject = {}; + if (searchByCategory) { + queryObject.tags = querySubObject; + } else { + queryObject.title = querySubObject; + queryObject.title.$regex = searchQuery; + queryObject.title.$options = "i"; + } + var query = db.collection(channel_name).find(queryObject); + paginate(query, { limit: 30, page: page }, function( + err, + result + ) { + if (result.items.length == 0) { res.status(404).send(error.not_found.local); return; - } - var to_return = error.no_error; - if(docs[0].source == undefined) { - docs[0].source = "youtube"; - } - if(docs[0].thumbnail == undefined) { - docs[0].thumbnail = "https://img.youtube.com/vi/" + docs[0].id + "/mqdefault.jpg" - } - to_return.results = docs; - res.status(200).send(to_return); - return; - }); + } + var to_return = error.no_error; + to_return.results = {}; + if (result.hasNext) { + to_return.results.next = result.page + 1; + } + if (result.hasPrevious) { + to_return.results.prev = result.page - 1; + } + to_return.results.search_results = result.items; + + res.status(200).send(to_return); + }); + } + ); + }); }); - }); + }); + }); }); -router.route('/api/conf/:channel_name').get(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); +router.route("/api/list/:channel_name/:video_id").post(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + var fetch_only = false; + if (req.body.hasOwnProperty("fetch_song")) { + fetch_only = true; + } + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + try { + if ( + !fetch_only && + (!req.body.hasOwnProperty("adminpass") || + !req.body.hasOwnProperty("userpass") || + !req.params.hasOwnProperty("channel_name") || + !req.params.hasOwnProperty("video_id") || + !req.body.hasOwnProperty("duration") || + !req.body.hasOwnProperty("start_time") || + !req.body.hasOwnProperty("end_time") || + !req.body.hasOwnProperty("title") || + !req.body.hasOwnProperty("source")) + ) { + throw "Wrong format"; + } - checkTimeout(guid, res, false, "GET", function() { - var channel_name = cleanChannelName(req.params.channel_name); - db.collection(channel_name + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs.length > 0 && (docs[0].userpass == "" || docs[0].userpass == undefined)) { - var conf = docs[0]; - if(conf.adminpass != "") { - conf.adminpass = true; - } else { - conf.adminpass = false; - } - if(conf.userpass != "" && conf.userpass != undefined) { - conf.userpass = true; - } else { - conf.userpass = false; - } - var to_return = error.no_error; - to_return.results = [conf]; - res.status(200).send(to_return); - } else if(docs.length > 0 && docs[0].userpass != "" && docs[0].userpass != undefined){ - res.status(403).send(error.not_authenticated); - return; + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var userpass; + if (req.body.hasOwnProperty("userpass")) { + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + userpass = req.body.userpass; + } else { + userpass = ""; + } + var channel_name = cleanChannelName(req.params.channel_name); + var video_id = req.params.video_id; + if (!fetch_only) { + var adminpass = + req.body.adminpass == "" + ? "" + : Functions.hash_pass( + crypto + .createHash("sha256") + .update(req.body.adminpass, "utf8") + .digest("hex") + ); + var duration = parseInt(req.body.duration); + var start_time = parseInt(req.body.start_time); + var end_time = parseInt(req.body.end_time); + var tags = []; + if (req.body.tags != undefined) tags = req.body.tags.split(","); + var source = req.body.source; + if (source == "soundcloud" && !req.body.hasOwnProperty("thumbnail")) { + throw "Wrong format"; + } + if (duration != end_time - start_time) duration = end_time - start_time; + var title = req.body.title; + if ( + typeof userpass != "string" || + typeof adminpass != "string" || + typeof title != "string" || + isNaN(duration) || + isNaN(start_time) || + isNaN(end_time) + ) { + throw "Wrong format"; + } + } + } catch (e) { + var result = { + adminpass: { + expected: "string", + got: req.body.hasOwnProperty("adminpass") + ? typeof req.body.adminpass + : undefined + }, + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + }, + title: { + expected: "string", + got: req.body.hasOwnProperty("title") + ? typeof req.body.title + : undefined + }, + start_time: { + expected: "number or string that can be cast to int", + got: !req.body.hasOwnProperty("start_time") + ? undefined + : isNaN(req.body.start_time) + ? "uncastable string" + : typeof req.body.start_time + }, + end_time: { + expected: "number or string that can be cast to int", + got: !req.body.hasOwnProperty("end_time") + ? undefined + : isNaN(req.body.end_time) + ? "uncastable string" + : typeof req.body.end_time + }, + duration: { + expected: "number or string that can be cast to int", + got: !req.body.hasOwnProperty("duration") + ? undefined + : isNaN(req.body.duration) + ? "uncastable string" + : typeof req.body.duration + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + var cookie = req.cookies._uI; + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.adminpass == "") { + adminpass = Functions.hash_pass(_a); + } + if (req.body.userpass == "") { + userpass = _u; + } + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "POST", function() { + if (token != "" && !authorized) { + //updateTimeout(guid, res, authorized, "POST", function(err, docs) { + res.status(400).send(error.wrong_token); + return; + //}); } else { + var type = fetch_only ? "fetch_song" : "add"; + validateLogin( + adminpass, + userpass, + channel_name, + type, + res, + function(exists, conf, authenticated) { + db.collection(channel_name).find({ id: video_id }, function( + err, + result + ) { + if (result.length == 0 || result[0].type == "suggested") { + var song_type = authenticated ? "video" : "suggested"; + if (fetch_only && result.length == 0) { + res.status(404).send(error.not_found.local); + return; + } + db.collection(channel_name).find( + { now_playing: true }, + function(err, now_playing) { + var set_np = false; + if (now_playing.length == 0 && authenticated) { + set_np = true; + } + var new_song = { + tags: tags, + added: Functions.get_time(), + guids: [guid], + id: video_id, + now_playing: set_np, + title: title, + votes: 1, + duration: duration, + start: parseInt(start_time), + end: parseInt(end_time), + type: song_type, + source: source + }; + var runFunction = Search.get_correct_info; + if (source == "soundcloud") { + if ( + req.body.thumbnail.indexOf( + "https://i1.sndcdn.com" + ) > -1 || + req.body.thumbnail.indexOf( + "https://w1.sndcdn.com" + ) > -1 + ) { + new_song.thumbnail = req.body.thumbnail; + } else { + new_song.thumbnail = + "https://img.youtube.com/vi/404_notfound/mqdefault.jpg"; + } + runFunction = function( + new_song, + foo_2, + foo_3, + callback + ) { + callback(new_song, true); + }; + } else if (source == "youtube") + new_song.thumbnail = + "https://img.youtube.com/vi/" + + new_song.id + + "/mqdefault.jpg"; + runFunction(new_song, channel_name, false, function( + element, + found + ) { + if (!found) { + res.status(404).send(error.not_found.youtube); + return; + } + new_song = element; + db.collection("frontpage_lists").find( + { _id: channel_name }, + function(err, count) { + var create_frontpage_lists = false; + if (count.length == 0) { + create_frontpage_lists = true; + } + if (!exists) { + var configs = { + addsongs: false, + adminpass: "", + allvideos: true, + frontpage: true, + longsongs: false, + removeplay: false, + shuffle: true, + skip: false, + skips: [], + startTime: Functions.get_time(), + views: [], + vote: false, + desc: "" + }; + db.collection( + channel_name + "_settings" + ).insert(configs, function(err, docs) { + io.to(channel_name).emit("conf", configs); + }); + } + db.collection(channel_name).update( + { id: new_song.id }, + new_song, + { upsert: true }, + function(err, success) { + if (authorized) { + incrementToken(token); + } + if (create_frontpage_lists) { + db.collection("frontpage_lists").update( + { + _id: channel_name, + count: authenticated ? 1 : 0, + frontpage: true, + accessed: Functions.get_time(), + viewers: 1 + }, + { upsert: true }, + function(err, docs) { + if (authenticated) { + io.to(channel_name).emit( + "channel", + { type: "added", value: new_song } + ); + } else { + io.to(channel_name).emit( + "suggested", + new_song + ); + } + postEnd( + channel_name, + configs, + new_song, + guid, + res, + authenticated, + authorized + ); + } + ); + } else if (set_np) { + var thumbnail = + req.body.thumbnail != undefined + ? req.body.thumbnail + : undefined; + Frontpage.update_frontpage( + channel_name, + video_id, + title, + thumbnail, + source, + function() { + io.to(channel_name).emit("np", { + np: [new_song], + conf: [conf] + }); + postEnd( + channel_name, + configs, + new_song, + guid, + res, + authenticated, + authorized + ); + } + ); + } else { + db.collection("frontpage_lists").update( + { _id: channel_name }, + { + $inc: { count: authenticated ? 1 : 0 } + }, + function(err, docs) { + if (authenticated) { + io.to(channel_name).emit( + "channel", + { type: "added", value: new_song } + ); + } else { + io.to(channel_name).emit( + "suggested", + new_song + ); + } + postEnd( + channel_name, + configs, + new_song, + guid, + res, + authenticated, + authorized + ); + } + ); + } + } + ); + } + ); + }); + } + ); + } else if (fetch_only) { + var to_return = error.no_error; + to_return.results = result; + res.status(200).send(to_return); + return; + } else { + res.status(409).send(error.conflicting); + return; + } + }); + } + ); + } + }); + }); + }); + }); +}); + +router.route("/api/list/:channel_name").get(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + var channel_name = cleanChannelName(req.params.channel_name); + db.collection(channel_name).aggregate( + [ + { + $match: { + type: { + $ne: "suggested" + } + } + }, + { + $project: projects.project_object + }, + { $sort: { now_playing: -1, votes: -1, added: 1, title: 1 } } + ], + function(err, docs) { + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + //db.collection(channel_name).find({views: {$exists: false}}, projects.toShowChannel, function(err, docs) { + checkTimeout(guid, res, false, "GET", function() { + if (docs.length > 0) { + db.collection(channel_name + "_settings").find( + { id: "config" }, + function(err, conf) { + if (conf.length == 0) { res.status(404).send(error.not_found.list); return; + } else if ( + conf[0].userpass != "" && + conf[0].userpass != undefined + ) { + res.status(403).send(error.not_authenticated); + return; + } + var to_return = error.no_error; + to_return.results = docs; + res.status(200).send(to_return); } - }); - }); + ); + } else { + res.status(404).send(error.not_found.list); + } + }); + } + ); }); -router.route('/api/conf/:channel_name').post(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); +router.route("/api/list/:channel_name/:video_id").get(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); - try { - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var channel_name = cleanChannelName(req.params.channel_name); - var userpass; - if(req.body.hasOwnProperty("userpass")) { - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - userpass = req.body.userpass; - } else { - userpass = ""; - } - } catch(e) { - var result = { - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); - return; + checkTimeout(guid, res, false, "GET", function() { + var channel_name = cleanChannelName(req.params.channel_name); + var video_id = req.params.video_id; + var searchQuery = { id: video_id }; + if (video_id == "__np__") { + searchQuery = { now_playing: true }; } - var cookie = req.cookies._uI; - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.userpass == "") { - userpass = crypto.createHash('sha256').update(Functions.decrypt_string("", _u), 'utf8').digest("base64"); - } - - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; + db.collection(channel_name).find( + searchQuery, + projects.toShowChannel, + function(err, docs) { + db.collection(channel_name + "_settings").find( + { id: "config" }, + function(err, conf) { + if (conf.length == 0) { + res.status(404).send(error.not_found.list); + return; + } else if ( + conf[0].userpass != "" && + conf[0].userpass != undefined + ) { + res.status(403).send(error.not_authenticated); + return; } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "POST", function() { - if(token != "" && !authorized) { - //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { - res.status(400).send(error.wrong_token); - return; - //}); - } else { - db.collection(channel_name + "_settings").aggregate([ - { - "$match": { - id: "config" - } - }, - { - "$project": projects.toShowConfig - }, - ], function(err, docs) { - if(docs.length > 0 && docs[0].userpass == userpass) { - var conf = docs[0]; - if(conf.adminpass != "") { - conf.adminpass = true; - } else { - conf.adminpass = false; - } - if(conf.userpass != "") { - conf.userpass = true; - } else { - conf.userpass = false; - } - if(authorized) { - incrementToken(token); - } - //updateTimeout(guid, res, authorized, "POST", function(err, docs) { - var to_return = error.no_error; - to_return.results = [conf]; - res.status(200).send(to_return); - //}); - } else if(docs.length > 0 && docs[0].userpass != userpass) { - res.status(403).send(error.not_authenticated); - return; - } else { - res.status(404).send(error.not_found.list); - return; - } - }); + if (docs.length == 0) { + res.status(404).send(error.not_found.local); + return; + } + var to_return = error.no_error; + if (docs[0].source == undefined) { + docs[0].source = "youtube"; + } + if (docs[0].thumbnail == undefined) { + docs[0].thumbnail = + "https://img.youtube.com/vi/" + docs[0].id + "/mqdefault.jpg"; + } + to_return.results = docs; + res.status(200).send(to_return); + return; + } + ); + } + ); + }); +}); + +router.route("/api/conf/:channel_name").get(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + + checkTimeout(guid, res, false, "GET", function() { + var channel_name = cleanChannelName(req.params.channel_name); + db.collection(channel_name + "_settings").aggregate( + [ + { + $match: { + id: "config" + } + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if ( + docs.length > 0 && + (docs[0].userpass == "" || docs[0].userpass == undefined) + ) { + var conf = docs[0]; + if (conf.adminpass != "") { + conf.adminpass = true; + } else { + conf.adminpass = false; + } + if (conf.userpass != "" && conf.userpass != undefined) { + conf.userpass = true; + } else { + conf.userpass = false; + } + var to_return = error.no_error; + to_return.results = [conf]; + res.status(200).send(to_return); + } else if ( + docs.length > 0 && + docs[0].userpass != "" && + docs[0].userpass != undefined + ) { + res.status(403).send(error.not_authenticated); + return; + } else { + res.status(404).send(error.not_found.list); + return; + } + } + ); + }); +}); + +router.route("/api/conf/:channel_name").post(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + + try { + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var channel_name = cleanChannelName(req.params.channel_name); + var userpass; + if (req.body.hasOwnProperty("userpass")) { + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + userpass = req.body.userpass; + } else { + userpass = ""; + } + } catch (e) { + var result = { + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); + return; + } + var cookie = req.cookies._uI; + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.userpass == "") { + userpass = crypto + .createHash("sha256") + .update(Functions.decrypt_string("", _u), "utf8") + .digest("base64"); + } + + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "POST", function() { + if (token != "" && !authorized) { + //updateTimeout(guid, res, authorized, "DELETE", function(err, docs) { + res.status(400).send(error.wrong_token); + return; + //}); + } else { + db.collection(channel_name + "_settings").aggregate( + [ + { + $match: { + id: "config" } - }); - }); + }, + { + $project: projects.toShowConfig + } + ], + function(err, docs) { + if (docs.length > 0 && docs[0].userpass == userpass) { + var conf = docs[0]; + if (conf.adminpass != "") { + conf.adminpass = true; + } else { + conf.adminpass = false; + } + if (conf.userpass != "") { + conf.userpass = true; + } else { + conf.userpass = false; + } + if (authorized) { + incrementToken(token); + } + //updateTimeout(guid, res, authorized, "POST", function(err, docs) { + var to_return = error.no_error; + to_return.results = [conf]; + res.status(200).send(to_return); + //}); + } else if (docs.length > 0 && docs[0].userpass != userpass) { + res.status(403).send(error.not_authenticated); + return; + } else { + res.status(404).send(error.not_found.list); + return; + } + } + ); + } + }); }); - }); + }); + }); }); function checkOveruseApiToken(authorized, token_docs, res, callback) { - if(!authorized || (authorized && token_docs[0].limit == 0)) { - callback(); - return; - } + if (!authorized || (authorized && token_docs[0].limit == 0)) { + callback(); + return; + } - db.collection("timeout_api").find({guid: token_docs[0].token}, function(e, doc) { - if(doc.length == 1) { - var this_doc = doc[0]; - var date = new Date(this_doc.createdAt); - date.setSeconds(date.getSeconds() + 1); - var now = new Date(); - var retry_in = (date.getTime() - now.getTime()) / 1000; - if(this_doc.used >= token_docs[0].limit && retry_in > 0) { - res.header({'Retry-After': retry_in}); - res.status(429).send(error.tooMany); - return; - } else { - var updateElement = {}; - if(retry_in <= 0) { - updateElement["$set"] = {createdAt: new Date(), used: 1}; - } else { - updateElement["$inc"] = {used: 1}; - } - db.collection("timeout_api").update({guid: token_docs[0].token}, updateElement, function(e, d) { - callback(); - }); - } + db.collection("timeout_api").find({ guid: token_docs[0].token }, function( + e, + doc + ) { + if (doc.length == 1) { + var this_doc = doc[0]; + var date = new Date(this_doc.createdAt); + date.setSeconds(date.getSeconds() + 1); + var now = new Date(); + var retry_in = (date.getTime() - now.getTime()) / 1000; + if (this_doc.used >= token_docs[0].limit && retry_in > 0) { + res.header({ "Retry-After": retry_in }); + res.status(429).send(error.tooMany); + return; + } else { + var updateElement = {}; + if (retry_in <= 0) { + updateElement["$set"] = { createdAt: new Date(), used: 1 }; } else { - db.collection("timeout_api").update({guid: token_docs[0].token}, {$set: {guid: token_docs[0].token, createdAt: new Date(), type: "ALL"}, $inc: {used: 1}}, {upsert: true}, function(e, d) { - callback(); - }); + updateElement["$inc"] = { used: 1 }; } - }); + db.collection("timeout_api").update( + { guid: token_docs[0].token }, + updateElement, + function(e, d) { + callback(); + } + ); + } + } else { + db.collection("timeout_api").update( + { guid: token_docs[0].token }, + { + $set: { + guid: token_docs[0].token, + createdAt: new Date(), + type: "ALL" + }, + $inc: { used: 1 } + }, + { upsert: true }, + function(e, d) { + callback(); + } + ); + } + }); } -router.route('/api/list/:channel_name').post(function(req, res) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - res.header({"Content-Type": "application/json"}); - try { - var token = ""; - if(req.body.hasOwnProperty("token")) { - token = req.body.token; - } - var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - var guid = Functions.hash_pass(req.get('User-Agent') + ip + req.headers["accept-language"]); - var channel_name = cleanChannelName(req.params.channel_name); - var userpass; - if(req.body.hasOwnProperty("userpass")) { - req.body.userpass = req.body.userpass == "" ? "" : crypto.createHash('sha256').update(req.body.userpass, 'utf8').digest("base64"); - userpass = req.body.userpass; - } else { - userpass = ""; - } +router.route("/api/list/:channel_name").post(function(req, res) { + res.header("Access-Control-Allow-Origin", "*"); + res.header( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + res.header({ "Content-Type": "application/json" }); + try { + var token = ""; + if (req.body.hasOwnProperty("token")) { + token = req.body.token; + } + var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; + var guid = Functions.hash_pass( + req.get("User-Agent") + ip + req.headers["accept-language"] + ); + var channel_name = cleanChannelName(req.params.channel_name); + var userpass; + if (req.body.hasOwnProperty("userpass")) { + req.body.userpass = + req.body.userpass == "" + ? "" + : crypto + .createHash("sha256") + .update(req.body.userpass, "utf8") + .digest("base64"); + userpass = req.body.userpass; + } else { + userpass = ""; + } - /*if(typeof(userpass) != "string") { + /*if(typeof(userpass) != "string") { throw "Wrong format"; }*/ - } catch(e) { - var result = { - userpass: { - expected: "string", - got: req.body.hasOwnProperty("userpass") ? typeof(req.body.userpass) : undefined - } - }; - var to_send = error.formatting; - to_send.results = [result]; - res.status(400).send(to_send); + } catch (e) { + var result = { + userpass: { + expected: "string", + got: req.body.hasOwnProperty("userpass") + ? typeof req.body.userpass + : undefined + } + }; + var to_send = error.formatting; + to_send.results = [result]; + res.status(400).send(to_send); - return; + return; + } + var cookie = req.cookies._uI; + Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { + if (req.body.userpass == "") { + //userpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(_u))) + userpass = _u; } - var cookie = req.cookies._uI; - Functions.getSessionAdminUser(cookie, channel_name, function(_u, _a) { - if(req.body.userpass == "") { - //userpass = Functions.hash_pass(Functions.hash_pass(Functions.decrypt_string(_u))) - userpass = _u; - } - token_db.collection("api_token").find({token: token}, function(err, token_docs) { - var authorized = false; - var origin; - try { - origin = req.headers.referer.split("/")[2]; - } catch(e) { origin = ""; } - if(token_docs.length == 1 && token_docs[0].token == token && (token_docs[0].origin == "*" || origin.indexOf(token_docs[0].origin) > -1)) { - authorized = true; - } - checkOveruseApiToken(authorized, token_docs, res, function() { - checkTimeout(guid, res, authorized, "POST", function() { - if(token != "" && !authorized) { - //updateTimeout(guid, res, authorized, "POST", function(err, docs) { - res.status(400).send(error.wrong_token); - return; - //}); - } else { - db.collection(channel_name).aggregate([ - { - "$match": { - "type": { - "$ne": "suggested" - } - } - }, - { "$project": projects.project_object }, - { "$sort" : { "now_playing" : -1, "votes": -1, "added": 1, "title": 1 } } - ], function(err, list) { - //db.collection(channel_name).find({views: {$exists: false}}, projects.toShowChannel, function(err, list) { - if(list.length > 0) { - db.collection(channel_name + "_settings").find({ id: "config" }, function(err, conf) { - if(conf.length == 0) { - res.status(404).send(error.not_found.list); - return; - } else if(conf[0].userpass != userpass && conf[0].userpass != "" && conf[0].userpass != undefined) { - res.status(403).send(error.not_authenticated); - return; - } - if(authorized) { - incrementToken(token); - } - //updateTimeout(guid, res, authorized, "POST", function(err, docs) { - var to_return = error.no_error; - to_return.results = list; - res.status(200).send(to_return); - return; - //}); - }); - } else { - res.status(404).send(error.not_found.list); - return; - } - }); + token_db + .collection("api_token") + .find({ token: token }, function(err, token_docs) { + var authorized = false; + var origin; + try { + origin = req.headers.referer.split("/")[2]; + } catch (e) { + origin = ""; + } + if ( + token_docs.length == 1 && + token_docs[0].token == token && + (token_docs[0].origin == "*" || + origin.indexOf(token_docs[0].origin) > -1) + ) { + authorized = true; + } + checkOveruseApiToken(authorized, token_docs, res, function() { + checkTimeout(guid, res, authorized, "POST", function() { + if (token != "" && !authorized) { + //updateTimeout(guid, res, authorized, "POST", function(err, docs) { + res.status(400).send(error.wrong_token); + return; + //}); + } else { + db.collection(channel_name).aggregate( + [ + { + $match: { + type: { + $ne: "suggested" + } } - }); - }); + }, + { $project: projects.project_object }, + { $sort: { now_playing: -1, votes: -1, added: 1, title: 1 } } + ], + function(err, list) { + //db.collection(channel_name).find({views: {$exists: false}}, projects.toShowChannel, function(err, list) { + if (list.length > 0) { + db.collection(channel_name + "_settings").find( + { id: "config" }, + function(err, conf) { + if (conf.length == 0) { + res.status(404).send(error.not_found.list); + return; + } else if ( + conf[0].userpass != userpass && + conf[0].userpass != "" && + conf[0].userpass != undefined + ) { + res.status(403).send(error.not_authenticated); + return; + } + if (authorized) { + incrementToken(token); + } + //updateTimeout(guid, res, authorized, "POST", function(err, docs) { + var to_return = error.no_error; + to_return.results = list; + res.status(200).send(to_return); + return; + //}); + } + ); + } else { + res.status(404).send(error.not_found.list); + return; + } + } + ); + } + }); }); - }); + }); + }); }); function incrementToken(token) { - token_db.collection("api_token").update({token: token}, {$inc: {usage: 1}}, function(err, doc) { - - }); + token_db + .collection("api_token") + .update({ token: token }, { $inc: { usage: 1 } }, function(err, doc) {}); } -router.route('/api/color').post(function(req, res) { - try { - var origin = req.get("origin").replace("https://", "").replace("http://", ""); - var allowed = ["client.localhost", "localhost", "zoff.me", "client.zoff.me", "zoff.no", "client.zoff.no"]; - if(allowed.indexOf(origin) < 0) { - throw "Wrong origin"; - } - } catch(e) { - res.sendStatus(403); - return; +router.route("/api/color").post(function(req, res) { + try { + var origin = req + .get("origin") + .replace("https://", "") + .replace("http://", ""); + var allowed = [ + "client.localhost", + "localhost", + "zoff.me", + "client.zoff.me", + "zoff.no", + "client.zoff.no" + ]; + if (allowed.indexOf(origin) < 0) { + throw "Wrong origin"; } - if(!req.body.hasOwnProperty("id") || typeof(req.body.id) != "string") { - res.sendStatus(400); - return; - } - List.sendColor(false, undefined, req.body.id, true, res); + } catch (e) { + res.sendStatus(403); + return; + } + if (!req.body.hasOwnProperty("id") || typeof req.body.id != "string") { + res.sendStatus(400); + return; + } + List.sendColor(false, undefined, req.body.id, true, res); }); -router.route('/api/imageblob').post(function(req, res) { - var Jimp = require("jimp"); - try { - var origin = req.get("origin").replace("https://", "").replace("http://", ""); - var allowed = ["client.localhost", "localhost", "zoff.me", "client.zoff.me", "zoff.no", "client.zoff.no"]; - if(allowed.indexOf(origin) < 0) { - throw "Wrong origin"; - } - } catch(e) { - res.sendStatus(403); - return; +router.route("/api/imageblob").post(function(req, res) { + var Jimp = require("jimp"); + try { + var origin = req + .get("origin") + .replace("https://", "") + .replace("http://", ""); + var allowed = [ + "client.localhost", + "localhost", + "zoff.me", + "client.zoff.me", + "zoff.no", + "client.zoff.no" + ]; + if (allowed.indexOf(origin) < 0) { + throw "Wrong origin"; } + } catch (e) { + res.sendStatus(403); + return; + } - Jimp.read('https://img.youtube.com/vi/' + req.body.id + '/mqdefault.jpg', function (err, image) { - if (err) { - console.log(err); - res.sendStatus(404); - return; - } - image.blur(50) - .write(path.join(pathThumbnails, '/public/assets/images/thumbnails/' + req.body.id + '.jpg'), function(e, r) { + Jimp.read( + "https://img.youtube.com/vi/" + req.body.id + "/mqdefault.jpg", + function(err, image) { + if (err) { + console.log(err); + res.sendStatus(404); + return; + } + image + .blur(50) + .write( + path.join( + pathThumbnails, + "/public/assets/images/thumbnails/" + req.body.id + ".jpg" + ), + function(e, r) { res.status(200).send(req.body.id + ".jpg"); return; - }); - }); + } + ); + } + ); }); try { - var nodemailer = require('nodemailer'); - var mailconfig = require(path.join(__dirname, '../../config/mailconfig.js')); - var recaptcha_config = require(path.join(__dirname, '../../config/recaptcha.js')); - var Recaptcha = require('express-recaptcha'); - var RECAPTCHA_SITE_KEY = recaptcha_config.site; - var RECAPTCHA_SECRET_KEY = recaptcha_config.key; - var recaptcha = new Recaptcha(RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY); + var nodemailer = require("nodemailer"); + var mailconfig = require(path.join(__dirname, "../../config/mailconfig.js")); + var recaptcha_config = require(path.join( + __dirname, + "../../config/recaptcha.js" + )); + var Recaptcha = require("express-recaptcha"); + var RECAPTCHA_SITE_KEY = recaptcha_config.site; + var RECAPTCHA_SECRET_KEY = recaptcha_config.key; + var recaptcha = new Recaptcha(RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY); - router.route('/api/apply').post(recaptcha.middleware.verify, function(req, res) { - if(req.body.email == "" || req.body.email == undefined) { - res.send("failed"); - return; - } - if(req.recaptcha.error == null) { - var origin = "*"; - if(req.body.origin != undefined && req.body.origin != "") origin = req.body.origin; - var name = req.body.email; - var id = crypto.createHash('sha256').update(uniqid()).digest('base64'); - var uniqid_link = crypto.createHash('sha256').update(uniqid()).digest('hex'); - token_db.collection("api_token").find({name: name}, function(err, results_find) { - var token = ""; - if(results_find.length > 0) { - token = results_find[0].token; - } - token_db.collection("api_links").find({token: token}, function(e, d) { - if(results_find.length == 0 || (d.length == 0 && results_find.length > 0 && !results_find[0].active)) { - token_db.collection("api_token").insert({name: name, origin: origin, token: id, usage: 0, active: false, limit: 20}, function(err, docs){ - createApiLink(req, res, uniqid_link, id, name); - }); - } else { - createApiLink(req, res, uniqid_link, token, name); + router + .route("/api/apply") + .post(recaptcha.middleware.verify, function(req, res) { + if (req.body.email == "" || req.body.email == undefined) { + res.send("failed"); + return; + } + if (req.recaptcha.error == null) { + var origin = "*"; + if (req.body.origin != undefined && req.body.origin != "") + origin = req.body.origin; + var name = req.body.email; + var id = crypto + .createHash("sha256") + .update(uniqid()) + .digest("base64"); + var uniqid_link = crypto + .createHash("sha256") + .update(uniqid()) + .digest("hex"); + token_db + .collection("api_token") + .find({ name: name }, function(err, results_find) { + var token = ""; + if (results_find.length > 0) { + token = results_find[0].token; + } + token_db + .collection("api_links") + .find({ token: token }, function(e, d) { + if ( + results_find.length == 0 || + (d.length == 0 && + results_find.length > 0 && + !results_find[0].active) + ) { + token_db.collection("api_token").insert( + { + name: name, + origin: origin, + token: id, + usage: 0, + active: false, + limit: 20 + }, + function(err, docs) { + createApiLink(req, res, uniqid_link, id, name); } - }); - }) - } else { - res.send("failed"); - return; - } + ); + } else { + createApiLink(req, res, uniqid_link, token, name); + } + }); + }); + } else { + res.send("failed"); + return; + } }); - function createApiLink(req, res, uniqid_link, id, name) { - token_db.collection("api_links").insert({id: uniqid_link, token: id, createdAt: new Date()}, function(err, docs) { - let transporter = nodemailer.createTransport(mailconfig); - transporter.verify(function(error, success) { - if (error) { - token_db.collection("api_links").remove({id: uniqid_link}, function(e,d) { - res.send("failed"); - return; - }) - } else { - var subject = 'ZOFF: API-key'; - var message = "Hello,

Thanks for signing up for the API, here is your key: https://zoff.me/api/apply/" + uniqid_link + "

This link will expire in 1 day, so please write it down.

zoff-logo"; - var msg = { - from: mailconfig.from, - to: name, - subject: subject, - text: message, - html: message, - } - transporter.sendMail(msg, (error, info) => { - if (error) { - res.send("failed"); - transporter.close(); - return; - } - res.status(200).send("success"); - transporter.close(); - return; - }); - } + function createApiLink(req, res, uniqid_link, id, name) { + token_db + .collection("api_links") + .insert({ id: uniqid_link, token: id, createdAt: new Date() }, function( + err, + docs + ) { + let transporter = nodemailer.createTransport(mailconfig); + transporter.verify(function(error, success) { + if (error) { + token_db + .collection("api_links") + .remove({ id: uniqid_link }, function(e, d) { + res.send("failed"); + return; + }); + } else { + var subject = "ZOFF: API-key"; + var message = + "Hello,

Thanks for signing up for the API, here is your key: https://zoff.me/api/apply/" + + uniqid_link + + "

This link will expire in 1 day, so please write it down.

zoff-logo"; + var msg = { + from: mailconfig.from, + to: name, + subject: subject, + text: message, + html: message + }; + transporter.sendMail(msg, (error, info) => { + if (error) { + res.send("failed"); + transporter.close(); + return; + } + res.status(200).send("success"); + transporter.close(); + return; }); - }) - } + } + }); + }); + } - router.route('/api/mail').post(recaptcha.middleware.verify, function(req, res) { - if(req.recaptcha.error == null) { - let transporter = nodemailer.createTransport(mailconfig); + router + .route("/api/mail") + .post(recaptcha.middleware.verify, function(req, res) { + if (req.recaptcha.error == null) { + let transporter = nodemailer.createTransport(mailconfig); - transporter.verify(function(error, success) { - if (error) { - res.sendStatus(500); - return; - } else { - var subject = 'ZOFF: Contact form webpage'; - if(req.body.error_report) { - subject = 'ZOFF: Error report'; - } - var from = req.body.from; - var message = req.body.message; - var msg = { - from: mailconfig.from, - to: mailconfig.to, - subject: subject, - text: message, - html: message, - replyTo: from - } - transporter.sendMail(msg, (error, info) => { - if (error) { - res.status(500).send("failed"); - transporter.close(); - return; - } - res.status(200).send("success"); - transporter.close(); - }); - } - }); - } else { - res.status(500).send("failed"); + transporter.verify(function(error, success) { + if (error) { + res.sendStatus(500); return; - } - }); -} 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."); - router.route('/api/mail').post(function(req, res) { - console.log("Someone tried to send a mail, but the mailsystem hasn't been enabled..") + } else { + var subject = "ZOFF: Contact form webpage"; + if (req.body.error_report) { + subject = "ZOFF: Error report"; + } + var from = req.body.from; + var message = req.body.message; + var msg = { + from: mailconfig.from, + to: mailconfig.to, + subject: subject, + text: message, + html: message, + replyTo: from + }; + transporter.sendMail(msg, (error, info) => { + if (error) { + res.status(500).send("failed"); + transporter.close(); + return; + } + res.status(200).send("success"); + transporter.close(); + }); + } + }); + } else { res.status(500).send("failed"); return; + } }); +} 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." + ); + router.route("/api/mail").post(function(req, res) { + console.log( + "Someone tried to send a mail, but the mailsystem hasn't been enabled.." + ); + res.status(500).send("failed"); + return; + }); } function updateTimeout(guid, res, authorized, type, callback) { - if(authorized) { - callback(null, null); - return; + if (authorized) { + callback(null, null); + return; + } + db.collection("timeout_api").update( + { type: type, guid: guid }, + { + $set: { + createdAt: new Date(), + type: type, + guid: guid + } + }, + { upsert: true }, + function(err, docs) { + callback(err, docs); } - db.collection("timeout_api").update({type: type, guid: guid}, { - $set: { - "createdAt": new Date(), - type: type, - guid: guid, - }, - }, {upsert: true}, function(err, docs) { - callback(err, docs); - }); + ); } function checkTimeout(guid, res, authorized, type, callback) { - if(authorized) { - callback(); - return; - } - db.collection("timeout_api").find({ - type: type, - guid: guid, - }, function(err, docs) { - if(docs.length > 0) { - var date = new Date(docs[0].createdAt); - date.setSeconds(date.getSeconds() + 1); - var now = new Date(); - var retry_in = (date.getTime() - now.getTime()) / 1000; - if(retry_in > 0) { - res.header({'Retry-After': retry_in}); - var thisErrorString = JSON.stringify(error.tooMany); - var thisError = JSON.parse(thisErrorString); - thisError.error += " To get an API-key, visit https://zoff.me/api/apply."; - res.status(429).send(thisError); - return; - } + if (authorized) { + callback(); + return; + } + db.collection("timeout_api").find( + { + type: type, + guid: guid + }, + function(err, docs) { + if (docs.length > 0) { + var date = new Date(docs[0].createdAt); + date.setSeconds(date.getSeconds() + 1); + var now = new Date(); + var retry_in = (date.getTime() - now.getTime()) / 1000; + if (retry_in > 0) { + res.header({ "Retry-After": retry_in }); + var thisErrorString = JSON.stringify(error.tooMany); + var thisError = JSON.parse(thisErrorString); + thisError.error += + " To get an API-key, visit https://zoff.me/api/apply."; + res.status(429).send(thisError); + return; } - var now_date = new Date(); - db.collection("timeout_api").update({type: type, guid: guid}, { - $set: { - "createdAt": now_date, - type: type, - guid: guid, - }, - }, {upsert: true}, function(err, docs) { - callback(); - return; - }); - }); + } + var now_date = new Date(); + db.collection("timeout_api").update( + { type: type, guid: guid }, + { + $set: { + createdAt: now_date, + type: type, + guid: guid + } + }, + { upsert: true }, + function(err, docs) { + callback(); + return; + } + ); + } + ); } function cleanChannelName(channel_name) { - var coll = Functions.removeEmojis(channel_name).toLowerCase(); - //coll = coll.replace("_", ""); - //coll = encodeURIComponent(coll).replace(/\W/g, ''); - coll = Functions.encodeChannelName(channel_name); - coll = filter.clean(coll); - return coll; + var coll = Functions.removeEmojis(channel_name).toLowerCase(); + //coll = coll.replace("_", ""); + //coll = encodeURIComponent(coll).replace(/\W/g, ''); + coll = Functions.encodeChannelName(channel_name); + coll = filter.clean(coll); + return coll; } function validateLogin(adminpass, userpass, channel_name, type, res, callback) { - db.collection(channel_name + "_settings").find({ id: "config" }, function(err, conf) { - var exists = false; - if(conf.length > 0 && ((conf[0].userpass == undefined || conf[0].userpass == "" || conf[0].userpass == userpass))) { - exists = true; - } else if(conf.length > 0 && type == "config") { - res.status(404).send(error.not_found.list); - return; - } else if(conf.length == 0) { - res.status(404).send(error.not_found.list); - return; - } + db.collection(channel_name + "_settings").find({ id: "config" }, function( + err, + conf + ) { + var exists = false; + if ( + conf.length > 0 && + (conf[0].userpass == undefined || + conf[0].userpass == "" || + conf[0].userpass == userpass) + ) { + exists = true; + } else if (conf.length > 0 && type == "config") { + res.status(404).send(error.not_found.list); + return; + } else if (conf.length == 0) { + res.status(404).send(error.not_found.list); + return; + } - if( - (type == "fetch_song") || - (type == "add" && ((conf[0].addsongs && (conf[0].adminpass == "" || conf[0].adminpass == undefined || conf[0].adminpass == adminpass)) || !conf[0].addsongs)) || - (type == "delete" && (conf[0].adminpass == "" || conf[0].adminpass == undefined || conf[0].adminpass == adminpass)) || - (type == "vote" && ((conf[0].vote && (conf[0].adminpass == "" || conf[0].adminpass == undefined || conf[0].adminpass == adminpass)) || !conf[0].vote)) || - (type == "config" && (conf[0].adminpass == "" || conf[0].adminpass == undefined || conf[0].adminpass == adminpass)) - ) { - callback(exists, conf, true); - } else if(type == "add") { - callback(exists, conf, false); - } else { - res.status(403).send(error.not_authenticated); - return; - } - }); + if ( + type == "fetch_song" || + (type == "add" && + ((conf[0].addsongs && + (conf[0].adminpass == "" || + conf[0].adminpass == undefined || + conf[0].adminpass == adminpass)) || + !conf[0].addsongs)) || + (type == "delete" && + (conf[0].adminpass == "" || + conf[0].adminpass == undefined || + conf[0].adminpass == adminpass)) || + (type == "vote" && + ((conf[0].vote && + (conf[0].adminpass == "" || + conf[0].adminpass == undefined || + conf[0].adminpass == adminpass)) || + !conf[0].vote)) || + (type == "config" && + (conf[0].adminpass == "" || + conf[0].adminpass == undefined || + conf[0].adminpass == adminpass)) + ) { + callback(exists, conf, true); + } else if (type == "add") { + callback(exists, conf, false); + } else { + res.status(403).send(error.not_authenticated); + return; + } + }); } -function postEnd(channel_name, configs, new_song, guid, res, authenticated, authorized) { - if(configs != undefined) { - io.to(channel_name).emit("conf", configs); +function postEnd( + channel_name, + configs, + new_song, + guid, + res, + authenticated, + authorized +) { + if (configs != undefined) { + io.to(channel_name).emit("conf", configs); + } + List.getNextSong(channel_name, undefined, function() { + //updateTimeout(guid, res, authorized, "POST", function(err, docs) { + var to_return = error.no_error; + if (!authenticated) { + to_return = error.not_authenticated; + to_return.success = true; } - List.getNextSong(channel_name, undefined, function() { - //updateTimeout(guid, res, authorized, "POST", function(err, docs) { - var to_return = error.no_error; - if(!authenticated) { - to_return = error.not_authenticated; - to_return.success = true; - } - to_return.results = [new_song]; - res.status(authenticated ? 200 : 403).send(to_return); - return; - //}); - }); + to_return.results = [new_song]; + res.status(authenticated ? 200 : 403).send(to_return); + return; + //}); + }); } module.exports = _exports;