diff --git a/packages/common/utils/config.ts b/packages/common/utils/config.ts index 291e045a..390e27b5 100644 --- a/packages/common/utils/config.ts +++ b/packages/common/utils/config.ts @@ -162,7 +162,10 @@ export const updateConfigFile = () => { } if (newOptions !== '') { - wLogger.warn(`New options available in config: ${newOptions}\n`); + wLogger.warn( + '[config]', + `New options available in config: ${newOptions}\n` + ); } }; @@ -200,7 +203,7 @@ export const refreshConfig = (httpServer: any, refresh: boolean) => { const { parsed, error } = dotenv.config({ path: configPath }); if (error != null || parsed == null) { - wLogger.error(`Config ${status} failed`); + wLogger.error('[config]', `Config ${status} failed`); return; } @@ -295,7 +298,7 @@ export const refreshConfig = (httpServer: any, refresh: boolean) => { fs.mkdirSync(staticPath); } - if (updated) wLogger.info(`Config ${status}ed`); + if (updated) wLogger.info('[config]', `Config ${status}ed`); }; export const writeConfig = (httpServer: any, options: any) => { diff --git a/packages/common/utils/logger.ts b/packages/common/utils/logger.ts index e334f013..e96eecd7 100644 --- a/packages/common/utils/logger.ts +++ b/packages/common/utils/logger.ts @@ -29,15 +29,15 @@ export const wLogger = { const coloredText = colorText('info'); console.log(coloredText, ...args); - if (config.debugLogging === true) writeLog('info', args); + writeLog('info', args); }, debug: (...args: any) => { + writeLog('debug', args); + if (config.debugLogging !== true) return; const coloredText = colorText('debug'); console.log(coloredText, ...args); - - writeLog('debug', args); }, debugError: (...args: any) => { if (config.debugLogging !== true) return; @@ -45,19 +45,19 @@ export const wLogger = { const coloredText = colorText('debugError'); console.log(coloredText, ...args); - if (config.debugLogging === true) writeLog('debugError', args); + writeLog('debugError', args); }, error: (...args: any) => { const coloredText = colorText('error'); console.log(coloredText, ...args); - if (config.debugLogging === true) writeLog('error', args); + writeLog('error', args); }, warn: (...args: any) => { const coloredText = colorText('warn'); console.log(coloredText, ...args); - if (config.debugLogging === true) writeLog('warn', args); + writeLog('warn', args); } }; diff --git a/packages/common/utils/unzip.ts b/packages/common/utils/unzip.ts index 3bf995a5..69aa4edd 100644 --- a/packages/common/utils/unzip.ts +++ b/packages/common/utils/unzip.ts @@ -5,19 +5,16 @@ import { wLogger } from './logger'; export const unzip = (zipPath: string, extractPath: string): Promise => new Promise((resolve, reject) => { - if (!fs.existsSync(extractPath)) { - fs.mkdirSync(extractPath); - } - const zip = new AdmZip(zipPath); try { - // Extract all contents of the zip file to the specified destination - zip.extractAllTo(extractPath, /* overwrite */ true); + if (!fs.existsSync(extractPath)) fs.mkdirSync(extractPath); + + zip.extractAllTo(extractPath, true); resolve(extractPath); } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + wLogger.error('[unzip]', (error as any).message); + wLogger.debug('[unzip]', error); reject(error); } }); diff --git a/packages/server/index.ts b/packages/server/index.ts index de1ab53f..708cb495 100644 --- a/packages/server/index.ts +++ b/packages/server/index.ts @@ -120,7 +120,7 @@ export class Server { return next(); } - wLogger.warn('Unallowed request', req.url, { + wLogger.warn('[request]', 'Unallowed request', req.url, { address: req.socket.remoteAddress, origin: req.headers.origin, referer: req.headers.referer diff --git a/packages/server/router/assets.ts b/packages/server/router/assets.ts index 4d2cb13d..c7eabb9a 100644 --- a/packages/server/router/assets.ts +++ b/packages/server/router/assets.ts @@ -15,10 +15,8 @@ export default function buildAssetsApi(server: Server) { path.join(pkgAssetsPath, req.params.filePath), (err, content) => { if (err) { - wLogger.debug(err); - res.writeHead(404, { - 'Content-Type': 'text/html' - }); + wLogger.debug(`/assets/${req.params.filePath}`, err); + res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('page not found'); return; diff --git a/packages/server/router/index.ts b/packages/server/router/index.ts index e5d235a7..623a22c5 100644 --- a/packages/server/router/index.ts +++ b/packages/server/router/index.ts @@ -1,5 +1,6 @@ import rosu from '@kotrikd/rosu-pp'; import { + JsonSafeParse, downloadFile, getCachePath, getProgramPath, @@ -38,37 +39,26 @@ export default function buildBaseApi(server: Server) { req.instanceManager.focusedClient ); if (!osuInstance) { - res.statusCode = 500; - wLogger.debug('/json', 'not_ready'); - return sendJson(res, { error: 'not_ready' }); + throw new Error('osu is not ready/running'); } const json = osuInstance.getState(req.instanceManager); - sendJson(res, json); + return sendJson(res, json); }); server.app.route( /^\/api\/counters\/search\/(?.*)/, 'GET', (req, res) => { - try { - const query = decodeURI(req.params.query) - .replace(/[^a-z0-9A-Z]/, '') - .toLowerCase(); + const query = decodeURI(req.params.query) + .replace(/[^a-z0-9A-Z]/, '') + .toLowerCase(); - if (req.query?.tab === '1') { - return buildExternalCounters(res, query); - } - - return buildLocalCounters(res, query); - } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); - - return sendJson(res, { - error: (error as any).message - }); + if (req.query?.tab === '1') { + return buildExternalCounters(res, query); } + + return buildLocalCounters(res, query); } ); @@ -97,55 +87,54 @@ export default function buildBaseApi(server: Server) { if (!fs.existsSync(cacheFolder)) fs.mkdirSync(cacheFolder); - try { - const startUnzip = (result) => { - unzip(result, folderPath) - .then(() => { - wLogger.info( - `PP Counter downloaded: ${folderName} (${req.headers.referer})` - ); - fs.unlinkSync(tempPath); - - server.WS_COMMANDS.socket.emit( - 'message', - `getCounters:__ingame__` - ); - - sendJson(res, { - status: 'Finished', - path: result - }); - }) - .catch((reason) => { - fs.unlinkSync(tempPath); - wLogger.debug( - `counter-${folderName}-unzip`, - reason - ); - - sendJson(res, { - error: reason - }); - }); - }; + const startUnzip = (result) => { + unzip(result, folderPath) + .then(() => { + wLogger.info( + `PP Counter downloaded: ${folderName} (${req.headers.referer})` + ); + fs.unlinkSync(tempPath); + + server.WS_COMMANDS.socket.emit( + 'message', + `getCounters:__ingame__` + ); - downloadFile(req.params.url, tempPath) - .then(startUnzip) + sendJson(res, { + status: 'Finished', + path: result + }); + }) .catch((reason) => { - wLogger.debug(`counter-${folderName}-download`, reason); + fs.unlinkSync(tempPath); + + wLogger.error( + '[overlay-unzip]', + folderName, + (reason as Error).message + ); + wLogger.debug('[overlay-unzip]', folderName, reason); sendJson(res, { - error: reason + error: (reason as Error).message }); }); - } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + }; - sendJson(res, { - error: (error as any).message + downloadFile(req.params.url, tempPath) + .then(startUnzip) + .catch((reason) => { + wLogger.error( + '[overlay-download]', + folderName, + (reason as Error).message + ); + wLogger.debug(`[overlay-download]`, folderName, reason); + + sendJson(res, { + error: (reason as Error).message + }); }); - } } ); @@ -153,50 +142,53 @@ export default function buildBaseApi(server: Server) { /^\/api\/counters\/open\/(?.*)/, 'GET', (req, res) => { - try { - const folderName = req.params.name; - if (!folderName) { - return sendJson(res, { - error: 'no folder name' - }); - } - - const staticPath = getStaticPath(); - let folderPath = path.join(staticPath, decodeURI(folderName)); - if (folderName === 'tosu.exe') folderPath = getProgramPath(); - else if (folderName === 'static.exe') - folderPath = getStaticPath(); + const folderName = req.params.name; + if (!folderName) { + return sendJson(res, { + error: 'no folder name' + }); + } - if (!fs.existsSync(folderPath)) { - return sendJson(res, { - error: "Folder doesn't exists" - }); - } + const staticPath = getStaticPath(); + let folderPath = path.join(staticPath, decodeURI(folderName)); + if (folderName === 'tosu.exe') folderPath = getProgramPath(); + else if (folderName === 'static.exe') folderPath = getStaticPath(); - wLogger.info( - `PP Counter opened: ${folderName} (${req.headers.referer})` - ); + if (!fs.existsSync(folderPath)) { + return sendJson(res, { + error: "Folder doesn't exists" + }); + } - const platform = platformResolver(process.platform); - exec(`${platform.command} "${folderPath}"`, (err) => { - if (err) { - wLogger.error('Error opening file explorer:'); - wLogger.debug(err); + wLogger.info( + `PP Counter opened: ${folderName} (${req.headers.referer})` + ); - return sendJson(res, { - error: `Error opening file explorer: ${err.message}` - }); - } + const platform = platformResolver(process.platform); + exec(`${platform.command} "${folderPath}"`, (err) => { + if (err) { + wLogger.error( + '/counters/open', + req.query.name, + 'Error opening folder', + err.message + ); + wLogger.debug( + '/counters/open', + req.query.name, + 'Error opening folder', + err + ); return sendJson(res, { - status: 'opened' + error: `Error opening folder: ${err.message}` }); - }); - } catch (error) { + } + return sendJson(res, { - error: (error as any).message + status: 'opened' }); - } + }); } ); @@ -204,42 +196,33 @@ export default function buildBaseApi(server: Server) { /^\/api\/counters\/delete\/(?.*)/, 'GET', (req, res) => { - try { - const folderName = req.params.name; - if (!folderName) { - return sendJson(res, { - error: 'no folder name' - }); - } + const folderName = req.params.name; + if (!folderName) { + return sendJson(res, { + error: 'no folder name' + }); + } - const staticPath = getStaticPath(); - const folderPath = path.join(staticPath, decodeURI(folderName)); + const staticPath = getStaticPath(); + const folderPath = path.join(staticPath, decodeURI(folderName)); - if (!fs.existsSync(folderPath)) { - return sendJson(res, { - error: "Folder doesn't exists" - }); - } + if (!fs.existsSync(folderPath)) { + return sendJson(res, { + error: "Folder doesn't exists" + }); + } - wLogger.info( - `PP Counter removed: ${folderName} (${req.headers.referer})` - ); + wLogger.info( + `PP Counter removed: ${folderName} (${req.headers.referer})` + ); - fs.rmSync(folderPath, { recursive: true, force: true }); + fs.rmSync(folderPath, { recursive: true, force: true }); - server.WS_COMMANDS.socket.emit( - 'message', - `getCounters:__ingame__` - ); + server.WS_COMMANDS.socket.emit('message', `getCounters:__ingame__`); - return sendJson(res, { - status: 'deleted' - }); - } catch (error) { - return sendJson(res, { - error: (error as any).message - }); - } + return sendJson(res, { + status: 'deleted' + }); } ); @@ -247,36 +230,27 @@ export default function buildBaseApi(server: Server) { /^\/api\/counters\/settings\/(?.*)/, 'GET', (req, res) => { - try { - const folderName = req.params.name; - if (!folderName) { - return sendJson(res, { - error: 'No folder name' - }); - } - - const settings = parseCounterSettings(folderName, 'parse'); - if (settings instanceof Error) { - wLogger.debug( - `counter-${folderName}-settings-get`, - settings - ); - - return sendJson(res, { - error: settings.name - }); - } + const folderName = req.params.name; + if (!folderName) { + return sendJson(res, { + error: 'No folder name' + }); + } - wLogger.info( - `Settings accessed: ${folderName} (${req.headers.referer})` - ); + const settings = parseCounterSettings(folderName, 'parse'); + if (settings instanceof Error) { + wLogger.debug(`[overlay-settings]`, folderName, settings); - return sendJson(res, settings); - } catch (error) { return sendJson(res, { - error: (error as any).message + error: settings.message }); } + + wLogger.info( + `Settings accessed: ${folderName} (${req.headers.referer})` + ); + + return sendJson(res, settings); } ); @@ -284,267 +258,217 @@ export default function buildBaseApi(server: Server) { /^\/api\/counters\/settings\/(?.*)/, 'POST', (req, res) => { - let body: ISettings[]; - try { - body = JSON.parse(req.body); - } catch (error) { + const body: ISettings[] | Error = JsonSafeParse( + req.body, + new Error('Failed to parse body') + ); + if (body instanceof Error) throw body; + + const folderName = req.params.name; + if (!folderName) { return sendJson(res, { - error: (error as any).message + error: 'no folder name' }); } - try { - const folderName = req.params.name; - if (!folderName) { - return sendJson(res, { - error: 'no folder name' - }); - } - - if (req.query.update === 'yes') { - const result = parseCounterSettings( + if (req.query.update === 'yes') { + const result = parseCounterSettings( + folderName, + 'dev/save', + body as any + ); + if (result instanceof Error) { + wLogger.debug( + `[overlay-settings]`, + 'update', folderName, - 'dev/save', - body as any + result ); - if (result instanceof Error) { - wLogger.debug(`${folderName}-settings-update`, result); - - return sendJson(res, { - error: result.name - }); - } - wLogger.info( - `Settings re:created: ${folderName} (${req.headers.referer})` - ); - - fs.writeFileSync( - result.settingsPath!, - JSON.stringify(result.settings), - 'utf8' - ); - - return sendJson(res, { result: 'success' }); + return sendJson(res, { + error: result.message + }); } wLogger.info( - `Settings saved: ${folderName} (${req.headers.referer})` + `Settings re:created: ${folderName} (${req.headers.referer})` ); - const html = saveSettings(folderName, body as any); - if (html instanceof Error) { - wLogger.debug(`${folderName}-settings-save`, html); - - return sendJson(res, { - error: html.name - }); - } - - server.WS_COMMANDS.socket.emit( - 'message', - `getSettings:${folderName}` + fs.writeFileSync( + result.settingsPath!, + JSON.stringify(result.settings), + 'utf8' ); return sendJson(res, { result: 'success' }); - } catch (error) { + } + + wLogger.info( + `Settings saved: ${folderName} (${req.headers.referer})` + ); + + const html = saveSettings(folderName, body as any); + if (html instanceof Error) { + wLogger.debug(`[overlay-settings]`, 'save', folderName, html); + return sendJson(res, { - error: (error as any).message + error: html.message }); } + + server.WS_COMMANDS.socket.emit( + 'message', + `getSettings:${folderName}` + ); + + return sendJson(res, { result: 'success' }); } ); server.app.route('/api/runUpdates', 'GET', async (req, res) => { - try { - const result = await autoUpdater(); - if (result instanceof Error) { - sendJson(res, { result: result.name }); - return; - } - - sendJson(res, { result: 'updated' }); - } catch (exc) { - wLogger.error('runUpdates', (exc as any).message); - wLogger.debug('runUpdates', exc); - - return sendJson(res, { - error: (exc as any).message - }); + const result = await autoUpdater(); + if (result instanceof Error) { + sendJson(res, { result: result.name }); + return; } + + return sendJson(res, { result: 'updated' }); }); server.app.route('/api/settingsSave', 'POST', (req, res) => { - let body: object; - try { - body = JSON.parse(req.body); - } catch (error) { - return sendJson(res, { - error: (error as any).message - }); - } + const body: object | Error = JsonSafeParse( + req.body, + new Error('Failed to parse body') + ); + if (body instanceof Error) throw body; writeConfig(server, body); - - sendJson(res, { - status: 'updated' - }); + return sendJson(res, { status: 'updated' }); }); server.app.route('/api/calculate/pp', 'GET', (req, res) => { - try { - const query: any = req.query; + const query: any = req.query; - const osuInstance: any = req.instanceManager.getInstance( - req.instanceManager.focusedClient - ); - if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - const { global, menu, beatmapPP } = osuInstance.getServices([ - 'global', - 'menu', - 'beatmapPP' - ]); - - let beatmap: rosu.Beatmap; - const exists = fs.existsSync(query.path); - if (exists) { - const beatmapFilePath = path.join( - global.songsFolder, - menu.folder, - menu.filename - ); - - const beatmapContent = fs.readFileSync(beatmapFilePath, 'utf8'); - beatmap = new rosu.Beatmap(beatmapContent); - } else { - beatmap = beatmapPP.getCurrentBeatmap(); - } + const osuInstance: any = req.instanceManager.getInstance( + req.instanceManager.focusedClient + ); + if (!osuInstance) { + throw new Error('osu is not ready/running'); + } - if (query.mode !== undefined) beatmap.convert(query.mode); - - const params: rosu.PerformanceArgs = {}; - - if (query.ar !== undefined) params.ar = +query.ar; - if (query.cs !== undefined) params.cs = +query.cs; - if (query.hp !== undefined) params.hp = +query.hp; - if (query.od !== undefined) params.od = +query.od; - - if (query.clockRate !== undefined) - params.clockRate = +query.clockRate; - if (query.passedObjects !== undefined) - params.passedObjects = +query.passedObjects; - if (query.combo !== undefined) params.combo = +query.combo; - if (query.nMisses !== undefined) params.misses = +query.nMisses; - if (query.n100 !== undefined) params.n100 = +query.n100; - if (query.n300 !== undefined) params.n300 = +query.n300; - if (query.n50 !== undefined) params.n50 = +query.n50; - if (query.nGeki !== undefined) params.nGeki = +query.nGeki; - if (query.nKatu !== undefined) params.nKatu = +query.nKatu; - if (query.mods !== undefined) - params.mods = Array.isArray(query.mods) - ? query.mods - : +query.mods; - if (query.acc !== undefined) params.accuracy = +query.acc; - if (query.sliderEndHits !== undefined) - params.sliderEndHits = +query.sliderEndHits; - if (query.smallTickHits !== undefined) - params.smallTickHits = +query.smallTickHits; - if (query.largeTickHits !== undefined) - params.largeTickHits = +query.largeTickHits; - - const calculate = new rosu.Performance(params).calculate(beatmap); - sendJson(res, calculate); - - // free beatmap only when map path specified - if (query.path) beatmap.free(); - calculate.free(); - } catch (exc) { - wLogger.error('calculate/pp', (exc as any).message); - wLogger.debug('calculate/pp', exc); + const { global, menu, beatmapPP } = osuInstance.getServices([ + 'global', + 'menu', + 'beatmapPP' + ]); + + let beatmap: rosu.Beatmap; + const exists = fs.existsSync(query.path); + if (exists) { + const beatmapFilePath = path.join( + global.songsFolder, + menu.folder, + menu.filename + ); - return sendJson(res, { - error: typeof exc === 'string' ? exc : (exc as any).message - }); + const beatmapContent = fs.readFileSync(beatmapFilePath, 'utf8'); + beatmap = new rosu.Beatmap(beatmapContent); + } else { + beatmap = beatmapPP.getCurrentBeatmap(); } + + if (query.mode !== undefined) beatmap.convert(query.mode); + + const params: rosu.PerformanceArgs = {}; + + if (query.ar !== undefined) params.ar = +query.ar; + if (query.cs !== undefined) params.cs = +query.cs; + if (query.hp !== undefined) params.hp = +query.hp; + if (query.od !== undefined) params.od = +query.od; + + if (query.clockRate !== undefined) params.clockRate = +query.clockRate; + if (query.passedObjects !== undefined) + params.passedObjects = +query.passedObjects; + if (query.combo !== undefined) params.combo = +query.combo; + if (query.nMisses !== undefined) params.misses = +query.nMisses; + if (query.n100 !== undefined) params.n100 = +query.n100; + if (query.n300 !== undefined) params.n300 = +query.n300; + if (query.n50 !== undefined) params.n50 = +query.n50; + if (query.nGeki !== undefined) params.nGeki = +query.nGeki; + if (query.nKatu !== undefined) params.nKatu = +query.nKatu; + if (query.mods !== undefined) + params.mods = Array.isArray(query.mods) ? query.mods : +query.mods; + if (query.acc !== undefined) params.accuracy = +query.acc; + if (query.sliderEndHits !== undefined) + params.sliderEndHits = +query.sliderEndHits; + if (query.smallTickHits !== undefined) + params.smallTickHits = +query.smallTickHits; + if (query.largeTickHits !== undefined) + params.largeTickHits = +query.largeTickHits; + + const calculate = new rosu.Performance(params).calculate(beatmap); + sendJson(res, calculate); + + // free beatmap only when map path specified + if (query.path) beatmap.free(); + calculate.free(); }); server.app.route(/\/api\/ingame/, 'GET', (req, res) => { - try { - fs.readFile( - path.join(pkgAssetsPath, 'ingame.html'), - 'utf8', - (err, content) => { - if (err) { - res.writeHead(500); - return res.end(`Server Error: ${err.code}`); - } - - const counters = getLocalCounters(); - - content += `\n\n\n\n`; - - res.writeHead(200, { - 'Content-Type': 'text/html; charset=utf-8' - }); - res.end(content, 'utf-8'); + fs.readFile( + path.join(pkgAssetsPath, 'ingame.html'), + 'utf8', + (err, content) => { + if (err) { + wLogger.debug('/ingame', err); + res.writeHead(500); + return res.end(`Server Error: ${err.code}\n${err.message}`); } - ); - } catch (error) { - wLogger.debug(error); - return sendJson(res, { - error: (error as any).message - }); - } + const counters = getLocalCounters(); + content += `\n\n\n\n`; + + res.writeHead(200, { + 'Content-Type': 'text/html; charset=utf-8' + }); + res.end(content, 'utf-8'); + } + ); }); server.app.route(/.*/, 'GET', (req, res) => { - try { - const url = req.pathname || '/'; - const staticPath = getStaticPath(); - - if (url === '/') { - if (req.query?.tab === '1') { - return buildExternalCounters(res); - } + const url = req.pathname || '/'; + const staticPath = getStaticPath(); - if (req.query?.tab === '2') { - return buildSettings(res); - } - - if (req.query?.tab === '3') { - return buildInstructionLocal(res); - } + if (url === '/') { + if (req.query?.tab === '1') { + return buildExternalCounters(res); + } - return buildLocalCounters(res); + if (req.query?.tab === '2') { + return buildSettings(res); } - const extension = path.extname(url); - if (extension === '' && !url.endsWith('/')) { - res.writeHead(301, { Location: url + '/' }); - return res.end(); + if (req.query?.tab === '3') { + return buildInstructionLocal(res); } - const selectIndexHTML = url.endsWith('/') - ? url + 'index.html' - : url; - directoryWalker({ - _htmlRedirect: true, - res, - baseUrl: url, - pathname: selectIndexHTML, - folderPath: staticPath - }); - } catch (error) { - wLogger.debug(error); + return buildLocalCounters(res); + } - return sendJson(res, { - error: (error as any).message - }); + const extension = path.extname(url); + if (extension === '' && !url.endsWith('/')) { + res.writeHead(301, { Location: url + '/' }); + return res.end(); } + + const selectIndexHTML = url.endsWith('/') ? url + 'index.html' : url; + directoryWalker({ + _htmlRedirect: true, + res, + baseUrl: url, + pathname: selectIndexHTML, + folderPath: staticPath + }); }); } diff --git a/packages/server/router/scApi.ts b/packages/server/router/scApi.ts index a287afdc..51737a2a 100644 --- a/packages/server/router/scApi.ts +++ b/packages/server/router/scApi.ts @@ -7,12 +7,11 @@ export default function buildSCApi(app: HttpServer) { req.instanceManager.focusedClient ); if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); + throw new Error('osu is not ready/running'); } const json = osuInstance.getStateSC(req.instanceManager); - sendJson(res, json); + return sendJson(res, json); }); app.route('/backgroundImage', 'GET', (req, res) => diff --git a/packages/server/router/socket.ts b/packages/server/router/socket.ts index 54cac6e4..1988de80 100644 --- a/packages/server/router/socket.ts +++ b/packages/server/router/socket.ts @@ -21,7 +21,7 @@ export default function buildSocket({ app.server.on('upgrade', function (request, socket, head) { const allowed = isRequestAllowed(request); if (!allowed) { - wLogger.warn('External WebSocket request detected', request.url, { + wLogger.warn('[ws]', 'External request detected', request.url, { address: request.socket.remoteAddress, origin: request.headers.origin, referer: request.headers.referer @@ -96,11 +96,8 @@ export default function buildSocket({ ); } } catch (exc) { - wLogger.error( - `websocket connection (${request.url}) >>>`, - (exc as any).message - ); - wLogger.debug(exc); + wLogger.error('[ws]', request.url, (exc as any).message); + wLogger.debug('[ws]', request.url, exc); } }); } diff --git a/packages/server/router/v1.ts b/packages/server/router/v1.ts index 66d41071..3ac248c5 100644 --- a/packages/server/router/v1.ts +++ b/packages/server/router/v1.ts @@ -1,40 +1,26 @@ -import { wLogger } from '@tosu/common'; - -import { HttpServer, sendJson } from '../index'; +import { HttpServer } from '../index'; import { directoryWalker } from '../utils/directories'; export default function buildV1Api(app: HttpServer) { app.route(/^\/Songs\/(?.*)/, 'GET', (req, res) => { - try { - const url = req.pathname || '/'; - - const osuInstance: any = req.instanceManager.getInstance( - req.instanceManager.focusedClient - ); - if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - const global = osuInstance.get('global'); - if (global.songsFolder === '') { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - directoryWalker({ - res, - baseUrl: url, - pathname: req.params.filePath, - folderPath: global.songsFolder - }); - } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + const url = req.pathname || '/'; + const osuInstance: any = req.instanceManager.getInstance( + req.instanceManager.focusedClient + ); + if (!osuInstance) { + throw new Error('osu is not ready/running'); + } - return sendJson(res, { - error: (error as any).message - }); + const global = osuInstance.get('global'); + if (global.songsFolder === '') { + throw new Error('osu is not ready/running'); } + + directoryWalker({ + res, + baseUrl: url, + pathname: req.params.filePath, + folderPath: global.songsFolder + }); }); } diff --git a/packages/server/router/v2.ts b/packages/server/router/v2.ts index 940c35ec..827e2b92 100644 --- a/packages/server/router/v2.ts +++ b/packages/server/router/v2.ts @@ -1,4 +1,3 @@ -import { wLogger } from '@tosu/common'; import path from 'path'; import { HttpServer, sendJson } from '../index'; @@ -11,12 +10,11 @@ export default function buildV2Api(app: HttpServer) { req.instanceManager.focusedClient ); if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); + throw new Error('osu is not ready/running'); } const json = osuInstance.getStateV2(req.instanceManager); - sendJson(res, json); + return sendJson(res, json); }); app.route('/json/v2/precise', 'GET', (req, res) => { @@ -24,12 +22,11 @@ export default function buildV2Api(app: HttpServer) { req.instanceManager.focusedClient ); if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); + throw new Error('osu is not ready/running'); } const json = osuInstance.getPreciseData(req.instanceManager); - sendJson(res, json); + return sendJson(res, json); }); app.route( @@ -39,77 +36,50 @@ export default function buildV2Api(app: HttpServer) { ); app.route(/^\/files\/beatmap\/(?.*)/, 'GET', (req, res) => { - try { - const url = req.pathname || '/'; - - const osuInstance: any = req.instanceManager.getInstance( - req.instanceManager.focusedClient - ); - if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - const global = osuInstance.get('global'); - if (global.songsFolder === '') { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - directoryWalker({ - res, - baseUrl: url, - pathname: req.params.filePath, - folderPath: global.songsFolder - }); - } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); - - return sendJson(res, { - error: (error as any).message - }); + const url = req.pathname || '/'; + const osuInstance: any = req.instanceManager.getInstance( + req.instanceManager.focusedClient + ); + if (!osuInstance) { + throw new Error('osu is not ready/running'); } + const global = osuInstance.get('global'); + if (global.songsFolder === '') { + throw new Error('osu is not ready/running'); + } + + directoryWalker({ + res, + baseUrl: url, + pathname: req.params.filePath, + folderPath: global.songsFolder + }); }); app.route(/^\/files\/skin\/(?.*)/, 'GET', (req, res) => { - try { - const url = req.pathname || '/'; + const url = req.pathname || '/'; - const osuInstance: any = req.instanceManager.getInstance( - req.instanceManager.focusedClient - ); - if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - const global = osuInstance.get('global'); - if ( - (global.gameFolder === '' && global.skinFolder === '') || - (global.gameFolder == null && global.skinFolder == null) - ) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - const folder = path.join( - global.gameFolder, - 'Skins', - global.skinFolder - ); - directoryWalker({ - res, - baseUrl: url, - pathname: req.params.filePath, - folderPath: folder - }); - } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + const osuInstance: any = req.instanceManager.getInstance( + req.instanceManager.focusedClient + ); + if (!osuInstance) { + throw new Error('osu is not ready/running'); + } - return sendJson(res, { - error: (error as any).message - }); + const global = osuInstance.get('global'); + if ( + (global.gameFolder === '' && global.skinFolder === '') || + (global.gameFolder == null && global.skinFolder == null) + ) { + throw new Error('osu is not ready/running'); } + + const folder = path.join(global.gameFolder, 'Skins', global.skinFolder); + directoryWalker({ + res, + baseUrl: url, + pathname: req.params.filePath, + folderPath: folder + }); }); } diff --git a/packages/server/scripts/beatmapFile.ts b/packages/server/scripts/beatmapFile.ts index 21433998..16215752 100644 --- a/packages/server/scripts/beatmapFile.ts +++ b/packages/server/scripts/beatmapFile.ts @@ -1,4 +1,3 @@ -import { wLogger } from '@tosu/common'; import { ServerResponse } from 'http'; import path from 'path'; @@ -11,51 +10,40 @@ export function beatmapFileShortcut( res: ServerResponse, beatmapFileType: 'audio' | 'background' | 'file' ) { - try { - const url = req.pathname || '/'; + const url = req.pathname || '/'; - const osuInstance: any = req.instanceManager.getInstance( - req.instanceManager.focusedClient - ); - if (!osuInstance) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - const { global, menu } = osuInstance.getServices(['global', 'menu']); - if ( - (global.gameFolder === '' && global.skinFolder === '') || - (global.gameFolder == null && global.skinFolder == null) - ) { - res.statusCode = 500; - return sendJson(res, { error: 'not_ready' }); - } - - const folder = path.join(global.songsFolder, menu.folder || ''); - let fileName = ''; + const osuInstance: any = req.instanceManager.getInstance( + req.instanceManager.focusedClient + ); + if (!osuInstance) { + throw new Error('osu is not ready/running'); + } - if (beatmapFileType === 'audio') fileName = menu.audioFilename; - else if (beatmapFileType === 'background') - fileName = menu.backgroundFilename; - else if (beatmapFileType === 'file') fileName = menu.filename; - else { - return sendJson(res, { - error: 'Unknown file type' - }); - } + const { global, menu } = osuInstance.getServices(['global', 'menu']); + if ( + (global.gameFolder === '' && global.skinFolder === '') || + (global.gameFolder == null && global.skinFolder == null) + ) { + throw new Error('osu is not ready/running'); + } - directoryWalker({ - res, - baseUrl: url, - pathname: fileName || '', - folderPath: folder - }); - } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + const folder = path.join(global.songsFolder, menu.folder || ''); + let fileName = ''; + if (beatmapFileType === 'audio') fileName = menu.audioFilename; + else if (beatmapFileType === 'background') + fileName = menu.backgroundFilename; + else if (beatmapFileType === 'file') fileName = menu.filename; + else { return sendJson(res, { - error: (error as any).message + error: 'Unknown file type' }); } + + directoryWalker({ + res, + baseUrl: url, + pathname: fileName || '', + folderPath: folder + }); } diff --git a/packages/server/utils/commands.ts b/packages/server/utils/commands.ts index 68d7a36d..6b981f43 100644 --- a/packages/server/utils/commands.ts +++ b/packages/server/utils/commands.ts @@ -5,7 +5,7 @@ import { parseCounterSettings } from './parseSettings'; import { ModifiedWebsocket } from './socket'; export function handleSocketCommands(data: string, socket: ModifiedWebsocket) { - wLogger.debug(`WS_COMMANDS >>>`, data); + wLogger.debug('[ws]', `commands`, data); if (!data.includes(':')) { return; } @@ -49,7 +49,7 @@ export function handleSocketCommands(data: string, socket: ModifiedWebsocket) { ); if (result instanceof Error) { message = { - error: result.name + error: result.message }; break; } @@ -57,10 +57,12 @@ export function handleSocketCommands(data: string, socket: ModifiedWebsocket) { message = result.values; } catch (exc) { wLogger.error( - `WS_COMMANDS(getSettings) >>>`, - (exc as any).message + '[ws]', + `commands`, + command, + (exc as Error).message ); - wLogger.debug(exc); + wLogger.debug('[ws]', `commands`, command, exc); } break; @@ -69,8 +71,13 @@ export function handleSocketCommands(data: string, socket: ModifiedWebsocket) { case 'applyFilters': { const json = JsonSafeParse(payload, new Error('Broken json')); if (json instanceof Error) { - wLogger.error(`applyFilter >>>`, (json as any).message); - wLogger.debug(json); + wLogger.error( + '[ws]', + `commands`, + command, + (json as Error).message + ); + wLogger.debug('[ws]', `commands`, command, json); return; } @@ -87,10 +94,12 @@ export function handleSocketCommands(data: string, socket: ModifiedWebsocket) { return; } catch (exc) { wLogger.error( - `WS_COMMANDS(applyFilter) >>>`, - (exc as any).message + '[ws]', + `commands`, + command, + (exc as Error).message ); - wLogger.debug(exc); + wLogger.debug('[ws]', `commands`, command, exc); } } } @@ -103,7 +112,7 @@ export function handleSocketCommands(data: string, socket: ModifiedWebsocket) { }) ); } catch (exc) { - wLogger.error(`WS_COMMANDS(sending) >>>`, (exc as any).message); - wLogger.debug(exc); + wLogger.error('[ws]', `commands-send`, (exc as Error).message); + wLogger.debug('[ws]', `commands-send`, exc); } } diff --git a/packages/server/utils/counters.ts b/packages/server/utils/counters.ts index 3c03178d..5ae1d2c4 100644 --- a/packages/server/utils/counters.ts +++ b/packages/server/utils/counters.ts @@ -317,8 +317,8 @@ function rebuildJSON({ .replace('{GALLERY}', gallery) .replace('{FOOTER}', footer); } catch (error) { - wLogger.error(`rebuild(${item.name})`, (error as any).message); - wLogger.debug(error); + wLogger.error('rebuildJSON', item.name, (error as any).message); + wLogger.debug('rebuildJSON', item.name, error); } } @@ -384,8 +384,9 @@ export function getLocalCounters(): ICounter[] { const array = countersListTXT.map((r) => parseTXT(r)); return array.concat(arrayOfLocal).filter((r) => r.name !== ''); } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + wLogger.error('getLocalCounters', (error as any).message); + wLogger.debug('getLocalCounters', error); + return []; } } @@ -410,7 +411,7 @@ export function buildLocalCounters(res: http.ServerResponse, query?: string) { 'utf8', (err, content) => { if (err) { - wLogger.debug(err); + wLogger.debug('buildLocalCounters', 'homepage read', err); res.writeHead(404, { 'Content-Type': 'text/html' }); @@ -486,8 +487,8 @@ export async function buildExternalCounters( totalLocal = exists.length; totalAvailable = json.length; } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + wLogger.error('buildExternalCounters', (error as any).message); + wLogger.debug('buildExternalCounters', error); if (query != null) { res.writeHead(200, { @@ -504,10 +505,8 @@ export async function buildExternalCounters( 'utf8', (err, content) => { if (err) { - wLogger.debug(err); - res.writeHead(404, { - 'Content-Type': 'text/html' - }); + wLogger.debug('buildExternalCounters', 'homepage read', err); + res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('page not found'); return; @@ -758,10 +757,8 @@ export function buildSettings(res: http.ServerResponse) { 'utf8', (err, content) => { if (err) { - wLogger.debug(err); - res.writeHead(404, { - 'Content-Type': 'text/html' - }); + wLogger.debug('buildSettings', 'homepage read', err); + res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('page not found'); return; @@ -803,10 +800,8 @@ export function buildInstructionLocal(res: http.ServerResponse) { 'utf8', (err, content) => { if (err) { - wLogger.debug(err); - res.writeHead(404, { - 'Content-Type': 'text/html' - }); + wLogger.debug('buildInstructionLocal', 'homepage read', err); + res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('page not found'); return; diff --git a/packages/server/utils/directories.ts b/packages/server/utils/directories.ts index 5d0e9d9c..42198815 100644 --- a/packages/server/utils/directories.ts +++ b/packages/server/utils/directories.ts @@ -147,8 +147,8 @@ export function addCounterMetadata(html: string, filePath: string) { return html; } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + wLogger.error('addCounterMetadata', (error as any).message); + wLogger.debug('addCounterMetadata', error); return ''; } diff --git a/packages/server/utils/http.ts b/packages/server/utils/http.ts index 6a551d93..9e149c95 100644 --- a/packages/server/utils/http.ts +++ b/packages/server/utils/http.ts @@ -2,6 +2,8 @@ import { config, wLogger } from '@tosu/common'; import { exec } from 'child_process'; import http, { IncomingMessage, ServerResponse } from 'http'; +import { sendJson } from './index'; + export interface ExtendedIncomingMessage extends IncomingMessage { instanceManager: any; body: string; @@ -41,12 +43,12 @@ export class HttpServer { this.server.on('error', (err) => { if (err.message.includes('getaddrinfo')) { - wLogger.warn('Incorrect server ip or url'); + wLogger.warn('server', 'Incorrect server ip or url'); return; } - wLogger.error(`[server] ${err.message}`); - wLogger.debug(err); + wLogger.error('[server]', err.message); + wLogger.debug('[server]', err); }); } @@ -82,15 +84,18 @@ export class HttpServer { let body = ''; res.on('finish', () => { - const finishTime = performance.now(); + const elapsedTime = (performance.now() - startTime).toFixed(2); wLogger.debug( - `[${(finishTime - startTime).toFixed(2)}ms] ${req.method} ${ - res.statusCode - } ${res.getHeader('content-type')} ${req.url}` + `[request]`, + `${elapsedTime}ms`, + req.method, + res.statusCode, + res.getHeader('content-type'), + req.url ); }); - const next = (index) => { + const next = (index: number) => { if (index < this.middlewares.length) { const savedIndex = index; const middleware = this.middlewares[index++]; @@ -99,8 +104,13 @@ export class HttpServer { middleware(req, res, () => { next(savedIndex + 1); }); - } catch (error) { - wLogger.error('middleware error', error); + } catch (exc) { + wLogger.error( + '[server]', + 'middleware', + (exc as Error).message + ); + wLogger.debug('[server]', 'middleware', exc); } return; } @@ -168,7 +178,20 @@ export class HttpServer { } if (!routeExists) continue; - return route.handler(req, res); + try { + return route.handler(req, res); + } catch (exc) { + const message = + typeof exc === 'string' ? exc : (exc as Error).message; + + res.statusCode = 500; + res.statusMessage = message; + + wLogger.error(parsedURL.pathname, message); + wLogger.debug(parsedURL.pathname, exc); + + return sendJson(res, { error: message }); + } } res.statusCode = 404; @@ -178,7 +201,10 @@ export class HttpServer { listen(port: number, hostname: string) { this.server.listen(port, hostname, () => { const ip = hostname === '0.0.0.0' ? 'localhost' : hostname; - wLogger.info(`Web server started on http://${ip}:${port}`); + wLogger.info( + '[server]', + `Dashboard started on http://${ip}:${port}` + ); if (config.openDashboardOnStartup === true) { const command = diff --git a/packages/server/utils/parseSettings.ts b/packages/server/utils/parseSettings.ts index a92391a6..9e7bf22c 100644 --- a/packages/server/utils/parseSettings.ts +++ b/packages/server/utils/parseSettings.ts @@ -31,7 +31,6 @@ export function parseCounterSettings( try { // copy legacy settings instead of moving/renaming, because some could have their static folder on other drive if (fs.existsSync(legacySettingsValuesPath)) { - // wLogger.warn('counter-settings', 'copied legacy settings to new folder', decodeURI(folderName)); fs.copyFileSync(legacySettingsValuesPath, settingsValuesPath); fs.renameSync( legacySettingsValuesPath, @@ -205,11 +204,8 @@ export function parseCounterSettings( return new Error('Undefined action to parse counter settings'); } catch (exc) { - wLogger.error(`parseCounterSettings: ${(exc as any).message}`); - wLogger.debug(exc, { - staticPath, - folderName - }); + wLogger.error('parseCounterSettings', (exc as any).message); + wLogger.debug('parseCounterSettings', { staticPath, folderName }, exc); return new Error(`parseCounterSettings Error: ${(exc as any).message}`); } diff --git a/packages/server/utils/socket.ts b/packages/server/utils/socket.ts index 2483ca3b..f20fe932 100644 --- a/packages/server/utils/socket.ts +++ b/packages/server/utils/socket.ts @@ -77,22 +77,18 @@ export class Websocket { ws.originAddress = request.headers.origin || ''; ws.remoteAddress = `${request.socket.remoteAddress}:${request.socket.remotePort}`; - wLogger.debug(`WS(CONNECTED) >>> ${ws.id}`); + wLogger.debug('[ws]', 'connected', ws.id); ws.on('close', (reason, description) => { this.clients.delete(ws.id); - wLogger.debug( - `WS(CLOSED) >>> ${ws.id}: ${reason} [${description}]` - ); + wLogger.debug('[ws]', 'closed', ws.id, reason, description); }); ws.on('error', (reason, description) => { this.clients.delete(ws.id); - wLogger.debug( - `WS(ERROR) >>> ${ws.id}: ${reason} [${description}]` - ); + wLogger.debug('[ws]', 'error', ws.id, reason, description); }); if (typeof this.onMessageCallback === 'function') { @@ -153,8 +149,8 @@ export class Websocket { client.send(message); }); } catch (error) { - wLogger.error((error as any).message); - wLogger.debug(error); + wLogger.error('[ws]', 'loop', (error as any).message); + wLogger.debug('[ws]', 'loop', error); } }, config[this.pollRateFieldName]); } diff --git a/packages/tosu/src/instances/index.ts b/packages/tosu/src/instances/index.ts index 4ba2dcbc..4cb43153 100644 --- a/packages/tosu/src/instances/index.ts +++ b/packages/tosu/src/instances/index.ts @@ -131,8 +131,20 @@ export abstract class AbstractInstance { } return true; - } catch (error) { - wLogger.debug(`MP(resolvePatterns)[${this.pid}]`, error); + } catch (exc) { + wLogger.error( + ClientType[this.client], + this.pid, + 'resolvePatterns', + (exc as Error).message + ); + wLogger.debug( + ClientType[this.client], + this.pid, + 'resolvePatterns', + exc + ); + return false; } } @@ -148,19 +160,28 @@ export abstract class AbstractInstance { throw new Error('Memory resolve failed'); } - wLogger.debug( - `[${this.pid} ${this.client}] Took ${(performance.now() - s1).toFixed(2)} ms to scan patterns` - ); - + const elapsedTime = `${(performance.now() - s1).toFixed(2)}ms`; wLogger.info( - `[${this.pid} ${this.client}] ALL PATTERNS ARE RESOLVED, STARTING WATCHING THE DATA` + ClientType[this.client], + this.pid, + `All patterns resolved within ${elapsedTime}` ); + this.isReady = true; } catch (exc) { wLogger.error( - `[${this.pid} ${this.client}] PATTERN SCANNING FAILED, TRYING ONE MORE TIME...` + ClientType[this.client], + this.pid, + 'Pattern scanning failed, Trying one more time...', + (exc as Error).message ); - wLogger.debug(exc); + wLogger.debug( + ClientType[this.client], + this.pid, + 'Pattern scanning failed, Trying one more time...', + exc + ); + this.emitter.emit('onResolveFailed', this.pid); return; } @@ -179,7 +200,18 @@ export abstract class AbstractInstance { const result = await injectGameOverlay(this.process, this.bitness); this.isGameOverlayInjected = result === true; } catch (exc) { - wLogger.debug(`instance(injectGameOverlay)`, exc); + wLogger.error( + ClientType[this.client], + this.pid, + 'injectGameOverlay', + (exc as Error).message + ); + wLogger.debug( + ClientType[this.client], + this.pid, + 'injectGameOverlay', + exc + ); } } @@ -197,11 +229,14 @@ export abstract class AbstractInstance { if (this.isDestroyed === true) return; if (!Process.isProcessExist(this.process.handle)) { - this.isDestroyed = true; wLogger.warn( - `OI(watchProcessHealth) osu!.exe at ${this.pid} got destroyed ` + ClientType[this.client], + this.pid, + 'osu!.exe got destroyed' ); + this.emitter.emit('onDestroy', this.pid); + this.isDestroyed = true; } setTimeout(this.watchProcessHealth, config.pollRate); diff --git a/packages/tosu/src/instances/lazerInstance.ts b/packages/tosu/src/instances/lazerInstance.ts index d9fafc71..5fcf461b 100644 --- a/packages/tosu/src/instances/lazerInstance.ts +++ b/packages/tosu/src/instances/lazerInstance.ts @@ -1,4 +1,11 @@ -import { Bitness, GameState, config, sleep, wLogger } from '@tosu/common'; +import { + Bitness, + ClientType, + GameState, + config, + sleep, + wLogger +} from '@tosu/common'; import { LazerMemory } from '@/memory/lazer'; import { Gameplay } from '@/states/gameplay'; @@ -18,7 +25,7 @@ export class LazerInstance extends AbstractInstance { } async regularDataLoop(): Promise { - wLogger.debug('SM(lazer:startDataLoop) starting'); + wLogger.debug(ClientType[this.client], this.pid, 'regularDataLoop'); const { global, menu, beatmapPP, gameplay, resultScreen, user } = this.getServices([ @@ -168,10 +175,19 @@ export class LazerInstance extends AbstractInstance { await sleep(config.pollRate); } catch (exc) { - wLogger.debug(`SM(startDataLoop)[${this.pid}]`, exc); wLogger.error( - `SM(startDataLoop)[${this.pid}]`, - (exc as any).message + ClientType[this.client], + this.pid, + 'regularDataLoop', + 'error within a loop', + (exc as Error).message + ); + wLogger.debug( + ClientType[this.client], + this.pid, + 'regularDataLoop', + 'error within a loop', + exc ); } } diff --git a/packages/tosu/src/instances/manager.ts b/packages/tosu/src/instances/manager.ts index 5058a5ba..128cfe31 100644 --- a/packages/tosu/src/instances/manager.ts +++ b/packages/tosu/src/instances/manager.ts @@ -117,8 +117,8 @@ export class InstanceManager { osuInstance.start(); } } catch (exc) { - wLogger.error('InstanceManager', (exc as any).message); - wLogger.debug(exc); + wLogger.error('[manager]', 'handleProcesses', (exc as any).message); + wLogger.debug('[manager]', 'handleProcesses', exc); } } diff --git a/packages/tosu/src/instances/osuInstance.ts b/packages/tosu/src/instances/osuInstance.ts index 5a5f9186..56b68d55 100644 --- a/packages/tosu/src/instances/osuInstance.ts +++ b/packages/tosu/src/instances/osuInstance.ts @@ -1,4 +1,11 @@ -import { Bitness, GameState, config, sleep, wLogger } from '@tosu/common'; +import { + Bitness, + ClientType, + GameState, + config, + sleep, + wLogger +} from '@tosu/common'; import fs from 'fs'; import path from 'path'; @@ -18,210 +25,196 @@ export class OsuInstance extends AbstractInstance { } async regularDataLoop() { - try { - wLogger.debug('SM(startDataLoop) starting'); - - const { - global, - menu, - bassDensity, - beatmapPP, - gameplay, - resultScreen, - settings, - tourneyManager, - user - } = this.getServices([ - 'global', - 'menu', - 'bassDensity', - 'beatmapPP', - 'gameplay', - 'resultScreen', - 'settings', - 'tourneyManager', - 'user' - ]); - - while (!this.isDestroyed) { - try { - global.updateState(); - const menuUpdate = menu.updateState(); - if (menuUpdate === 'not-ready') { - await sleep(config.pollRate); - continue; - } + wLogger.debug(ClientType[this.client], this.pid, 'regularDataLoop'); + + const { + global, + menu, + bassDensity, + beatmapPP, + gameplay, + resultScreen, + settings, + tourneyManager, + user + } = this.getServices([ + 'global', + 'menu', + 'bassDensity', + 'beatmapPP', + 'gameplay', + 'resultScreen', + 'settings', + 'tourneyManager', + 'user' + ]); + + while (!this.isDestroyed) { + try { + global.updateState(); + const menuUpdate = menu.updateState(); + if (menuUpdate === 'not-ready') continue; + + // osu! calculates audioTrack length a little bit after updating menu, sooo.. lets this thing run regardless of menu updating + if (menu.folder !== '' && menu.folder !== null) { + menu.updateMP3Length(); + } - // osu! calculates audioTrack length a little bit after updating menu, sooo.. lets this thing run regardless of menu updating - if (menu.folder !== '' && menu.folder !== null) { - menu.updateMP3Length(); + if (!global.gameFolder) { + global.setGameFolder(this.path); + + // condition when user have different BeatmapDirectory in osu! config + if (fs.existsSync(global.memorySongsFolder)) { + global.setSongsFolder(global.memorySongsFolder); + } else { + global.setSongsFolder( + path.join(this.path, global.memorySongsFolder) + ); } + } + + // update important data before doing rest + if (global.status === GameState.resultScreen) { + const resultUpdate = resultScreen.updateState(); + if (resultUpdate === 'not-ready') continue; + } + + settings.updateState(); + + const currentMods = + global.status === GameState.play + ? gameplay.mods + : global.status === GameState.resultScreen + ? resultScreen.mods + : global.menuMods; + + const currentMode = + global.status === GameState.play + ? gameplay.mode + : global.status === GameState.resultScreen + ? resultScreen.mode + : menu.gamemode; + + const currentState = `${menu.checksum}:${currentMode}:${currentMods.checksum}`; + const updateGraph = + this.previousState !== currentState || + this.previousMP3Length !== menu.mp3Length; + if ( + menu.filename?.endsWith('.osu') && + global.gameFolder && + this.previousState !== currentState + ) { + const metadataUpdate = beatmapPP.updateMapMetadata( + currentMods, + currentMode + ); + if (metadataUpdate === 'not-ready') continue; + + beatmapPP.updateGraph(currentMods.array); + this.previousState = currentState; + } + + if ( + menu.filename?.endsWith('.osu') && + global.gameFolder && + updateGraph + ) { + beatmapPP.updateGraph(currentMods.array); + this.previousMP3Length = menu.mp3Length; + } + + beatmapPP.updateRealTimeBPM(global.playTime, currentMods.rate); + + switch (global.status) { + case GameState.menu: + bassDensity.updateState(); + break; + + case GameState.edit: + if (this.previousTime === global.playTime) break; - if (!global.gameFolder) { - global.setGameFolder(this.path); + this.previousTime = global.playTime; + beatmapPP.updateEditorPP(); + break; - // condition when user have different BeatmapDirectory in osu! config - if (fs.existsSync(global.memorySongsFolder)) { - global.setSongsFolder(global.memorySongsFolder); - } else { - global.setSongsFolder( - path.join(this.path, global.memorySongsFolder) - ); + case GameState.selectEdit: + case GameState.selectPlay: + // Reset Gameplay/ResultScreen data on joining to songSelect + if (!gameplay.isDefaultState) { + gameplay.init(undefined, '4,5'); + resultScreen.init(); + beatmapPP.resetAttributes(); } - } - // update important data before doing rest - if (global.status === GameState.resultScreen) { - const resultUpdate = resultScreen.updateState(); - if (resultUpdate === 'not-ready') { - await sleep(config.pollRate); - continue; + // Reset ResultScreen if we in song select + if (resultScreen.playerName) { + resultScreen.init(); } - } + break; - settings.updateState(); - - const currentMods = - global.status === GameState.play - ? gameplay.mods - : global.status === GameState.resultScreen - ? resultScreen.mods - : global.menuMods; - - const currentMode = - global.status === GameState.play - ? gameplay.mode - : global.status === GameState.resultScreen - ? resultScreen.mode - : menu.gamemode; - - const currentState = `${menu.checksum}:${currentMode}:${currentMods.checksum}`; - const updateGraph = - this.previousState !== currentState || - this.previousMP3Length !== menu.mp3Length; - if ( - menu.filename?.endsWith('.osu') && - global.gameFolder && - this.previousState !== currentState - ) { - const metadataUpdate = beatmapPP.updateMapMetadata( - currentMods, - currentMode - ); - if (metadataUpdate === 'not-ready') { - await sleep(config.pollRate); - continue; + case GameState.play: + // Reset gameplay data on retry + if (this.previousTime > global.playTime) { + gameplay.init(true); + beatmapPP.resetAttributes(); } - beatmapPP.updateGraph(currentMods.array); - this.previousState = currentState; - } + // reset before first object + if (global.playTime < beatmapPP.timings.firstObj) { + gameplay.resetQuick(); + } - if ( - menu.filename?.endsWith('.osu') && - global.gameFolder && - updateGraph - ) { - beatmapPP.updateGraph(currentMods.array); - this.previousMP3Length = menu.mp3Length; - } + this.previousTime = global.playTime; - beatmapPP.updateRealTimeBPM( - global.playTime, - currentMods.rate - ); + gameplay.updateState(); + break; - switch (global.status) { - case GameState.menu: - bassDensity.updateState(); - break; - - case GameState.edit: - if (this.previousTime === global.playTime) break; - - this.previousTime = global.playTime; - beatmapPP.updateEditorPP(); - break; - - case GameState.selectEdit: - case GameState.selectPlay: - // Reset Gameplay/ResultScreen data on joining to songSelect - if (!gameplay.isDefaultState) { - gameplay.init(undefined, '4,5'); - resultScreen.init(); - beatmapPP.resetAttributes(); - } - - // Reset ResultScreen if we in song select - if (resultScreen.playerName) { - resultScreen.init(); - } - break; - - case GameState.play: - // Reset gameplay data on retry - if (this.previousTime > global.playTime) { - gameplay.init(true); - beatmapPP.resetAttributes(); - } - - // reset before first object - if (global.playTime < beatmapPP.timings.firstObj) { - gameplay.resetQuick(); - } - - this.previousTime = global.playTime; - - gameplay.updateState(); - break; - - case GameState.resultScreen: - resultScreen.updatePerformance(); - break; - - case GameState.tourney: - if (!this.isTourneyManager) { - this.isTourneyManager = true; - } - await tourneyManager.updateState(); - break; - - // do not spam reset on multiplayer and direct - case GameState.lobby: - case GameState.matchSetup: - case GameState.onlineSelection: - break; - - default: - gameplay.init( - undefined, - `default-${global.status}` - ); - resultScreen.init(); - break; - } + case GameState.resultScreen: + resultScreen.updatePerformance(); + break; - if (this.isTourneySpectator) { - tourneyManager.updateUser(); - } + case GameState.tourney: + if (!this.isTourneyManager) { + this.isTourneyManager = true; + } + tourneyManager.updateState(); + break; + + // do not spam reset on multiplayer and direct + case GameState.lobby: + case GameState.matchSetup: + case GameState.onlineSelection: + break; + + default: + gameplay.init(undefined, `default-${global.status}`); + resultScreen.init(); + break; + } - user.updateState(); - } catch (exc) { - wLogger.error( - `SM(startDataLoop)[${this.pid}]`, - 'error happend while another loop executed' - ); - wLogger.debug(exc); + if (this.isTourneySpectator) { + tourneyManager.updateUser(); } + user.updateState(); + } catch (exc) { + wLogger.error( + ClientType[this.client], + this.pid, + 'regularDataLoop', + 'error within a loop', + (exc as Error).message + ); + wLogger.debug( + ClientType[this.client], + this.pid, + 'regularDataLoop', + 'error within a loop', + exc + ); + } finally { await sleep(config.pollRate); } - } catch (exc) { - wLogger.debug(`SM(startDataLoop)[${this.pid}]`, exc); - wLogger.error( - `SM(startDataLoop)[${this.pid}]`, - (exc as any).message - ); } } diff --git a/packages/tosu/src/memory/index.ts b/packages/tosu/src/memory/index.ts index 04ff4626..f15d1771 100644 --- a/packages/tosu/src/memory/index.ts +++ b/packages/tosu/src/memory/index.ts @@ -1,4 +1,4 @@ -import { wLogger } from '@tosu/common'; +import { ClientType, wLogger } from '@tosu/common'; import { platform } from 'process'; import { Process } from 'tsprocess/dist/process'; @@ -76,9 +76,10 @@ export abstract class AbstractMemory> { checkIsBasesValid(): boolean { Object.entries(this.patterns).map((entry) => wLogger.debug( - `SM(checkIsBasesValid)[${this.pid}] ${entry[0]}: ${entry[1] - .toString(16) - .toUpperCase()}` + ClientType[this.game.client], + this.pid, + 'checkIsBasesValid', + `${entry[0]}: ${entry[1].toString(16).toUpperCase()}` ) ); return !Object.values(this.patterns).some((base) => base === 0); diff --git a/packages/tosu/src/memory/lazer.ts b/packages/tosu/src/memory/lazer.ts index e429ce4e..bb47d2f8 100644 --- a/packages/tosu/src/memory/lazer.ts +++ b/packages/tosu/src/memory/lazer.ts @@ -100,10 +100,10 @@ export class LazerMemory extends AbstractMemory { ); wLogger.debug( - 'GameBase address - old:', - oldAddress?.toString(16), - 'new:', - this.gameBaseAddress.toString(16) + 'lazer', + this.pid, + 'updateGameBaseAddress', + `${oldAddress?.toString(16)} => ${this.gameBaseAddress.toString(16)}` ); } @@ -129,7 +129,7 @@ export class LazerMemory extends AbstractMemory { // Check if gamebase instance is valid if (!this.checkIfGameBase(this.gameBaseAddress)) { - wLogger.debug('GameBase has been reset'); + wLogger.debug('lazer', this.pid, 'GameBase has been reset'); const scanPattern = this.scanPatterns.spectatorClient; this.setPattern( @@ -358,7 +358,12 @@ export class LazerMemory extends AbstractMemory { private initModMapping(gamemode: number) { if (!ModsCategories[gamemode]) { - wLogger.warn(`Unknown mods gamemode`, gamemode); + wLogger.warn( + 'lazer', + this.pid, + 'initModMapping', + `Unknown mods gamemode: ${gamemode}` + ); return; } @@ -1743,8 +1748,15 @@ export class LazerMemory extends AbstractMemory { if (!this.modMappings.has(gamemode.toString())) { try { this.initModMapping(gamemode); - } catch (error) { - wLogger.debug('lazer-global', error); + } catch (exc) { + wLogger.error( + 'lazer', + this.pid, + 'global', + 'mods', + (exc as Error).message + ); + wLogger.debug('lazer', this.pid, 'global', 'mods', exc); } } diff --git a/packages/tosu/src/memory/stable.ts b/packages/tosu/src/memory/stable.ts index 4df8a547..03a59e01 100644 --- a/packages/tosu/src/memory/stable.ts +++ b/packages/tosu/src/memory/stable.ts @@ -149,10 +149,7 @@ export class StableMemory extends AbstractMemory { this.process.readInt(this.getPattern('rulesetsAddr') - 0xb) + 0x4 ); - if (rulesetAddr === 0) { - wLogger.debug('BDD(updateState) rulesetAddr is zero'); - return null; - } + if (rulesetAddr === 0) return 'rulesetAddr is zero'; // [Ruleset + 0x44] + 0x10 const audioVelocityBase = this.process.readInt( @@ -160,12 +157,8 @@ export class StableMemory extends AbstractMemory { ); const bassDensityLength = this.process.readInt(audioVelocityBase + 0x4); - if (bassDensityLength < 40) { - wLogger.debug( - 'BDD(updateState) bassDensity length less than 40 (basically it have 1024 values)' - ); - return null; - } + if (bassDensityLength < 40) + return 'bassDensity length less than 40 (basically it have 1024 values)'; const result: number[] = []; for (let i = 0; i < 40; i++) { @@ -264,7 +257,7 @@ export class StableMemory extends AbstractMemory { result.push(i); } catch (exc) { - wLogger.debug(exc); + wLogger.debug('stable', this.pid, 'configOffsets', exc); } } @@ -290,7 +283,7 @@ export class StableMemory extends AbstractMemory { result.push(i); } catch (exc) { - wLogger.debug(exc); + wLogger.debug('stable', this.pid, 'bindingsOffsets', exc); } } @@ -382,7 +375,6 @@ export class StableMemory extends AbstractMemory { const resultScreenBase = this.process.readInt(rulesetAddr + 0x38); if (resultScreenBase === 0) { - wLogger.debug('RSD(updateState) '); return 'resultScreenBase is zero'; } @@ -781,9 +773,7 @@ export class StableMemory extends AbstractMemory { const baseAddr = this.getPattern('baseAddr'); const beatmapAddr = this.process.readPointer(baseAddr - 0xc); - if (beatmapAddr === 0) { - return 'beatmapAddr is 0'; - } + if (beatmapAddr === 0) return 'beatmapAddr is 0'; const gamemode = this.process.readPointer(baseAddr - 0x33); const checksum = this.process.readSharpString( @@ -887,9 +877,7 @@ export class StableMemory extends AbstractMemory { const rulesetAddr = this.process.readInt( this.process.readInt(address - 0xb) + 0x4 ); - if (rulesetAddr === 0) { - return 'RulesetAddr is 0'; - } + if (rulesetAddr === 0) return 'RulesetAddr is 0'; const teamLeftBase = this.process.readInt(rulesetAddr + 0x1c); const teamRightBase = this.process.readInt(rulesetAddr + 0x20); @@ -983,10 +971,10 @@ export class StableMemory extends AbstractMemory { continue; } - for (let i = 0; i < messagesSize; i++) { + for (let m = 0; m < messagesSize; m++) { try { const current = - messagesItems + this.getLeaderStart() + 0x4 * i; + messagesItems + this.getLeaderStart() + 0x4 * m; const currentItem = this.process.readInt(current); // [Base + 0x4] @@ -1016,13 +1004,25 @@ export class StableMemory extends AbstractMemory { content }); } catch (exc) { - wLogger.debug(exc); + wLogger.debug( + 'stable', + this.pid, + 'tourneyChat', + `message loop ${m}`, + exc + ); } } return result; } catch (exc) { - wLogger.debug(exc); + wLogger.debug( + 'stable', + this.pid, + 'tourneyChat', + `chat loop ${i}`, + exc + ); } } @@ -1037,9 +1037,7 @@ export class StableMemory extends AbstractMemory { const address = this.process.readPointer( this.getPattern('spectatingUserPtr') ); - if (!address) { - return 'Slot is not equiped'; - } + if (!address) return 'Slot is not equiped'; const userAccuracy = this.process.readDouble(address + 0x4); const userRankedScore = this.process.readLong(address + 0xc); diff --git a/packages/tosu/src/memory/types.ts b/packages/tosu/src/memory/types.ts index 9fdbeadb..0a04fb53 100644 --- a/packages/tosu/src/memory/types.ts +++ b/packages/tosu/src/memory/types.ts @@ -10,7 +10,7 @@ export type ScanPatterns = { }; }; -export type IAudioVelocityBase = number[] | null; +export type IAudioVelocityBase = number[] | string; export type IUser = | Error diff --git a/packages/tosu/src/states/bassDensity.ts b/packages/tosu/src/states/bassDensity.ts index 919b0212..9762c187 100644 --- a/packages/tosu/src/states/bassDensity.ts +++ b/packages/tosu/src/states/bassDensity.ts @@ -1,4 +1,4 @@ -import { wLogger } from '@tosu/common'; +import { ClientType, wLogger } from '@tosu/common'; import { AbstractState } from '@/states'; @@ -10,7 +10,15 @@ export class BassDensity extends AbstractState { updateState() { try { const audioVelocityBase = this.game.memory.audioVelocityBase(); - if (audioVelocityBase === null) return; + if (typeof audioVelocityBase === 'string') { + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + 'resolvePatterns', + audioVelocityBase + ); + return; + } let bass = 0.0; let currentAudioVelocity = this.currentAudioVelocity; @@ -37,14 +45,22 @@ export class BassDensity extends AbstractState { this.currentAudioVelocity = currentAudioVelocity; this.density = (1 + currentAudioVelocity) * 0.5; - this.resetReportCount('BassDensity(updateState)'); + this.resetReportCount('BassDensity updateState'); } catch (exc) { this.reportError( - 'BassDensity(updateState)', + 'BassDensity updateState', 10, - `BassDensity(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + 'BassDensity updateState', + (exc as Error).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + 'BassDensity updateState', + exc ); - wLogger.debug(exc); } } } diff --git a/packages/tosu/src/states/beatmap.ts b/packages/tosu/src/states/beatmap.ts index 5319762f..70f1774d 100644 --- a/packages/tosu/src/states/beatmap.ts +++ b/packages/tosu/src/states/beatmap.ts @@ -226,19 +226,27 @@ export class BeatmapPP extends AbstractState { }; } catch (exc) { wLogger.error( - `BPPD(updatePPAttributes)-${type}`, - (exc as any).message + ClientType[this.game.client], + this.game.pid, + `beatmapPP updatePPAttributes(${type})`, + (exc as Error).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `beatmapPP updatePPAttributes(${type})`, + exc ); - wLogger.debug(`BPPD(updatePPAttributes)-${type}`, exc); } } updateCurrentAttributes(stars: number, pp: number) { if (this.currAttributes.pp.toFixed(2) !== pp.toFixed(2)) { wLogger.debug( - `BPPD(updateCurrentAttributes) maxPP -> ${this.currAttributes.maxThisPlayPP.toFixed( - 2 - )} pp -> ${pp.toFixed(2)} stars -> ${stars.toFixed(2)}` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateCurrentAttributes`, + `maxPP -> ${this.currAttributes.maxThisPlayPP.toFixed(2)} pp -> ${pp.toFixed(2)} stars -> ${stars.toFixed(2)}` ); } const maxThisPlayPP = Math.max(pp, this.currAttributes.maxThisPlayPP); @@ -288,7 +296,10 @@ export class BeatmapPP extends AbstractState { if (menu.folder === '' && !lazerByPass) { wLogger.debug( - `BPPD(updateMapMetadata) Skip osu! music theme file`, + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `Skip osu! music theme file`, { SongsFolder: global.songsFolder, Folder: menu.folder, @@ -299,11 +310,17 @@ export class BeatmapPP extends AbstractState { } if (!menu.filename) { - wLogger.debug(`BPPD(updateMapMetadata) Skip new map creation`, { - SongsFolder: global.songsFolder, - Folder: menu.folder, - Path: menu.filename - }); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `Skip new map creation`, + { + SongsFolder: global.songsFolder, + Folder: menu.folder, + Path: menu.filename + } + ); return; } @@ -321,7 +338,10 @@ export class BeatmapPP extends AbstractState { } catch (exc) { this.beatmap = undefined; wLogger.debug( - `BPPD(updateMapMetadata) unable to free beatmap`, + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `unable to free beatmap`, exc ); } @@ -332,13 +352,19 @@ export class BeatmapPP extends AbstractState { } catch (exc) { this.performanceAttributes = undefined; wLogger.debug( - `BPPD(updateMapMetadata) unable to free PerformanceAttributes`, + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `unable to free PerformanceAttributes`, exc ); } } catch (error) { wLogger.debug( - `BPPD(updateMapMetadata) Can't get map`, + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `Can't get map`, { mapPath, currentMods: currentMods.array, @@ -356,7 +382,10 @@ export class BeatmapPP extends AbstractState { const beatmapCheckTime = performance.now(); const totalTime = (beatmapCheckTime - startTime).toFixed(2); wLogger.debug( - `BPPD(updateMapMetadata) [${totalTime}ms] Spend on opening beatmap` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `[${totalTime}ms] Spend on opening beatmap` ); const attributes = new rosu.BeatmapAttributesBuilder({ @@ -396,9 +425,10 @@ export class BeatmapPP extends AbstractState { const calculationTime = performance.now(); wLogger.debug( - `BPPD(updateMapMetadata) [${( - calculationTime - beatmapCheckTime - ).toFixed(2)}ms] Spend on attributes & strains calculation` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `[${(calculationTime - beatmapCheckTime).toFixed(2)}ms] Spend on attributes & strains calculation` ); try { @@ -451,29 +481,39 @@ export class BeatmapPP extends AbstractState { this.timingPoints = this.lazerBeatmap.controlPoints.timingPoints; - this.resetReportCount('BPPD(updateMapMetadataTimings)'); + this.resetReportCount('beatmapPP updateMapMetadataTimings'); } catch (exc) { this.reportError( - 'BPPD(updateMapMetadataTimings)', + 'beatmapPP updateMapMetadataTimings', 10, - `BPPD(updateMapMetadataTimings) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + exc ); - wLogger.debug(exc); return; } const beatmapParseTime = performance.now(); wLogger.debug( - `BPPD(updateMapMetadata) [${( - beatmapParseTime - calculationTime - ).toFixed(2)}ms] Spend on parsing beatmap` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `[${(beatmapParseTime - calculationTime).toFixed(2)}ms] Spend on parsing beatmap` ); const endTime = performance.now(); wLogger.debug( - `BPPD(updateMapMetadata) [${(endTime - startTime).toFixed( - 2 - )}ms] Total spent time` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + `[${(endTime - startTime).toFixed(2)}ms] Total spent time` ); this.calculatedMapAttributes = { @@ -505,14 +545,22 @@ export class BeatmapPP extends AbstractState { attributes.free(); - this.resetReportCount('BPPD(updateMapMetadata)'); + this.resetReportCount('beatmapPP updateMapMetadata'); } catch (exc) { this.reportError( - 'BPPD(updateMapMetadata)', + 'beatmapPP updateMapMetadata', 10, - `BPPD(updateMapMetadata) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateMapMetadata`, + exc ); - wLogger.debug(exc); } } @@ -632,7 +680,10 @@ export class BeatmapPP extends AbstractState { const endTIme = performance.now(); wLogger.debug( - `BPPD(updateGraph) [${(endTIme - startTime).toFixed(2)}ms] Spend on processing graph strains` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateGraph`, + `[${(endTIme - startTime).toFixed(2)}ms] Spend on processing graph strains` ); for (let i = 0; i < LEFT_OFFSET; i++) { @@ -660,14 +711,22 @@ export class BeatmapPP extends AbstractState { strains.free(); - this.resetReportCount('BPPD(updateGraph)'); + this.resetReportCount('beatmapPP updateGraph'); } catch (exc) { this.reportError( - 'BPPD(updateGraph)', + 'beatmapPP updateGraph', 10, - `BPPD(updateGraph) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateGraph`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateGraph`, + exc ); - wLogger.debug(exc); } } @@ -689,7 +748,10 @@ export class BeatmapPP extends AbstractState { const beatmapParseTime = performance.now(); const totalTime = (beatmapParseTime - startTime).toFixed(2); wLogger.debug( - `(updateEditorPP) Spend:${totalTime}ms on beatmap parsing` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateEditorPP`, + `${totalTime}ms Spend on beatmap parsing` ); const passedObjects = this.lazerBeatmap.hitObjects.filter( @@ -710,21 +772,30 @@ export class BeatmapPP extends AbstractState { : curPerformance.difficulty.stars; wLogger.debug( - `(updateEditorPP) Spend:${( - calculateTime - beatmapParseTime - ).toFixed(2)}ms on calculating performance` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateEditorPP`, + `${(calculateTime - beatmapParseTime).toFixed(2)}ms Spend on calculating performance` ); curPerformance.free(); - this.resetReportCount('BPPD(updateEditorPP)'); + this.resetReportCount('beatmapPP updateEditorPP'); } catch (exc) { this.reportError( - 'BPPD(updateEditorPP)', + 'beatmapPP updateEditorPP', 10, - `BPPD(updateEditorPP) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateEditorPP`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `beatmapPP updateEditorPP`, + exc ); - wLogger.debug(exc); } } diff --git a/packages/tosu/src/states/gameplay.ts b/packages/tosu/src/states/gameplay.ts index 518ad9af..394c5e44 100644 --- a/packages/tosu/src/states/gameplay.ts +++ b/packages/tosu/src/states/gameplay.ts @@ -76,7 +76,11 @@ export class Gameplay extends AbstractState { } init(isRetry?: boolean, from?: string) { - wLogger.debug(`GD(init) Reset (${isRetry} - ${from})`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay init (${isRetry} - ${from})` + ); this.hitErrors = []; this.maxCombo = 0; @@ -144,7 +148,11 @@ export class Gameplay extends AbstractState { } resetQuick() { - wLogger.debug('GD(resetQuick) Reset'); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay resetQuick` + ); this.previousPassedObjects = 0; this.gradualPerformance = undefined; @@ -156,7 +164,11 @@ export class Gameplay extends AbstractState { return; } - wLogger.debug('GD(resetKeyOverlay) Reset'); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay resetKeyOverlay` + ); this.keyOverlay.K1Pressed = false; this.keyOverlay.K2Pressed = false; @@ -181,7 +193,12 @@ export class Gameplay extends AbstractState { const result = this.game.memory.gameplay(); if (result instanceof Error) throw result; if (typeof result === 'string') { - wLogger.debug(`GD(updateState) ${result}`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateState`, + result + ); return 'not-ready'; } @@ -244,14 +261,22 @@ export class Gameplay extends AbstractState { this.updateStarsAndPerformance(); this.updateLeaderboard(); - this.resetReportCount('GD(updateState)'); + this.resetReportCount('gameplay updateState'); } catch (exc) { this.reportError( - 'GD(updateState)', + 'gameplay updateState', 10, - `GD(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `gameplay updateState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateState`, + exc ); - wLogger.debug(exc); } } @@ -262,7 +287,12 @@ export class Gameplay extends AbstractState { if (typeof result === 'string') { if (result === '') return; - wLogger.debug(`GD(updateKeyOverlay)`, result); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateKeyOverlay`, + result + ); return 'not-ready'; } @@ -288,18 +318,31 @@ export class Gameplay extends AbstractState { const keysLine = `${this.keyOverlay.K1Count}:${this.keyOverlay.K2Count}:${this.keyOverlay.M1Count}:${this.keyOverlay.M2Count}`; if (this.cachedkeys !== keysLine) { - wLogger.debug(`GD(updateKeyOverlay) updated ${keysLine}`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateKeyOverlay`, + keysLine + ); this.cachedkeys = keysLine; } - this.resetReportCount('GD(updateKeyOverlay)'); + this.resetReportCount('gameplay updateKeyOverlay'); } catch (exc) { this.reportError( - 'GD(updateKeyOverlay)', + 'gameplay updateKeyOverlay', 10, - `GD(updateKeyOverlay) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `gameplay updateKeyOverlay`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateKeyOverlay`, + exc ); - wLogger.debug(exc); } } @@ -310,20 +353,34 @@ export class Gameplay extends AbstractState { if (typeof result === 'string') { if (result === '') return; - wLogger.debug(`GD(updateHitErrors)`, result); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateHitErrors`, + result + ); + return 'not-ready'; } this.hitErrors = result; - this.resetReportCount('GD(updateHitErrors)'); + this.resetReportCount('gameplay updateHitErrors'); } catch (exc) { this.reportError( - 'GD(updateHitErrors)', + 'gameplay updateHitErrors', 50, - `GD(updateHitErrors) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `gameplay updateHitErrors`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateHitErrors`, + exc ); - wLogger.debug(exc); } } @@ -389,14 +446,22 @@ export class Gameplay extends AbstractState { result[1] || Object.assign({}, defaultLBPlayer); this.leaderboardScores = result[2]; - this.resetReportCount('GD(updateLeaderboard)'); + this.resetReportCount('gameplay updateLeaderboard'); } catch (exc) { this.reportError( - 'GD(updateLeaderboard)', + 'gameplay updateLeaderboard', 10, - `GD(updateLeaderboard) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `gameplay updateLeaderboard`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateLeaderboard`, + exc ); - wLogger.debug(exc); } } @@ -405,7 +470,9 @@ export class Gameplay extends AbstractState { const t1 = performance.now(); if (!config.calculatePP) { wLogger.debug( - 'GD(updateStarsAndPerformance) pp calculation disabled' + ClientType[this.game.client], + this.game.pid, + `gameplay updateStarsAndPerformance pp calculation disabled` ); return; } @@ -418,7 +485,9 @@ export class Gameplay extends AbstractState { if (!global.gameFolder) { wLogger.debug( - 'GD(updateStarsAndPerformance) game folder not found' + ClientType[this.game.client], + this.game.pid, + `gameplay updateStarsAndPerformance game folder not found` ); return; } @@ -426,7 +495,9 @@ export class Gameplay extends AbstractState { const currentBeatmap = beatmapPP.getCurrentBeatmap(); if (!currentBeatmap) { wLogger.debug( - "GD(updateStarsAndPerformance) can't get current map" + ClientType[this.game.client], + this.game.pid, + `gameplay updateStarsAndPerformance can't get current map` ); return; } @@ -463,7 +534,10 @@ export class Gameplay extends AbstractState { if (!this.gradualPerformance || !this.performanceAttributes) { wLogger.debug( - `GD(updateStarsAndPerformance) One of things not ready. GP:${this.gradualPerformance === undefined} - PA:${this.performanceAttributes === undefined}` + ClientType[this.game.client], + this.game.pid, + `gameplay updateStarsAndPerformance One of the things not ready`, + `gradual: ${this.gradualPerformance === undefined} - attributes: ${this.performanceAttributes === undefined}` ); return; } @@ -524,17 +598,28 @@ export class Gameplay extends AbstractState { this.previousPassedObjects = passedObjects; wLogger.debug( - `GD(updateStarsAndPerformance) [${(t2 - t1).toFixed(2)}ms] elapsed time` + ClientType[this.game.client], + this.game.pid, + `gameplay updateStarsAndPerformance`, + `[${(t2 - t1).toFixed(2)}ms] elapsed time` ); - this.resetReportCount('GD(updateStarsAndPerformance)'); + this.resetReportCount('gameplay updateStarsAndPerformance'); } catch (exc) { this.reportError( - 'GD(updateStarsAndPerformance)', + 'gameplay updateStarsAndPerformance', 10, - `GD(updateStarsAndPerformance) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `gameplay updateStarsAndPerformance`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `gameplay updateStarsAndPerformance`, + exc ); - wLogger.debug(exc); } } } diff --git a/packages/tosu/src/states/global.ts b/packages/tosu/src/states/global.ts index c5b9b22b..55d6c664 100644 --- a/packages/tosu/src/states/global.ts +++ b/packages/tosu/src/states/global.ts @@ -1,4 +1,4 @@ -import { wLogger } from '@tosu/common'; +import { ClientType, wLogger } from '@tosu/common'; import { AbstractState } from '@/states'; import { defaultCalculatedMods } from '@/utils/osuMods'; @@ -40,7 +40,13 @@ export class Global extends AbstractState { if (typeof result === 'string') { if (result === '') return; - wLogger.debug(`Global(updateState)`, result); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `global updateState`, + result + ); + return 'not-ready'; } @@ -57,14 +63,22 @@ export class Global extends AbstractState { this.skinFolder = result.skinFolder; this.memorySongsFolder = result.memorySongsFolder; - this.resetReportCount('ATD(updateState)'); + this.resetReportCount('global updateState'); } catch (exc) { this.reportError( - 'ATD(updateState)', + 'global updateState', 10, - `ATD(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `global updateState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `global updateState`, + exc ); - wLogger.debug(exc); } } @@ -75,14 +89,22 @@ export class Global extends AbstractState { this.playTime = result.time; - this.resetReportCount('ATD(updatePreciseState)'); + this.resetReportCount('global updatePreciseState'); } catch (exc) { this.reportError( - 'ATD(updatePreciseState)', + 'global updatePreciseState', 10, - `ATD(updatePreciseState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `global updatePreciseState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `global updatePreciseState`, + exc ); - wLogger.debug(exc); } } } diff --git a/packages/tosu/src/states/menu.ts b/packages/tosu/src/states/menu.ts index 14f47ffd..86fc36ac 100644 --- a/packages/tosu/src/states/menu.ts +++ b/packages/tosu/src/states/menu.ts @@ -1,4 +1,4 @@ -import { wLogger } from '@tosu/common'; +import { ClientType, wLogger } from '@tosu/common'; import { AbstractState } from '@/states'; @@ -37,7 +37,12 @@ export class Menu extends AbstractState { if (typeof result === 'string') { if (result === '') return; - wLogger.debug(`MD(updateState) ${result}`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `menu updateState`, + result + ); return 'not-ready'; } if (typeof result === 'number') { @@ -93,14 +98,22 @@ export class Menu extends AbstractState { this.previousMD5 = this.checksum; - this.resetReportCount('MB(updateState)'); + this.resetReportCount('menu updateState'); } catch (exc) { this.reportError( - 'MB(updateState)', + 'menu updateState', 10, - `MB(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `menu updateState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `menu updateState`, + exc ); - wLogger.debug(exc); } } @@ -111,19 +124,33 @@ export class Menu extends AbstractState { if (typeof result === 'string') { if (result === '') return; - wLogger.debug(`MD(updateState) ${result}`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `menu updateMP3Length`, + result + ); + return 'not-ready'; } this.mp3Length = result; - this.resetReportCount('MB(updateMP3Length)'); + this.resetReportCount('menu updateMP3Length'); } catch (exc) { this.reportError( - 'MB(updateMP3Length)', + 'menu updateMP3Length', 10, - `MB(updateMP3Length) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `menu updateMP3Length`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `menu updateMP3Length`, + exc ); - wLogger.debug(exc); } } } diff --git a/packages/tosu/src/states/resultScreen.ts b/packages/tosu/src/states/resultScreen.ts index 1ddb5591..c7dac79a 100644 --- a/packages/tosu/src/states/resultScreen.ts +++ b/packages/tosu/src/states/resultScreen.ts @@ -38,7 +38,11 @@ export class ResultScreen extends AbstractState { } init() { - wLogger.debug('RSD(init) Reset'); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `resultScreen init` + ); this.onlineId = 0; this.playerName = ''; @@ -69,7 +73,12 @@ export class ResultScreen extends AbstractState { const result = this.game.memory.resultScreen(); if (result instanceof Error) throw result; if (typeof result === 'string') { - wLogger.debug(`RSD(updateState) ${result}`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `resultScreen updateState`, + result + ); return 'not-ready'; } @@ -110,14 +119,22 @@ export class ResultScreen extends AbstractState { hits }); - this.resetReportCount('RSD(updateState)'); + this.resetReportCount('resultScreen updateState'); } catch (exc) { this.reportError( - 'RSD(updateState)', + 'resultScreen updateState', 10, - `RSD(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `resultScreen updateState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `resultScreen updateState`, + exc ); - wLogger.debug(exc); } } @@ -135,7 +152,11 @@ export class ResultScreen extends AbstractState { const currentBeatmap = beatmapPP.getCurrentBeatmap(); if (!currentBeatmap) { - wLogger.debug("RSD(updatePerformance) can't get current map"); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `resultScreen updatePerformance can't get current map` + ); return; } @@ -170,14 +191,22 @@ export class ResultScreen extends AbstractState { fcPerformance.free(); this.previousBeatmap = key; - this.resetReportCount('RSD(updatePerformance)'); + this.resetReportCount('resultScreen updatePerformance'); } catch (exc) { this.reportError( - 'RSD(updatePerformance)', + 'resultScreen updatePerformance', 10, - `RSD(updatePerformance) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `resultScreen updatePerformance`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `resultScreen updatePerformance`, + exc ); - wLogger.debug(exc); } } } diff --git a/packages/tosu/src/states/settings.ts b/packages/tosu/src/states/settings.ts index ae38109b..13028f4f 100644 --- a/packages/tosu/src/states/settings.ts +++ b/packages/tosu/src/states/settings.ts @@ -1,4 +1,4 @@ -import { wLogger } from '@tosu/common'; +import { ClientType, wLogger } from '@tosu/common'; import { AbstractState } from '@/states/index'; import { Bindings, VirtualKeyCode } from '@/utils/bindings'; @@ -452,26 +452,42 @@ export class Settings extends AbstractState { this.configList[result.key].setValue(result.value); this.resetReportCount( - `ATD(updateConfigState)[${position}]` + `settings updateConfigState [${position}]` ); } catch (exc) { this.reportError( - `ATD(updateConfigState)[${position}]`, + `settings updateConfigState [${position}]`, 10, - `ATD(updateConfigState)[${position}] ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `settings updateConfigState [${position}]`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `settings updateConfigState [${position}]`, + exc ); - wLogger.debug(exc); } } - this.resetReportCount('ATD(updateConfigState)'); + this.resetReportCount('settings updateConfigState'); } catch (exc) { this.reportError( - 'ATD(updateConfigState)', + 'settings updateConfigState', 10, - `ATD(updateConfigState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `settings updateConfigState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `settings updateConfigState`, + exc ); - wLogger.debug(exc); } } @@ -503,26 +519,42 @@ export class Settings extends AbstractState { bindable.setValue(result.value); this.resetReportCount( - `ATD(updateBindingState)[${position}]` + `settings updateBindingState [${position}]` ); } catch (exc) { this.reportError( - `ATD(updateBindingState)[${position}]`, + `settings updateBindingState [${position}]`, 10, - `ATD(updateBindingState)[${position}] ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `settings updateBindingState [${position}]`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `settings updateBindingState [${position}]`, + exc ); - wLogger.debug(exc); } } - this.resetReportCount('ATD(updateBindingState)'); + this.resetReportCount('settings updateBindingState'); } catch (exc) { this.reportError( - 'ATD(updateBindingState)', + 'settings updateBindingState', 10, - `ATD(updateBindingState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `settings updateBindingState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `settings updateBindingState`, + exc ); - wLogger.debug(exc); } } @@ -534,14 +566,22 @@ export class Settings extends AbstractState { this.updateConfigState(pointers.config); this.updateBindingState(pointers.binding); - this.resetReportCount('SETTINGS(updatestate)'); + this.resetReportCount('settings updatestate'); } catch (exc) { this.reportError( - 'SETTINGS(updatestate)', + 'settings updatestate', 10, - `SETTINGS(updatestate) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `settings updatestate`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `settings updatestate`, + exc ); - wLogger.debug(exc); } } } diff --git a/packages/tosu/src/states/tourney.ts b/packages/tosu/src/states/tourney.ts index 1aba037c..7a2dba69 100644 --- a/packages/tosu/src/states/tourney.ts +++ b/packages/tosu/src/states/tourney.ts @@ -1,4 +1,4 @@ -import { wLogger } from '@tosu/common'; +import { ClientType, wLogger } from '@tosu/common'; import { AbstractState } from '@/states'; @@ -53,12 +53,21 @@ export class TourneyManager extends AbstractState { updateState() { try { - wLogger.debug('TMD(updateState) Starting'); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `tourney updateState starting` + ); const result = this.game.memory.tourney(); if (result instanceof Error) throw result; if (typeof result === 'string') { - wLogger.debug(`TMD(updateState) ${result}`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `tourney updateState`, + result + ); return 'not-ready'; } @@ -79,14 +88,22 @@ export class TourneyManager extends AbstractState { this.messages = messages; - this.resetReportCount('TMD(updateState)'); + this.resetReportCount('tourney updateState'); } catch (exc) { this.reportError( - 'TMD(updateState)', + 'tourney updateState', 10, - `TMD(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `tourney updateState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `tourney updateState`, + exc ); - wLogger.debug(exc); } } @@ -100,7 +117,12 @@ export class TourneyManager extends AbstractState { const result = this.game.memory.tourneyUser(); if (result instanceof Error) throw result; if (typeof result === 'string') { - wLogger.debug(`TUPD(updateState) ${result}`); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `tourney updateUser`, + result + ); this.reset(); if (gameplay.isDefaultState === true) return; @@ -108,8 +130,6 @@ export class TourneyManager extends AbstractState { return; } - this.resetReportCount('TUPD(updateState) Slot'); - this.userAccuracy = result.accuracy; this.userRankedScore = result.rankedScore; this.userPlayCount = result.playcount; @@ -120,14 +140,22 @@ export class TourneyManager extends AbstractState { this.isDefaultState = false; - this.resetReportCount('TUPD(updateState)'); + this.resetReportCount('tourney updateUser'); } catch (exc) { this.reportError( - 'TUPD(updateState)', + 'tourney updateUser', 10, - `TUPD(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `tourney updateUser`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `tourney updateUser`, + exc ); - wLogger.debug(exc); } } } diff --git a/packages/tosu/src/states/user.ts b/packages/tosu/src/states/user.ts index c03ae5c5..0299a8e8 100644 --- a/packages/tosu/src/states/user.ts +++ b/packages/tosu/src/states/user.ts @@ -1,4 +1,4 @@ -import { wLogger } from '@tosu/common'; +import { ClientType, wLogger } from '@tosu/common'; import { AbstractState } from '@/states'; @@ -36,14 +36,22 @@ export class User extends AbstractState { this.backgroundColour = profile.backgroundColour; this.rawLoginStatus = profile.rawLoginStatus; - this.resetReportCount('User(updateState)'); + this.resetReportCount('user updateState'); } catch (exc) { this.reportError( - 'User(updateState)', + 'user updateState', 10, - `User(updateState) ${(exc as any).message}` + ClientType[this.game.client], + this.game.pid, + `user updateState`, + (exc as any).message + ); + wLogger.debug( + ClientType[this.game.client], + this.game.pid, + `user updateState`, + exc ); - wLogger.debug(exc); } } } diff --git a/packages/updater/index.ts b/packages/updater/index.ts index 0ddbfe48..6900ea54 100644 --- a/packages/updater/index.ts +++ b/packages/updater/index.ts @@ -25,24 +25,25 @@ const backupExecutablePath = path.join( const deleteNotLocked = async (filePath: string) => { try { await fs.promises.unlink(filePath); - } catch (err: any) { - if (err.code === 'EPERM') { + } catch (err) { + if ((err as any).code === 'EPERM') { await sleep(1000); deleteNotLocked(filePath); return; } - wLogger.error(err.message); - wLogger.debug(err); + wLogger.error('[updater]', 'deleteNotLocked', (err as any).message); + wLogger.debug('[updater]', 'deleteNotLocked', err); } }; export const checkUpdates = async () => { - wLogger.info('Checking updates'); + wLogger.info('[updater]', 'Checking updates'); try { if (platform.type === 'unknown') { wLogger.warn( + '[updater]', `Unsupported platform (${process.platform}). Unable to run updater` ); @@ -67,15 +68,18 @@ export const checkUpdates = async () => { config.updateVersion = versionName || currentVersion; if (versionName === null || versionName === undefined) { - wLogger.info(`Failed to check updates v${currentVersion}`); + wLogger.info( + '[updater]', + `Failed to check updates v${currentVersion}` + ); return new Error('Version the same'); } return { assets, versionName }; } catch (exc) { - wLogger.error(`checkUpdates`, (exc as any).message); - wLogger.debug(exc); + wLogger.error('[updater]', `checkUpdates`, (exc as any).message); + wLogger.debug('[updater]', `checkUpdates`, exc); config.currentVersion = currentVersion; config.updateVersion = currentVersion; @@ -93,7 +97,10 @@ export const autoUpdater = async () => { const { assets, versionName } = check; if (versionName.includes(currentVersion)) { - wLogger.info(`You're using latest version v${currentVersion}`); + wLogger.info( + '[updater]', + `You're using latest version v${currentVersion}` + ); if (fs.existsSync(fileDestination)) { await deleteNotLocked(fileDestination); @@ -110,7 +117,10 @@ export const autoUpdater = async () => { (r) => r.name.includes(platform.type) && r.name.endsWith('.zip') ); if (!findAsset) { - wLogger.info(`Files to update not found (${platform.type})`); + wLogger.info( + '[updater]', + `Files to update not found (${platform.type})` + ); return 'noFiles'; } @@ -124,7 +134,7 @@ export const autoUpdater = async () => { await fs.promises.rename(currentExecutablePath, backupExecutablePath); await unzip(downloadAsset, getProgramPath()); - wLogger.info('Restarting program'); + wLogger.info('[updater]', 'Restarting program'); spawn(`"${process.argv[0]}"`, process.argv.slice(1), { detached: true, @@ -132,14 +142,14 @@ export const autoUpdater = async () => { stdio: 'ignore' }).unref(); - wLogger.info('Closing program'); + wLogger.info('[updater]', 'Closing program'); await sleep(1000); process.exit(); } catch (exc) { - wLogger.error('autoUpdater', (exc as any).message); - wLogger.debug('autoUpdater', exc); + wLogger.error('[updater]', 'autoUpdater', (exc as any).message); + wLogger.debug('[updater]', 'autoUpdater', exc); return exc; }