diff --git a/README.md b/README.md index c32de38..1a7ab8d 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ $ node index.js --vd [Video directory] This project is under license from MIT. For more details, see the [LICENSE](LICENSE.md) file. -Made with :heart: by Me +Made with :heart: by Me   diff --git a/backend/userManagment/addNewUser.ts b/backend/userManagment/addNewUser.ts index 442726a..8c7299e 100644 --- a/backend/userManagment/addNewUser.ts +++ b/backend/userManagment/addNewUser.ts @@ -1,6 +1,6 @@ import { uuidv4 } from '../util'; import { db } from '../../index'; -import { BackendRequest } from "../../interfaces"; +import { BackendRequest } from '../../interfaces'; const PermissionLevel = ['User', 'Admin']; diff --git a/backend/util.ts b/backend/util.ts index 5402895..4bdebdf 100644 --- a/backend/util.ts +++ b/backend/util.ts @@ -4,7 +4,6 @@ import * as fs from 'fs'; import { SettingsDataInterface } from '../interfaces'; import * as loginBackend from './UserMangement'; import { db } from '../index'; -import { RunResult } from 'better-sqlite3'; import { UserData, BackendRequest} from '../interfaces'; function isEmptyObject(obj:object) : boolean { @@ -53,12 +52,11 @@ function saveUserData (token:string, ip:string, data:SettingsDataInterface) : Ba return {isOk: false, statusCode: 400, message: 'Malformatted data' }; const exists = db.prepare('SELECT * FROM settings WHERE UUID=?').get(user.value.uuid); - let answer:RunResult; if (exists) - answer = db.prepare('UPDATE settings SET volume = ? WHERE UUID = ?').run(data['volume'], user.value.uuid); + db.prepare('UPDATE settings SET volume = ? WHERE UUID = ?').run(data.volume, user.value.uuid); else - answer = db.prepare('INSERT INTO settings VALUES(?,?)').run(user.value.uuid, data['volume']); - return { isOk: true, value: undefined } + db.prepare('INSERT INTO settings VALUES(?,?)').run(user.value.uuid, data.volume); + return { isOk: true, value: undefined }; } function readdir(path:string) : string[] { diff --git a/backend/videoServing/getFiles.ts b/backend/videoServing/getFiles.ts index 39e5fd3..c16ff2f 100644 --- a/backend/videoServing/getFiles.ts +++ b/backend/videoServing/getFiles.ts @@ -79,8 +79,8 @@ function getFilesFromWatchList(token:string, ip:string) : BackendRequest { const pathCeck = checkPath(path); diff --git a/html/js/admin.ts b/html/js/admin.ts index 109b6a0..171f763 100644 --- a/html/js/admin.ts +++ b/html/js/admin.ts @@ -90,8 +90,8 @@ fetchBackend(url.toString(), { method: 'POST' }, (val) => { if (val !== undefined) { - alert(val) - checkavtive.checked = !checkavtive.checked + alert(val); + checkavtive.checked = !checkavtive.checked; } }, false, true); }); diff --git a/html/js/generalFunctions.ts b/html/js/generalFunctions.ts index b76104f..a9898c8 100644 --- a/html/js/generalFunctions.ts +++ b/html/js/generalFunctions.ts @@ -19,23 +19,23 @@ function setCookie(name: string, cookie: string, expires: Date, path = '/') : vo function fetchBackend(url: string, options: RequestInit, callback?: ((data: any) => void)|undefined, sendBack = false, canFail = false) : void { fetch(url, options).then(async data => { - if (!data.ok) { - console.log('[Request Error] ' + data.bodyUsed ? await data.text() : '') - if (sendBack) - document.location.href = '/'; - else if (!canFail) - document.getElementById('offline').classList.remove('false'); - } else { - document.getElementById('offline').classList.add('false'); - const text = await data.text() - if (callback) - try { - callback(JSON.parse(text)) - } catch { - callback(text) - } - } - }) + if (!data.ok) { + console.log('[Request Error] ' + data.bodyUsed ? await data.text() : ''); + if (sendBack) + document.location.href = '/'; + else if (!canFail) + document.getElementById('offline').classList.remove('false'); + } else { + document.getElementById('offline').classList.add('false'); + const text = await data.text(); + if (callback) + try { + callback(JSON.parse(text)); + } catch { + callback(text); + } + } + }) .catch(error => { document.getElementById('offline').classList.remove('false'); console.log(error); diff --git a/html/js/login.ts b/html/js/login.ts index 49d2d57..89c2f7c 100644 --- a/html/js/login.ts +++ b/html/js/login.ts @@ -66,10 +66,10 @@ async function login() { setTimeout(() => { wrongPassText.className = 'unvis'; }, 600); } }) - .catch(error => { - document.getElementById('offline').classList.remove('false'); - console.log(error); - }); + .catch(error => { + document.getElementById('offline').classList.remove('false'); + console.log(error); + }); return; } else { wrongPassText.className = 'vis'; diff --git a/html/js/player.ts b/html/js/player.ts index 3a7658b..89d2818 100644 --- a/html/js/player.ts +++ b/html/js/player.ts @@ -17,23 +17,23 @@ const skipButton = document.getElementById('SkipButton'); const next = document.getElementById('next'); const controls = document.getElementById('controls'); const info = document.getElementById('info'); +const blueJuice = document.getElementById('blue-juice'); let mouseDown = false; let skiped = false; let timer: NodeJS.Timeout; const WaitToHideTime = 1000; -let infoProgress: HTMLParagraphElement; const socket = io({ auth: { token: loadCookie('token') } }); -socket.on("error", (err:string, critical:boolean) => { - console.log(`[SocketIO] Recived error: ${err}`) +socket.on('error', (err:string, critical:boolean) => { + console.log(`[SocketIO] Recived error: ${err}`); if (critical) - socket.disconnect() -}) + socket.disconnect(); +}); document.body.onmousedown = function() { mouseDown = true; @@ -55,40 +55,22 @@ fetchBackend('/api/checkToken/', { const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); +type LiveTranscodingData = { + duration: number, +} | undefined +let liveTranscodingData: LiveTranscodingData = undefined; -if (!video.canPlayType(getVideoType(urlParams.get('path').split('.').pop()))) { - socket.on(urlParams.get('path') + '.mp4', (data) => { - switch (data.type) { - case 'error': - console.error(data.data); - showError(); - break; - case 'progress': - if (!infoProgress) { - infoProgress = document.createElement('p'); - info.appendChild(infoProgress); - } - infoProgress.innerHTML = Math.ceil(data.data * 100) / 100 + '%'; - break; - case 'finish': - if (!video.src) - video.src = '/video/' + urlParams.get('path') + '.mp4'; - } - }); - socket.emit('transcodeStatus', encodeURIComponent(urlParams.get('path')) + '.mp4', (res) => { - console.log(res.type); - switch (res.type) { - case 'error': - showError(); - break; - case 'ready': - video.src = '/video/' + urlParams.get('path') + '.mp4'; - break; - case 'notFound': - socket.emit('startTranscoding', urlParams.get('path') + '.mp4'); - break; +if (!video.canPlayType(getVideoType(urlParams.get('path').split('.').pop()))) { + socket.emit('videoMetaData', urlParams.get('path'), (res) => { + if (res.type === 'error') { + console.log(`[Error] ${typeof res.msg === 'object' ? JSON.stringify(res.msg) : res.msg}`); + return showError(typeof res.msg === 'object' ? JSON.stringify(res.msg) : res.msg); } + liveTranscodingData = { + duration: res.format.duration + }; + video.src = '/video/' + urlParams.get('path') + '.mp4'; }); } else { video.src = '/video/' + urlParams.get('path'); @@ -130,11 +112,11 @@ function loadData(res: SkipData) { if (res.next) { next.style.opacity = '1'; next.addEventListener('click', function() { - const nextURL = new URL(document.location.href) + const nextURL = new URL(document.location.href); nextURL.search = new URLSearchParams({ path: res.next - }).toString() - document.location.href = nextURL.toString() + }).toString(); + document.location.href = nextURL.toString(); }); } else next.disabled = true; @@ -196,7 +178,7 @@ barContainer.addEventListener('click', getClickPosition, false); TimeTooltipBar.addEventListener('mousemove', function(e) { const width = (e.clientX - (this.offsetLeft + (this.offsetParent).offsetLeft)) / this.offsetWidth; - const time = width * video.duration; + const time = width * (liveTranscodingData ? liveTranscodingData.duration : video.duration); const mincur = Math.floor(time / 60); let seccur: number|string = Math.floor(time % 60); if (seccur < 10) @@ -210,6 +192,9 @@ TimeTooltipBar.addEventListener('mousemove', function(e) { tooltip.style.left = (TimeTooltipBar.offsetWidth - 70) + 'px'; if (mouseDown) { + if (time > video.duration && liveTranscodingData) { + return alert('You may only seek backward or on the blue line'); + } video.currentTime = time; if (seccur < 10) seccur = '0' + seccur; @@ -221,7 +206,7 @@ TimeTooltipBar.addEventListener('mousemove', function(e) { function getClickPosition(e) { if (e.target === barContainer || e.target === bar || e.target === document.getElementById('TimeBar')) { const width = (e.clientX - (this.offsetLeft + this.offsetParent.offsetLeft)) / this.offsetWidth; - const time = width * video.duration; + const time = width * (liveTranscodingData ? liveTranscodingData.duration : video.duration); video.currentTime = time; const mincur = Math.floor(time / 60); let seccur:number|string = Math.floor(time % 60); @@ -252,11 +237,17 @@ buttonPlay.onclick = function() { let last = 0; video.addEventListener('timeupdate', function() { - const barPos = video.currentTime / video.duration; + const barPos = video.currentTime / ( liveTranscodingData ? liveTranscodingData.duration : video.duration); bar.style.width = barPos * 100 + '%'; + if (liveTranscodingData) { + const bluePos = video.duration / liveTranscodingData.duration; + blueJuice.style.width = bluePos * 100 + '%'; + blueJuice.style.display = 'inherit'; + } + const currTime = Math.round(video.currentTime); - const dur = Math.round(video.duration); + const dur = Math.round((liveTranscodingData ? liveTranscodingData.duration : video.duration)); const min = Math.floor(dur / 60); let sec:number|string = Math.floor(dur % 60); @@ -272,7 +263,7 @@ video.addEventListener('timeupdate', function() { time.innerHTML = mincur + ':' + seccur + ' / ' + min + ':' + sec; if (video.ended) buttonPlay.className = 'play'; - const timePer = Math.floor(video.currentTime / video.duration * 100) / 100; + const timePer = Math.floor(video.currentTime / (liveTranscodingData ? liveTranscodingData.duration : video.duration) * 100) / 100; if (timePer !== last) { last = timePer; fetchBackend('/api/setTime/', { @@ -331,7 +322,7 @@ document.addEventListener('fullscreenchange', function() { video.addEventListener('loadeddata', function () { info.style.display = 'none'; - if (!skiped) { + if (!skiped && !liveTranscodingData) { const url = new URL(window.location.origin + '/api/getTime/'); url.search = new URLSearchParams({ 'token': loadCookie('token'), diff --git a/html/js/videoSelector.ts b/html/js/videoSelector.ts index ceff3cb..b7728b4 100644 --- a/html/js/videoSelector.ts +++ b/html/js/videoSelector.ts @@ -92,15 +92,15 @@ class FileData { 'content-type': 'application/json; charset=UTF-8' }, method: 'GET' - }) + }); if (!response.ok) { document.getElementById('offline').classList.remove('false'); - console.log(`[Request Failed] ${response.body ? await response.text() : ''}`) + console.log(`[Request Failed] ${response.body ? await response.text() : ''}`); return; } - const parsedData : GetFilesResponse = await response.json() + const parsedData : GetFilesResponse = await response.json(); this.data = parsedData.files; this.pathSep = parsedData.pathSep; @@ -153,7 +153,7 @@ class FileData { }), method: (add.classList.contains('already') ? 'DELETE' : 'PUT') }, (data) => { - console.log(data) + console.log(data); if (data === 'added') { add.classList.remove('add'); add.classList.add('already'); diff --git a/html/player/index.html b/html/player/index.html index 3499e7e..44f5216 100644 --- a/html/player/index.html +++ b/html/player/index.html @@ -25,7 +25,10 @@
-
+
+
+
+
Tooltip text
diff --git a/html/style/player.css b/html/style/player.css index cdce168..7944ed1 100644 --- a/html/style/player.css +++ b/html/style/player.css @@ -62,6 +62,8 @@ body { .buttons { padding-left: 10px; padding-right: 10px; + position: relative; + top: 7px; } @@ -84,7 +86,18 @@ body { background-color: black; } +#blue-juice { + display: none; + background-color: blue; +} + +#orange-juice { + z-index: 1; +} + .orange-juice { + position: absolute; + top: 0; height: 7px; width: 0%; background-color: orangered; @@ -97,8 +110,6 @@ body { cursor: pointer; } - - .buttons #volume:before { content: '\f028'; font-family: 'Font Awesome 5 Free'; diff --git a/index.ts b/index.ts index 273dbdf..56f1ea7 100644 --- a/index.ts +++ b/index.ts @@ -17,34 +17,6 @@ import express from 'express'; import * as fs from 'fs'; import path from 'path'; - -function clearCacheRecur(p: string) { - if (!fs.existsSync(p)) - return; - const stats = fs.lstatSync(p); - if (stats.isDirectory()) { - const files = fs.readdirSync(p); - if (files.length === 0 && p !== path.join(__dirname, 'temp')) - fs.rmdirSync(p); - files.forEach(f => clearCacheRecur(path.join(p,f))); - } else { - if (stats.mtime.getTime() + 30 * 60 * 1000 < new Date().getTime()) { - fs.unlinkSync(p); - } - } -} - -function clearCache() { - if (!fs.existsSync('temp')) - fs.mkdirSync('temp'); - clearCacheRecur(path.join(__dirname, 'temp')); - setTimeout(() => { - clearCache(); - }, 1000 * 60 * 30); -} - -clearCache(); - const app = express(); if (!fs.existsSync(argv['Video Directory'])) { diff --git a/package.json b/package.json index e486745..f1f6939 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "videoplayer", - "version": "3.2.2", + "version": "3.3.0", "description": "A Video Player", "main": "index.js", "databaseVersion": 2, diff --git a/routes/ExpressUses.ts b/routes/ExpressUses.ts index 970f393..635992d 100644 --- a/routes/ExpressUses.ts +++ b/routes/ExpressUses.ts @@ -4,12 +4,9 @@ import * as path from 'path'; import { json } from 'body-parser'; import cookieParser from 'cookie-parser'; import { getUser, limiter } from './Routes'; -import fs from 'fs'; import ffmpeg from 'fluent-ffmpeg'; import { checkPath } from '../backend/util'; -import { getUserFromToken } from "../backend/UserMangement"; - -const currentTranscoding = []; +import { getUserFromToken } from '../backend/UserMangement'; export function init() : void { app.use(express.json()); @@ -46,22 +43,31 @@ export function init() : void { return res.status(404).end(); if (urlPath.pop() === 'mp4' && VideoNameExtensions.includes(urlPath.pop())) { - if (fs.existsSync(decodePath(pathCheck.value))) - return next(); - - if (fs.existsSync('temp' + path.sep + decodePath(pathCheck.value.substring(argv['Video Directory'].length)))) { - res.locals.tempVideo = 'temp' + path.sep + decodePath(pathCheck.value.substring(argv['Video Directory'].length)); - return next(); - } - + ffmpeg(decodePath(pathCheck.value).slice(0, -4)) + .ffprobe((er, data) => { + if (er) + return res.status(500).end('ffmpeg error'); + const command = ffmpeg(decodePath(pathCheck.value).slice(0, -4)) + .videoBitrate(data.format.bit_rate / 3) + .size('50%') + .videoCodec('libx264') + .format('mp4') + .outputOption('-movflags frag_keyframe+empty_moov') + .on('error', (er, stdout, stderr) => { + console.log(er, stdout, stderr); + return res.status(500).end('ffmpeg error'); + }) + .on('progress', (progress) => console.log(`[FFmpeg] ${progress.percent}`)); + command + .pipe(res) + .on('error', (er) => { + if (er.message !== 'Output stream closed') + console.log(er); + return res.status(500).end(er.message); + }); + }); } else next(); - }, (_, res, next) => { - if (!res.locals.tempVideo) - return next(); - return res.sendFile(res.locals.tempVideo, { - root: argv['Working Directory'] - }); }, express.static(argv['Video Directory'], { dotfiles: 'allow' })); @@ -72,95 +78,38 @@ export function init() : void { function initSocket() { socketIO.on('connection', (socket) => { if (socket.handshake.auth.token) { - const user = getUserFromToken(socket.handshake.auth.token, socket.handshake.address) + const user = getUserFromToken(socket.handshake.auth.token, socket.handshake.address); if (user.isOk === false) { delete user.isOk; - return socketIO.to(socket.id).emit('error', user, true) + return socketIO.to(socket.id).emit('error', user, true); } } else { - socketIO.to(socket.id).emit('error', 'No token provided', true) + socketIO.to(socket.id).emit('error', 'No token provided', true); return; } - socket.on('transcodeStatus', (pathToCheck, callback) => { - const pathCheck = checkPath(pathToCheck); + socket.on('videoMetaData', (filepath, callback) => { + const pathCheck = checkPath(filepath); if (pathCheck.isOk === false) return callback({ - type: 'error' + type: 'error', + msg: pathCheck.message }); - let p = decodePath(pathCheck.value.substring(argv['Video Directory'].length)); + let p = decodePath(pathCheck.value); while (p.startsWith(path.sep)) p = p.slice(1); - if (fs.existsSync('temp' + path.sep + p)) - return callback({ - type: 'ready' - }); - - if (currentTranscoding.includes(pathToCheck)) - return callback({ - type: 'transcoding' - }); - - return callback({ - type: 'notFound' - }); - }); - - socket.on('startTranscoding', (pathToCheck) => { - const pathCheck = checkPath(decodePath(pathToCheck)); - if (pathCheck.isOk === false) - return; - if (currentTranscoding.includes(decodeURIComponent(pathCheck.value))) - return; - - const streamPath = pathCheck.value.split('.').reverse().slice(1).reverse().join('.'); - - pathCheck.value.substring(argv['Video Directory'].length).split(path.sep).forEach((_: string, i: number, a: Array) => { - if (i === 0) - return; - const testPath = ['temp'].concat(a.slice(0, i)).join(path.sep); - if (!fs.existsSync(testPath)) - fs.mkdirSync(testPath); - }); - - ffmpeg() - .input(streamPath) - .outputOptions([ '-preset veryfast', '-vcodec libx264', '-b:v 500k', '-vf scale=1280:720', '-threads 0', '-y']) - .output('temp' + path.sep + decodePath(pathCheck.value.substring(argv['Video Directory'].length))) - .on('end', () => { - const index = currentTranscoding.indexOf((pathCheck.value)); - if (index > -1) { - currentTranscoding.splice(index, 1); - } - socketIO.emit(pathToCheck, { - type: 'finish' - }); - }) - .on('error', (err) => { - const index = currentTranscoding.indexOf(decodeURIComponent(pathCheck.value)); - if (index > -1) { - currentTranscoding.splice(index, 1); - } - socketIO.emit(pathToCheck, { + ffmpeg(p).ffprobe((er, data) => { + if (er) { + console.log(er); + return callback({ type: 'error', - data: err.message - }); - }) - .on('start', () => { - currentTranscoding.push(decodeURIComponent(pathCheck.value)); - socketIO.emit(pathToCheck, { - type: 'start' + msg: er }); - }) - .on('progress', (pro) => { - socketIO.emit(pathToCheck, { - type: 'progress', - data: pro.percent - }); - }) - .run(); + } + return callback(data); + }); }); }); } diff --git a/routes/Routes.ts b/routes/Routes.ts index 1408e91..7e6409c 100644 --- a/routes/Routes.ts +++ b/routes/Routes.ts @@ -12,13 +12,13 @@ export function getUser(force = false) : Handler { return next(); const token = req.body.token || req.cookies['token'] || req.headers['token'] || req.query['token']; if (!token) - return res.status(400).end('The request payload is invalid:\nName: token => Missing') + return res.status(400).end('The request payload is invalid:\nName: token => Missing'); const user = loginBackend.checkToken(token, req.header('x-forwarded-for') || req.socket.remoteAddress); if (user.isOk === true) { res.locals.user = user.value; next(); } else { - res.status(user.statusCode).end(user.message) + res.status(user.statusCode).end(user.message); } }; } @@ -33,26 +33,26 @@ export function requireArguments (toCheck:Array) : Handler { return function (req:Request, res:Response, next:NextFunction) { const arg = (req.method === 'GET' || req.method === 'HEAD') ? req.query : req.body; if (!arg && toCheck.length > 0) - return res.status(400).end('The request payload is invalid:\n' + toCheck.map(a => `Name: ${a.name} => Missing`).join('\n')) - const missing: number[] = [] - const invalid: number[] = [] + return res.status(400).end('The request payload is invalid:\n' + toCheck.map(a => `Name: ${a.name} => Missing`).join('\n')); + const missing: number[] = []; + const invalid: number[] = []; for(let i = 0; i < toCheck.length; i++) { if (arg[toCheck[i].name] === undefined) { if (toCheck[i].optional) continue; - missing.push(i) + missing.push(i); continue; } if (!toCheck[i].test) - toCheck[i].test = (val) => typeof val === "string" + toCheck[i].test = (val) => typeof val === 'string'; if (!toCheck[i].test(arg[toCheck[i].name])) - invalid.push(i) + invalid.push(i); } if (missing.length > 0 || invalid.length > 0) { - const answer = missing.map(a => `Name: ${toCheck[a].name} => Missing`).concat(invalid.map(a => `Name: ${toCheck[a].name} => Invalid`)) - return res.status(400).end('The request payload is invalid:\n' + answer.join('\n')) + const answer = missing.map(a => `Name: ${toCheck[a].name} => Missing`).concat(invalid.map(a => `Name: ${toCheck[a].name} => Invalid`)); + return res.status(400).end('The request payload is invalid:\n' + answer.join('\n')); } else - next() + next(); }; } diff --git a/routes/backend/FileData.ts b/routes/backend/FileData.ts index 0273309..fffc6ff 100644 --- a/routes/backend/FileData.ts +++ b/routes/backend/FileData.ts @@ -16,9 +16,9 @@ router.route('/' + routeName + '/') function getRouteHandler(req:express.Request, res:express.Response) { const answer = fileStuff.getFileData(req.query.path as string); if (answer.isOk === true) { - res.status(200).json(answer.value).end() + res.status(200).json(answer.value).end(); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/addUser.ts b/routes/backend/addUser.ts index 22e9d53..b1adf0e 100644 --- a/routes/backend/addUser.ts +++ b/routes/backend/addUser.ts @@ -21,12 +21,12 @@ function postRouteHandler(req:Request, res:Response) { if (res.locals.user['perm'] === 'Admin') { const response = loginBackend.addNewUser(req.body.username, req.body.password, req.body.perm); if (response.isOk === true) - res.status(200).end() + res.status(200).end(); else - res.status(response.statusCode).end(response.message) + res.status(response.statusCode).end(response.message); } else { - console.log(`[ERROR] User was not correctly parsed on ${routeName} request!`) - res.status(500).end() + console.log(`[ERROR] User was not correctly parsed on ${routeName} request!`); + res.status(500).end(); } } diff --git a/routes/backend/addWatchList.ts b/routes/backend/addWatchList.ts index 1465071..963d575 100644 --- a/routes/backend/addWatchList.ts +++ b/routes/backend/addWatchList.ts @@ -18,9 +18,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:Request, res:Response) { const response = fileStuff.addToWatchList(req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress, req.body.path); if (response.isOk === true) { - res.status(200).end(response.value) + res.status(200).end(response.value); } else { - res.status(response.statusCode).end(response.message) + res.status(response.statusCode).end(response.message); } } diff --git a/routes/backend/changeActive.ts b/routes/backend/changeActive.ts index c537ead..66b2bc0 100644 --- a/routes/backend/changeActive.ts +++ b/routes/backend/changeActive.ts @@ -10,23 +10,23 @@ const routeName = filename.slice(0, filename.length - 1).join('.'); router.route('/' + routeName + '/') .post(requireArguments([ { name: 'token'}, - { name: 'state', test: (val) => typeof val === "boolean" || typeof val === "number" }, + { name: 'state', test: (val) => typeof val === 'boolean' || typeof val === 'number' }, { name: 'uuid' } ]), getUser(true), postRouteHandler); function postRouteHandler(req:express.Request, res:express.Response) { if (res.locals.user['perm'] === 'Admin') { - if (typeof req.body.state === "boolean") - req.body.state = req.body.state ? 1 : 0 + if (typeof req.body.state === 'boolean') + req.body.state = req.body.state ? 1 : 0; const response = loginBackend.changeActiveState(req.body.state, req.body.uuid, req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress); if (response.isOk === true) { - res.status(200).end(response.value) + res.status(200).end(response.value); } else { - res.status(response.statusCode).end(response.message) + res.status(response.statusCode).end(response.message); } } else { - console.log(`[ERROR] User was not correctly parsed on ${routeName} request!`) - res.status(500).end() + console.log(`[ERROR] User was not correctly parsed on ${routeName} request!`); + res.status(500).end(); } } diff --git a/routes/backend/changePass.ts b/routes/backend/changePass.ts index 8359940..c82be6c 100644 --- a/routes/backend/changePass.ts +++ b/routes/backend/changePass.ts @@ -18,9 +18,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const response = loginBackend.changePassword(req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress, req.body.oldPass, req.body.newPass); if (response.isOk === true) { - res.status(200).end(response.value) + res.status(200).end(response.value); } else { - res.status(response.statusCode).end(response.message) + res.status(response.statusCode).end(response.message); } } diff --git a/routes/backend/checkToken.ts b/routes/backend/checkToken.ts index f9f1b3d..6e5697e 100644 --- a/routes/backend/checkToken.ts +++ b/routes/backend/checkToken.ts @@ -15,9 +15,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const response = loginBackend.checkToken(req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress); if (response.isOk === true) { - res.status(200).json(response.value).end() + res.status(200).json(response.value).end(); } else { - res.status(response.statusCode).end(response.message) + res.status(response.statusCode).end(response.message); } } diff --git a/routes/backend/deleteToken.ts b/routes/backend/deleteToken.ts index a1c02b1..05e4d09 100644 --- a/routes/backend/deleteToken.ts +++ b/routes/backend/deleteToken.ts @@ -17,9 +17,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const response = loginBackend.deleteToken(req.body.uuid, req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress); if (response.isOk === true) { - res.status(200).end(response.value) + res.status(200).end(response.value); } else { - res.status(response.statusCode).end(response.message) + res.status(response.statusCode).end(response.message); } } diff --git a/routes/backend/getFiles.ts b/routes/backend/getFiles.ts index 18e525d..ee7d07f 100644 --- a/routes/backend/getFiles.ts +++ b/routes/backend/getFiles.ts @@ -11,7 +11,7 @@ router.route('/' + routeName + '/') .get(requireArguments([ { name: 'path', test: (val) => typeof val === 'string' || val === undefined }, { name: 'token' }, - { name: 'type', test: (val) => typeof val === "string" || val === undefined, optional: true} + { name: 'type', test: (val) => typeof val === 'string' || val === undefined, optional: true} ]), postRouteHandler); function postRouteHandler(req:express.Request, res:express.Response) { @@ -20,9 +20,9 @@ function postRouteHandler(req:express.Request, res:express.Response) { res.status(200).json({ files: files.value, pathSep: Path.sep - }) + }); } else { - res.status(files.statusCode).end(files.message) + res.status(files.statusCode).end(files.message); } } diff --git a/routes/backend/getSortTypes.ts b/routes/backend/getSortTypes.ts index 8322c59..f85f7b7 100644 --- a/routes/backend/getSortTypes.ts +++ b/routes/backend/getSortTypes.ts @@ -13,9 +13,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const answer = fileStuff.getSortTypes(); if (answer.isOk === true) { - res.status(200).json(answer.value).end() + res.status(200).json(answer.value).end(); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/getStars.ts b/routes/backend/getStars.ts index c52894f..7aff5bb 100644 --- a/routes/backend/getStars.ts +++ b/routes/backend/getStars.ts @@ -16,9 +16,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const answer = fileStuff.getStars(req.query.token as string, req.header('x-forwarded-for') || req.socket.remoteAddress, req.query.path as string); if (answer.isOk === true) { - res.status(200).end(answer.value.toString()) + res.status(200).end(answer.value.toString()); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/getTime.ts b/routes/backend/getTime.ts index 539fae1..f4415db 100644 --- a/routes/backend/getTime.ts +++ b/routes/backend/getTime.ts @@ -16,9 +16,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const answer = fileStuff.loadTime(req.query.path as string, req.query.token as string, req.header('x-forwarded-for') || req.socket.remoteAddress); if (answer.isOk === true) { - res.status(200).end(answer.value.toString()) + res.status(200).end(answer.value.toString()); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/getUserData.ts b/routes/backend/getUserData.ts index 36f44af..a554f16 100644 --- a/routes/backend/getUserData.ts +++ b/routes/backend/getUserData.ts @@ -17,9 +17,9 @@ function postRouteHandler(req:express.Request, res:express.Response) { return res.status(400).send({status: false, reason: 'Can\'t parse query parameters'}); const answer = util.getUserData(req.query.token as string, req.header('x-forwarded-for') || req.socket.remoteAddress); if (answer.isOk === true) { - res.status(200).json(answer.value).end() + res.status(200).json(answer.value).end(); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/getUsers.ts b/routes/backend/getUsers.ts index 822eee8..bbc77b4 100644 --- a/routes/backend/getUsers.ts +++ b/routes/backend/getUsers.ts @@ -17,9 +17,9 @@ function postRouteHandler(req:express.Request, res:express.Response) { return res.status(400).send({status: false, reason: 'Can\'t parse query parameters'}); const answer = loginBackend.loadUsers(req.query.token as string, req.header('x-forwarded-for') || req.socket.remoteAddress); if (answer.isOk === true) { - res.status(200).json(answer.value).end() + res.status(200).json(answer.value).end(); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/login.ts b/routes/backend/login.ts index f2bff0c..2787a57 100644 --- a/routes/backend/login.ts +++ b/routes/backend/login.ts @@ -16,9 +16,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const answer = loginBackend.GenerateUserToken(req.body.Username, req.body.Passwort, req.header('x-forwarded-for') || req.socket.remoteAddress); if (answer.isOk === true) { - res.status(200).end(answer.value) + res.status(200).end(answer.value); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/logout.ts b/routes/backend/logout.ts index 27b35ba..c2577bc 100644 --- a/routes/backend/logout.ts +++ b/routes/backend/logout.ts @@ -15,9 +15,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:express.Request, res:express.Response) { const answer = loginBackend.logout(req.body.token); if (answer.isOk === true) { - res.status(200).end(answer.value) + res.status(200).end(answer.value); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/removeWatchList.ts b/routes/backend/removeWatchList.ts index 9218b78..aa83562 100644 --- a/routes/backend/removeWatchList.ts +++ b/routes/backend/removeWatchList.ts @@ -18,9 +18,9 @@ router.route('/' + routeName + '/') function postRouteHandler(req:Request, res:Response) { const answer = fileStuff.removeFromWatchList(req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress, req.body.path); if (answer.isOk === true) { - res.status(200).end(answer.value) + res.status(200).end(answer.value); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/setStars.ts b/routes/backend/setStars.ts index 46f90cf..d2485d5 100644 --- a/routes/backend/setStars.ts +++ b/routes/backend/setStars.ts @@ -11,16 +11,16 @@ router.route('/' + routeName + '/') .put(getUser(true), requireArguments([ { name: 'path' }, { name: 'token' }, - { name: 'stars', test: (val) => typeof val === "number" && (val === 1 || val === 2 + { name: 'stars', test: (val) => typeof val === 'number' && (val === 1 || val === 2 || val === 3 || val === 4 || val === 5 || val === 0)} ]), postRouteHandler); function postRouteHandler(req:express.Request, res:express.Response) { const answer = fileStuff.setStars(req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress, req.body.path, req.body.stars); if (answer.isOk === true) { - res.status(200).end(answer.value.toString()) + res.status(200).end(answer.value.toString()); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/setTime.ts b/routes/backend/setTime.ts index d6b1756..5455116 100644 --- a/routes/backend/setTime.ts +++ b/routes/backend/setTime.ts @@ -11,15 +11,15 @@ router.route('/' + routeName + '/') .put(getUser(true), requireArguments([ { name: 'path' }, { name: 'token' }, - { name: 'percent', test: (val) => typeof val === "number" && val <= 1 && val >= 0} + { name: 'percent', test: (val) => typeof val === 'number' && val <= 1 && val >= 0} ]), postRouteHandler); function postRouteHandler(req:express.Request, res:express.Response) { const answer = fileStuff.saveTime(req.body.path, req.body.token, req.body.percent, req.header('x-forwarded-for') || req.socket.remoteAddress); if (answer.isOk === true) { - res.status(200).end(answer.value) + res.status(200).end(answer.value); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } } diff --git a/routes/backend/setUserData.ts b/routes/backend/setUserData.ts index a47131f..f8deb8a 100644 --- a/routes/backend/setUserData.ts +++ b/routes/backend/setUserData.ts @@ -10,15 +10,15 @@ const routeName = filename.slice(0, filename.length - 1).join('.'); router.route('/' + routeName + '/') .put(getUser(true), requireArguments([ { name: 'token' }, - { name: 'data', test: (val) => typeof val === "object"} + { name: 'data', test: (val) => typeof val === 'object'} ]), postRouteHandler); function postRouteHandler(req:express.Request, res:express.Response) { const answer = util.saveUserData(req.body.token, req.header('x-forwarded-for') || req.socket.remoteAddress, req.body.data); if (answer.isOk === true) { - res.status(200).end(answer.value) + res.status(200).end(answer.value); } else { - res.status(answer.statusCode).end(answer.message) + res.status(answer.statusCode).end(answer.message); } }