fix(server): lint errors

This commit is contained in:
Roberto Tonino 2021-05-13 20:47:48 +02:00
parent 6b8e3be014
commit 669854f799
6 changed files with 112 additions and 114 deletions

View File

@ -1,25 +1,25 @@
import fs from 'fs'
import { sep } from 'path'
// @ts-expect-error // @ts-expect-error
import deemix from 'deemix' import deemix from 'deemix'
import fs from 'fs'
import {sep} from 'path'
import { wss } from './app'
import WebSocket from 'ws' import WebSocket from 'ws'
import { wss } from './app'
const Downloader = deemix.downloader.Downloader const Downloader = deemix.downloader.Downloader
const { Single, Collection, Convertable } = deemix.types.downloadObjects const { Single, Collection, Convertable } = deemix.types.downloadObjects
export const defaultSettings: any = deemix.settings.DEFAULTS export const defaultSettings: any = deemix.settings.DEFAULTS
export const configFolder: string = deemix.utils.localpaths.getConfigFolder() export const configFolder: string = deemix.utils.localpaths.getConfigFolder()
export let settings: any = deemix.settings.load(configFolder) export let settings: any = deemix.settings.load(configFolder)
export let sessionDZ: any = {} export const sessionDZ: any = {}
let deemixPlugins = {} const deemixPlugins = {}
export const listener = { export const listener = {
send: function(key:string, data:any){ send(key: string, data: any) {
console.log(key, data) console.log(key, data)
wss.clients.forEach(client => { wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) { if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({key, data})) client.send(JSON.stringify({ key, data }))
} }
}) })
} }
@ -30,66 +30,63 @@ export function saveSettings(newSettings: any) {
settings = newSettings settings = newSettings
} }
export let queueOrder: string[] = [] export const queueOrder: string[] = []
export let queue: any = {} export const queue: any = {}
export let currentJob: any = null let currentJob: any = null
export async function addToQueue(dz: any, url: string, bitrate: number){ export async function addToQueue(dz: any, url: string, bitrate: number) {
if (!dz.logged_in) throw new NotLoggedIn if (!dz.logged_in) throw new NotLoggedIn()
console.log(`Adding ${url} to queue`) console.log(`Adding ${url} to queue`)
let downloadObjs = await deemix.generateDownloadObject(dz, url, bitrate, deemixPlugins, listener) let downloadObjs = await deemix.generateDownloadObject(dz, url, bitrate, deemixPlugins, listener)
let isSingleObject = !Array.isArray(downloadObjs) const isSingleObject = !Array.isArray(downloadObjs)
console.log(downloadObjs) console.log(downloadObjs)
if (isSingleObject) downloadObjs = [downloadObjs] if (isSingleObject) downloadObjs = [downloadObjs]
let slimmedObjects: any[] = [] const slimmedObjects: any[] = []
downloadObjs.forEach(async (downloadObj: any) => { downloadObjs.forEach((downloadObj: any) => {
// Check if element is already in queue // Check if element is already in queue
if (queueOrder.includes(downloadObj.uuid)) if (queueOrder.includes(downloadObj.uuid)) throw new AlreadyInQueue(downloadObj.getEssentialDict(), !isSingleObject)
throw new AlreadyInQueue(downloadObj.getEssentialDict(), !isSingleObject)
// Save queue status when adding something to the queue // Save queue status when adding something to the queue
if (!fs.existsSync(configFolder+'queue')) fs.mkdirSync(configFolder+'queue') if (!fs.existsSync(configFolder + 'queue')) fs.mkdirSync(configFolder + 'queue')
queueOrder.push(downloadObj.uuid) queueOrder.push(downloadObj.uuid)
fs.writeFileSync(configFolder+`queue${sep}order.json`, JSON.stringify(queueOrder)) fs.writeFileSync(configFolder + `queue${sep}order.json`, JSON.stringify(queueOrder))
queue[downloadObj.uuid] = downloadObj.getEssentialDict() queue[downloadObj.uuid] = downloadObj.getEssentialDict()
fs.writeFileSync(configFolder+`queue${sep}${downloadObj.uuid}.json`, JSON.stringify(downloadObj.toDict())) fs.writeFileSync(configFolder + `queue${sep}${downloadObj.uuid}.json`, JSON.stringify(downloadObj.toDict()))
slimmedObjects.push(downloadObj.getSlimmedDict()) slimmedObjects.push(downloadObj.getSlimmedDict())
}) })
if (isSingleObject) if (isSingleObject) listener.send('addedToQueue', downloadObjs[0].getSlimmedDict())
listener.send('addedToQueue', downloadObjs[0].getSlimmedDict()) else listener.send('addedToQueue', slimmedObjects)
else
listener.send('addedToQueue', slimmedObjects)
startQueue(dz) startQueue(dz)
return slimmedObjects return slimmedObjects
} }
async function startQueue(dz: any): Promise<any>{ async function startQueue(dz: any): Promise<any> {
do { do {
if (currentJob !== null || queueOrder.length === 0){ if (currentJob !== null || queueOrder.length === 0) {
// Should not start another download // Should not start another download
return null return null
} }
currentJob = true // lock currentJob currentJob = true // lock currentJob
let currentUUID: string | undefined = queueOrder.shift() const currentUUID: string | undefined = queueOrder.shift()
let currentItem: any = JSON.parse(fs.readFileSync(configFolder+`queue${sep}${currentUUID}.json`).toString()) const currentItem: any = JSON.parse(fs.readFileSync(configFolder + `queue${sep}${currentUUID}.json`).toString())
let downloadObject: any let downloadObject: any
switch (currentItem.__type__) { switch (currentItem.__type__) {
case 'Single': case 'Single':
downloadObject = new Single(currentItem) downloadObject = new Single(currentItem)
break; break
case 'Collection': case 'Collection':
downloadObject = new Collection(currentItem) downloadObject = new Collection(currentItem)
break; break
case 'Convertable': case 'Convertable':
downloadObject = new Convertable(currentItem) downloadObject = new Convertable(currentItem)
// Convert object here // Convert object here
break; break
} }
currentJob = new Downloader(dz, downloadObject, settings, listener) currentJob = new Downloader(dz, downloadObject, settings, listener)
listener.send('startDownload', currentUUID) listener.send('startDownload', currentUUID)
@ -101,7 +98,7 @@ async function startQueue(dz: any): Promise<any>{
class QueueError extends Error { class QueueError extends Error {
constructor(message: string) { constructor(message: string) {
super(message) super(message)
this.name = "QueueError" this.name = 'QueueError'
} }
} }
@ -110,7 +107,7 @@ class AlreadyInQueue extends QueueError {
silent: boolean silent: boolean
constructor(dwObj: any, silent: boolean) { constructor(dwObj: any, silent: boolean) {
super(`${dwObj.artist} - ${dwObj.title} is already in queue.`) super(`${dwObj.artist} - ${dwObj.title} is already in queue.`)
this.name = "AlreadyInQueue" this.name = 'AlreadyInQueue'
this.item = dwObj this.item = dwObj
this.silent = silent this.silent = silent
} }
@ -119,6 +116,6 @@ class AlreadyInQueue extends QueueError {
class NotLoggedIn extends QueueError { class NotLoggedIn extends QueueError {
constructor() { constructor() {
super(`You must be logged in to start a download.`) super(`You must be logged in to start a download.`)
this.name = "NotLoggedIn" this.name = 'NotLoggedIn'
} }
} }

View File

@ -1,6 +1,6 @@
import type { Application } from 'express' import type { Application } from 'express'
import logger from 'morgan'
import express from 'express' import express from 'express'
import logger from 'morgan'
import cookieParser from 'cookie-parser' import cookieParser from 'cookie-parser'
import session from 'express-session' import session from 'express-session'

View File

@ -3,7 +3,7 @@ import { settings, defaultSettings } from '../../../main'
const path: ApiHandler['path'] = '/getSettings' const path: ApiHandler['path'] = '/getSettings'
const handler: ApiHandler['handler'] = async (_, res) => { const handler: ApiHandler['handler'] = (_, res) => {
res.send({ settings, defaultSettings }) res.send({ settings, defaultSettings })
} }

View File

@ -12,25 +12,26 @@ const handler: ApiHandler['handler'] = async (req, res) => {
const url = req.query.url const url = req.query.url
let bitrate = req.query.bitrate let bitrate = req.query.bitrate
if (bitrate === 'null') bitrate = settings.maxBitrate if (bitrate === 'null') bitrate = settings.maxBitrate
let obj: any; let obj: any
try { try {
obj = await addToQueue(dz, url, bitrate) obj = await addToQueue(dz, url, bitrate)
} catch (e){ } catch (e) {
switch (e.name) { switch (e.name) {
case 'AlreadyInQueue': case 'AlreadyInQueue':
res.send({result: false, errid: e.name, data: {url, bitrate, obj: e.data}}) res.send({ result: false, errid: e.name, data: { url, bitrate, obj: e.data } })
break
case 'NotLoggedIn':
res.send({ result: false, errid: e.name, data: { url, bitrate } })
break break
default: default:
console.error(e) console.error(e)
case 'NotLoggedIn':
res.send({result: false, errid: e.name, data: {url, bitrate}})
break break
} }
return return
} }
res.send({result: true, data: {url, bitrate, obj}}) res.send({ result: true, data: { url, bitrate, obj } })
} }
const apiHandler: ApiHandler = { path, handler } const apiHandler: ApiHandler = { path, handler }

View File

@ -1,5 +1,5 @@
import WebSocket from 'ws'
import { Server as WsServer } from 'ws' import { Server as WsServer } from 'ws'
import { consoleError, consoleInfo } from '../helpers/errors' import { consoleError, consoleInfo } from '../helpers/errors'
import wsModules from './modules' import wsModules from './modules'
@ -8,7 +8,7 @@ import wsModules from './modules'
export const registerWebsocket = (wss: WsServer) => { export const registerWebsocket = (wss: WsServer) => {
wss.on('connection', ws => { wss.on('connection', ws => {
ws.on('message', (message)=>{ ws.on('message', message => {
consoleInfo(`received: ${message}`) consoleInfo(`received: ${message}`)
const data = JSON.parse(message.toString()) const data = JSON.parse(message.toString())
wsModules.forEach(module => { wsModules.forEach(module => {

View File

@ -4,11 +4,11 @@ import { saveSettings, listener } from '../../main'
const eventName = 'saveSettings' const eventName = 'saveSettings'
const cb = (data: any, ws: any, wss: WsServer) => { const cb = (data: any, _: any, __: WsServer) => {
const {settings, spotifySettings} = data const { settings, spotifySettings } = data
saveSettings(settings) saveSettings(settings)
consoleInfo('Settings saved') consoleInfo('Settings saved')
listener.send('updateSettings', {settings, spotifySettings}) listener.send('updateSettings', { settings, spotifySettings })
} }
export default { eventName, cb } export default { eventName, cb }