Skip to content

Commit

Permalink
BETTER LOGGING
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsRiprod committed Nov 17, 2024
1 parent 102f1cc commit 3c4d401
Show file tree
Hide file tree
Showing 55 changed files with 1,055 additions and 827 deletions.
15 changes: 4 additions & 11 deletions DeskThingServer/src/main/handlers/adbHandler.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import path from 'path'
import { execFile } from 'child_process'
import getPlatform from '../utils/get-platform'
import dataListener, { MESSAGE_TYPES } from '../utils/events'
import loggingStore from '../stores/loggingStore'
import settingsStore from '../stores/settingsStore'
import { ReplyFn } from '@shared/types'
import { ReplyFn, MESSAGE_TYPES } from '@shared/types'

const isDevelopment = process.env.NODE_ENV === 'development'
const execPath = isDevelopment
Expand All @@ -28,17 +28,13 @@ const splitArgs = (str: string): string[] => {
export const handleAdbCommands = async (command: string, replyFn?: ReplyFn): Promise<string> => {
const settings = await settingsStore.getSettings()
const useGlobalADB = settings.globalADB === true
dataListener.asyncEmit(
MESSAGE_TYPES.LOGGING,
useGlobalADB ? 'Using Global ADB' : 'Using Local ADB'
)
loggingStore.log(MESSAGE_TYPES.LOGGING, useGlobalADB ? 'Using Global ADB' : 'Using Local ADB')
return new Promise((resolve, reject) => {
execFile(
useGlobalADB ? 'adb' : adbPath,
splitArgs(command),
{ cwd: execPath },
(error, stdout, stderr) => {
console.log(error, stdout, stderr)
if (error) {
replyFn &&
replyFn('logging', {
Expand All @@ -47,10 +43,7 @@ export const handleAdbCommands = async (command: string, replyFn?: ReplyFn): Pro
final: false,
error: stderr
})
dataListener.asyncEmit(
MESSAGE_TYPES.ERROR,
`ADB Error: ${stderr}, ${command}, ${adbPath}`
)
loggingStore.log(MESSAGE_TYPES.ERROR, `ADB Error: ${stderr}, ${command}, ${adbPath}`)
reject(`ADB Error: ${stderr}, ${command}, ${adbPath}`)
} else {
replyFn &&
Expand Down
21 changes: 12 additions & 9 deletions DeskThingServer/src/main/handlers/appHandler.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import path from 'path'
import { AppIPCData, ReplyFn } from '@shared/types/ipcTypes'
import dataListener, { MESSAGE_TYPES } from '../utils/events'
import {
App,
AppDataInterface,
AppReturnData,
AppIPCData,
ReplyFn,
MESSAGE_TYPES
} from '@shared/types'
import loggingStore from '../stores/loggingStore'
import { getData, setData } from './dataHandler'
import { dialog, BrowserWindow } from 'electron'
import { sendMessageToApp, AppHandler } from '../services/apps'
import { App, AppDataInterface, AppReturnData } from '@shared/types'
const appStore = AppHandler.getInstance()

export const appHandler: Record<
Expand Down Expand Up @@ -109,7 +115,7 @@ export const appHandler: Record<
return { path: filePath, name: path.basename(filePath) }
},
'dev-add-app': async (data, replyFn) => {
dataListener.asyncEmit(
loggingStore.log(
MESSAGE_TYPES.ERROR,
'Developer App Not implemented Yet ',
data.payload.appPath
Expand All @@ -118,7 +124,6 @@ export const appHandler: Record<
replyFn('logging', { status: true, data: 'Finished', final: true })
},
'send-to-app': async (data, replyFn) => {
console.log('sending data to app: ', data.payload.app, data)
await sendMessageToApp(data.payload.app, data.payload)
replyFn('logging', { status: true, data: 'Finished', final: true })
},
Expand All @@ -130,16 +135,14 @@ export const appHandler: Record<

const getApps = (replyFn: ReplyFn): App[] => {
replyFn('logging', { status: true, data: 'Getting data', final: false })
console.log('Getting app data')
const data = appStore.getAllBase()
replyFn('logging', { status: true, data: 'Finished', final: true })
replyFn('app-data', { status: true, data: data, final: true })
return data
}

const setAppData = async (replyFn: ReplyFn, id, data: AppDataInterface): Promise<void> => {
console.log('Saving app data: ', data)
dataListener.asyncEmit(MESSAGE_TYPES.LOGGING, 'SERVER: Saving ' + id + "'s data " + data)
loggingStore.log(MESSAGE_TYPES.LOGGING, 'SERVER: Saving ' + id + "'s data " + data)
await setData(id, data)
replyFn('logging', { status: true, data: 'Finished', final: true })
}
Expand All @@ -150,7 +153,7 @@ const getAppData = async (replyFn, payload): Promise<AppDataInterface | null> =>
replyFn('logging', { status: true, data: 'Finished', final: true })
return data
} catch (error) {
dataListener.asyncEmit(MESSAGE_TYPES.ERROR, 'SERVER: Error saving manifest' + error)
loggingStore.log(MESSAGE_TYPES.ERROR, 'SERVER: Error saving manifest' + error)
console.error('Error setting client manifest:', error)
replyFn('logging', { status: false, data: 'Unfinished', error: error, final: true })
return null
Expand Down
22 changes: 10 additions & 12 deletions DeskThingServer/src/main/handlers/authHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { sendMessageToApp } from '../services/apps' // Assuming you have an app
import http from 'http'
import url from 'url'
import settingsStore from '../stores/settingsStore'
import dataListener, { MESSAGE_TYPES } from '../utils/events'
import { Settings } from '@shared/types'
import loggingStore from '../stores/loggingStore'
import { Settings, MESSAGE_TYPES } from '@shared/types'

const successView = '<h1>Success</h1><p>You can now close this window.</p>'

Expand All @@ -14,7 +14,7 @@ let callBackPort: number
function handleCallback(req: http.IncomingMessage, res: http.ServerResponse): void {
const parsedUrl = url.parse(req.url || '', true)

dataListener.asyncEmit(
loggingStore.log(
MESSAGE_TYPES.LOGGING,
`AUTH: Received callback request for ${parsedUrl.pathname}`
)
Expand All @@ -29,15 +29,13 @@ function handleCallback(req: http.IncomingMessage, res: http.ServerResponse): vo

const appName = urlParts[1] // The app name should be the third part after '/callback/'
const config = getAppData() // Assuming getConfig() returns an object with active apps
console.log('AUTH DATA: ', config)
if (!config.apps || !config.apps.some((app) => app.name === appName && app.enabled)) {
res.writeHead(404, { 'Content-Type': 'text/html' })
res.end(`<h1>App Not Found</h1><p>App '${appName}' not found or not active.</p>`)
return
}

const code = parsedUrl.query.code as string
console.log('AUTH CODE: ', code)
sendMessageToApp(appName, { type: 'callback-data', payload: code })

res.writeHead(200, { 'Content-Type': 'text/html' })
Expand All @@ -47,11 +45,10 @@ function handleCallback(req: http.IncomingMessage, res: http.ServerResponse): vo
const startServer = async (): Promise<void> => {
if (server) {
await server.close(() => {
console.log('CALLBACK: Previous server closed.')
loggingStore.log(MESSAGE_TYPES.LOGGING, 'CALLBACK: Shutting down the server...')
})
}

console.log('CALLBACK: Starting server...')
server = http.createServer((req, res) => {
const parsedUrl = new URL(`http://${req.headers.host}${req.url}`)
const pathname = parsedUrl.pathname
Expand All @@ -63,9 +60,8 @@ const startServer = async (): Promise<void> => {
}
})

console.log('CALLBACK: Listening...')
server.listen(callBackPort, () => {
dataListener.asyncEmit(
loggingStore.log(
MESSAGE_TYPES.MESSAGE,
`CALLBACK: running at http://localhost:${callBackPort}/`
)
Expand All @@ -82,16 +78,18 @@ const initializeServer = async (): Promise<void> => {
}
}

dataListener.on(MESSAGE_TYPES.SETTINGS, (newSettings) => {
settingsStore.addListener((newSettings) => {
try {
if (newSettings.callbackPort != callBackPort) {
callBackPort = newSettings.callbackPort
startServer()
} else {
dataListener.asyncEmit(MESSAGE_TYPES.LOGGING, 'CALLBACK: Not starting - port is not changed')
loggingStore.log(MESSAGE_TYPES.LOGGING, 'CALLBACK: Not starting - port is not changed')
}
} catch (error) {
dataListener.asyncEmit(MESSAGE_TYPES.ERROR, 'CALLBACK: Error updating with settings', error)
if (error instanceof Error) {
loggingStore.log(MESSAGE_TYPES.ERROR, 'CALLBACK: Error updating with settings' + error)
}
}
})

Expand Down
30 changes: 19 additions & 11 deletions DeskThingServer/src/main/handlers/clientHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ClientIPCData, ReplyFn } from '@shared/types/ipcTypes'
import dataListener, { MESSAGE_TYPES } from '../utils/events'
import { ClientIPCData, ClientManifest, SocketData, ReplyFn, MESSAGE_TYPES } from '@shared/types'
import loggingStore from '../stores/loggingStore'
import { handleAdbCommands } from './adbHandler'
import {
configureDevice,
Expand All @@ -9,7 +9,6 @@ import {
HandleWebappZipFromUrl,
SetupProxy
} from './deviceHandler'
import { ClientManifest, SocketData } from '@shared/types'
import { sendMessageToClient, sendMessageToClients } from '../services/client/clientCom'

export const clientHandler: Record<
Expand All @@ -28,7 +27,11 @@ export const clientHandler: Record<
return `Pinging ${data.payload}...`
} catch (error) {
console.error('Error pinging client:', error)
dataListener.asyncEmit(MESSAGE_TYPES.ERROR, error)
if (error instanceof Error) {
loggingStore.log(MESSAGE_TYPES.ERROR, error.message)
} else {
loggingStore.log(MESSAGE_TYPES.ERROR, String(error))
}
return 'Error pinging' + data.payload
}
},
Expand All @@ -45,7 +48,6 @@ export const clientHandler: Record<
return handleUrl(data, replyFn)
},
adb: async (data, replyFn) => {
console.log('Running ADB command:', data.payload)
replyFn('logging', { status: true, data: 'Working', final: false })

const response = await handleAdbCommands(data.payload, replyFn)
Expand All @@ -70,7 +72,7 @@ export const clientHandler: Record<
},
'push-staged': async (data, replyFn) => {
try {
console.log('Pushing staged webapp...')
loggingStore.log(MESSAGE_TYPES.LOGGING, 'Pushing staged app...')
HandlePushWebApp(data.payload, replyFn)
} catch (error) {
replyFn('logging', {
Expand All @@ -79,13 +81,16 @@ export const clientHandler: Record<
error: 'Failed to push staged app!',
final: true
})
console.error('Error extracting zip file:', error)
dataListener.asyncEmit(MESSAGE_TYPES.ERROR, error)
if (error instanceof Error) {
loggingStore.log(MESSAGE_TYPES.ERROR, error.message)
} else {
loggingStore.log(MESSAGE_TYPES.ERROR, String(error))
}
}
},
'push-proxy-script': async (data, replyFn) => {
try {
console.log('Pushing proxy script...')
loggingStore.log(MESSAGE_TYPES.LOGGING, 'Pushing proxy script...')
SetupProxy(replyFn, data.payload)
replyFn('logging', {
status: true,
Expand All @@ -100,7 +105,11 @@ export const clientHandler: Record<
final: true
})
console.error('Error pushing proxy script:', error)
dataListener.asyncEmit(MESSAGE_TYPES.ERROR, error)
if (error instanceof Error) {
loggingStore.log(MESSAGE_TYPES.ERROR, error.message)
} else {
loggingStore.log(MESSAGE_TYPES.ERROR, String(error))
}
}
},
'run-device-command': async (data, replyFn) => {
Expand All @@ -112,7 +121,6 @@ export const clientHandler: Record<
request: data.payload.request,
payload: !payload.includes('{') ? data.payload.payload : JSON.parse(data.payload.payload)
}
console.log('Sending data', data)
replyFn('logging', { status: true, data: 'Finished', final: true })
return await sendMessageToClients(message)
}
Expand Down
32 changes: 15 additions & 17 deletions DeskThingServer/src/main/handlers/configHandler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sendIpcData } from '..'
import { AppData, App, Manifest, ButtonMapping } from '@shared/types'
import dataListener, { MESSAGE_TYPES } from '../utils/events'
import { AppData, App, MESSAGE_TYPES, Manifest, ButtonMapping } from '@shared/types'
import loggingStore from '../stores/loggingStore'
import { readFromFile, writeToFile } from '../utils/fileHandler'

const defaultData: AppData = {
Expand All @@ -17,7 +17,6 @@ const readData = (): AppData => {
const data = readFromFile<AppData>(dataFilePath)
if (!data) {
// File does not exist, create it with default data
console.log('File does not exist, creating it with default data')
writeToFile(defaultData, dataFilePath)
return defaultData
}
Expand All @@ -34,11 +33,11 @@ const writeData = (data: AppData): void => {
try {
const result = writeToFile<AppData>(data, 'apps.json')
if (!result) {
dataListener.asyncEmit(MESSAGE_TYPES.ERROR, 'Error writing data')
loggingStore.log(MESSAGE_TYPES.ERROR, 'Error writing data')
}
sendIpcData('app-data', data) // Send data to the web UI
} catch (err) {
dataListener.asyncEmit(MESSAGE_TYPES.ERROR, 'Error writing data' + err)
loggingStore.log(MESSAGE_TYPES.ERROR, 'Error writing data' + err)
console.error('Error writing data:', err)
}
}
Expand Down Expand Up @@ -104,12 +103,11 @@ const addConfig = (configName: string, config: string | Array<string>, data = re
} else {
data.config[configName] = config
}
console.log('THIS IS THE FIRST TIME THIS IS BEING EMITTED - TRY AND TRACK IT')
dataListener.asyncEmit(MESSAGE_TYPES.CONFIG, {
app: 'server',
type: 'config',
payload: data.config
})
// loggingStore.log(MESSAGE_TYPES.CONFIG, {
// app: 'server',
// type: 'config',
// payload: data.config
// })
writeData(data)
}
const getConfig = (
Expand Down Expand Up @@ -150,19 +148,19 @@ const getAppByIndex = (index: number): App | undefined => {
}

const purgeAppConfig = async (appName: string): Promise<void> => {
console.log('SERVER: Deleting App From Config...', appName)
loggingStore.log(MESSAGE_TYPES.LOGGING, `Purging app: ${appName}`)
const data = readData()

// Filter out the app to be purged
const filteredApps = data.apps.filter((app: App) => app.name !== appName)
data.apps = filteredApps

writeData(data)
dataListener.asyncEmit(MESSAGE_TYPES.CONFIG, {
app: 'server',
type: 'config',
payload: data.config
})
// loggingStore.log(MESSAGE_TYPES.CONFIG, {
// app: 'server',
// type: 'config',
// payload: data.config
// })
}

export {
Expand Down
1 change: 0 additions & 1 deletion DeskThingServer/src/main/handlers/dataHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ const getData = (app: string): AppDataInterface => {
}

const purgeAppData = async (appName: string): Promise<void> => {
console.log('SERVER: Deleting app data...')
const data = readData()
delete data[appName]
writeData(data)
Expand Down
Loading

0 comments on commit 3c4d401

Please sign in to comment.