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

View File

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

View File

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

View File

@ -9,28 +9,29 @@ const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const url = req.query.url
let bitrate = req.query.bitrate
if (bitrate === 'null') bitrate = settings.maxBitrate
let obj: any;
const url = req.query.url
let bitrate = req.query.bitrate
if (bitrate === 'null') bitrate = settings.maxBitrate
let obj: any
try {
obj = await addToQueue(dz, url, bitrate)
} catch (e){
switch (e.name) {
case 'AlreadyInQueue':
res.send({result: false, errid: e.name, data: {url, bitrate, obj: e.data}})
break
try {
obj = await addToQueue(dz, url, bitrate)
} catch (e) {
switch (e.name) {
case 'AlreadyInQueue':
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
default:
console.error(e)
case 'NotLoggedIn':
res.send({result: false, errid: e.name, data: {url, bitrate}})
break
}
return
}
break
}
return
}
res.send({result: true, data: {url, bitrate, obj}})
res.send({ result: true, data: { url, bitrate, obj } })
}
const apiHandler: ApiHandler = { path, handler }

View File

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

View File

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