Skip to content

Commit

Permalink
added isDev() mode and code cleanup (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
therockerline authored May 28, 2024
1 parent 362f766 commit d8866c2
Show file tree
Hide file tree
Showing 39 changed files with 70 additions and 295 deletions.
14 changes: 5 additions & 9 deletions src/main/classes/controllers/AccountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,11 @@ export class AccountController {
}
}

//salva i dati dell'account nel file config.json
//saves the account data in the config.json file
_saveNewAccountData(account: Account | undefined, isOpening = false, cryptString?: Buffer) {
const { CONFIG_FILE } = this._getPaths()
const config = this._getConfigFile(isOpening)
const lastUser = config.lastUser
//log('save account', config.lastUser, account?.username, isOpening)
if (account) {
const uniqueAccountName = `${account.host}@${account.username}`
if (cryptString)
Expand Down Expand Up @@ -90,7 +89,6 @@ export class AccountController {
log('On logout account', account?.username, { isSoft })
const API = NethVoiceAPI.api()
try {
//if (!isSoft)
await PhoneIslandController.instance.logout(account!)
await API.Authentication.logout()
log(`${account!.username} logout succesfully`)
Expand All @@ -116,7 +114,7 @@ export class AccountController {
try {
loggedAccount = await api.User.me()
} catch {
//recupera la password salvata e tenta un nuovo login
//retrieve the saved password and attempt a new login
if (account.cryptPsw) {
try {
const psw: Buffer = Buffer.from((account.cryptPsw as any).data)
Expand All @@ -134,7 +132,7 @@ export class AccountController {
log(e)
}
} else {
//se fallisce, il token era scaduto, lo rimuovo come ultimo utente in modo che non provi ulteriomente a loggarsi con il token
//if he fails, the token was expired, I remove him as the last user so that he does not try further to log in with the token
this.config!.lastUser = undefined
}
}
Expand Down Expand Up @@ -177,10 +175,9 @@ export class AccountController {
try {
const data = fs.readFileSync(CONFIG_FILE, { encoding: 'utf-8' })
const config = JSON.parse(data)
//log(config)
return Object.keys(config).includes('accounts')
} catch (e) {
//se non riesce a trasformare il file in json allora non è ben scritto e quindi non posso andare avanti
//if it fails to transform the file to json then it is not well written and therefore I cannot move forward
log(e)
return false
}
Expand All @@ -190,11 +187,10 @@ export class AccountController {

createConfigFile() {
const { CONFIG_PATH, CONFIG_FILE } = this._getPaths()
//Controllo se la cartella configs esiste, altrimenti la creo
//I check if the configs folder exists, if not, I create it

if (!this.hasConfigsFolderOfFile()) {
log("create config file")
//log('ENOENT')
try {
fs.mkdirSync(CONFIG_PATH)
} catch (e) {
Expand Down
1 change: 0 additions & 1 deletion src/main/classes/controllers/LoginController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export class LoginController {
if (loginPage) {
const bounds = loginPage.getBounds()
loginPage.setBounds({ ...bounds, width: LOGIN_WINDOW_WIDTH, height: h }, true)
//loginPage.center()
}
}
show() {
Expand Down
24 changes: 5 additions & 19 deletions src/main/classes/controllers/NethCTIController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export class NethVoiceAPI {
if (!nethlinkExtension)
reject(new Error("Questo utente non è abilitato all'uso del NethLink"))
else {
//importo il file config di questo host per prelevare le informazioni su SIP_host e port solo se sono su demo-leopard devo prenderli statici
//I import the config file of this host to take the information about SIP_host and port only if I am on demo-leopard I have to take them static
let SIP_HOST = '127.0.0.1'
let SIP_PORT = '5060'
let NUMERIC_TIMEZONE = '+0200'
Expand Down Expand Up @@ -148,12 +148,6 @@ export class NethVoiceAPI {
},
phoneIslandTokenLogin: async () =>
await this._POST('/webrest/authentication/phone_island_token_login'),
// persistantTokenRemove: async () =>
// await this._POST('/webrest/authentication/persistent_token_remove', {
// type: 'phone-island'
// }),
// phoneIslandTokenChack: async () =>
// await this._GET('/webrest/authentication/phone_island_token_exists')
}

CustCard = {}
Expand Down Expand Up @@ -213,14 +207,11 @@ export class NethVoiceAPI {
return newSpeedDial
},
updateSpeeddial: async (edit: NewSpeedDialType, current: ContactType) => {
//log(edit)

if (current.name && current.speeddial_num) {
const editedSpeedDial = Object.assign({}, current)
editedSpeedDial.speeddial_num = edit.speeddial_num
editedSpeedDial.name = edit.name
editedSpeedDial.id = editedSpeedDial.id?.toString()
//log('Edited speedDial', editedSpeedDial, current)
await this._POST(`/webrest/phonebook/modify_cticontact`, editedSpeedDial)
return editedSpeedDial
}
Expand All @@ -229,11 +220,9 @@ export class NethVoiceAPI {
await this._POST(`/webrest/phonebook/delete_cticontact`, { id: '' + obj.id })
return obj
},
///CONTACTS
//PROVA A METTERE IL CONTACTTYPE E NON IL NEWCONTACTTYPE
//CONTACTS
createContact: async (create: ContactType) => {
//L"API VUOLE IL PARAMETRO setInput
const newContact: ContactType /* & { setInput: string } */ = {
const newContact: ContactType = {
privacy: create.privacy,
type: create.privacy,
name: create.name,
Expand All @@ -246,9 +235,7 @@ export class NethVoiceAPI {
//DEFAULT VALUES
favorite: false,
selectedPrefNum: 'extension',
//setInput: ''
}
//console.log("DATA: ", newContact)
await this._POST(`/webrest/phonebook/create`, newContact)
return newContact
},
Expand Down Expand Up @@ -286,18 +273,17 @@ export class NethVoiceAPI {
heartbeat: async (extension: string) => await this._POST('/webrest/user/nethlink', { extension }),
default_device: async (deviceIdInformation: Extension) => await this._POST('/webrest/user/default_device', { id: deviceIdInformation.id }),
setPresence: async (status: StatusTypes) => await this._POST('/webrest/user/presence', { status })
//all_avatars: () => this._GET('/webrest/user/all_avatars'),
}

Voicemail = {}

fetchOperators = async (): Promise<OperatorData> => {
const endpoints: OperatorsType = await this.User.all_endpoints() //tutti i dispositivi
const endpoints: OperatorsType = await this.User.all_endpoints() //all devices
const groups = await this.AstProxy.groups() //
const extensions = await this.AstProxy.extensions()
const avatars = await this.User.all_avatars()
return {
userEndpoints: endpoints, //posso rimuoverlo
userEndpoints: endpoints, //TODO: remove this
operators: endpoints,
extensions,
groups,
Expand Down
2 changes: 1 addition & 1 deletion src/main/classes/controllers/NethLinkController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class NethLinkController {
}).then(() => {
this.window.emit(IPC_EVENTS.LOAD_DATA_END)
})
//Avviso la nethWindow che l'utente è cambiato
//Alert the nethWindow that the user has changed
}

async loadData() {
Expand Down
2 changes: 0 additions & 2 deletions src/main/classes/controllers/PhoneIslandController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,9 @@ export class PhoneIslandController {
sipHost: account.sipHost || '',
sipPort: account.sipPort || ''
}
//;('dm9pY2UuZGVtby1oZXJvbi5zZi5uZXRoc2VydmVyLm5ldDpsb3JlbnpvOmExN2ZjZDBjYTg1NDc2ZDZmOTQxZGRiM2QyNWVmMDZmMzM2M2I3ZDU6MjA5OjQ0MTYzMGYwOGJhMWY4ODdjYTU4MTUxOWFkNmJhM2Q5OjEyNy4wLjAuMToyMDEwNw==')
const dataConfig = btoa(
`${config.hostname}:${config.username}:${config.authToken}:${config.sipExten}:${config.sipSecret}:${config.sipHost}:${config.sipPort}`
)
//log('INIT PHONE-ISLAND', config.hostname, dataConfig)
this.window.emit(IPC_EVENTS.ON_DATA_CONFIG_CHANGE, dataConfig, account)
} else {
throw new Error('Incorrect configuration for the logged user')
Expand Down
1 change: 0 additions & 1 deletion src/main/classes/controllers/TrayController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export class TrayController {
const menu: (MenuItemConstructorOptions | MenuItem)[] = [
{
role: 'close',
//accelerator: 'Command+Q',
commandId: 1,
click: () => {
AppController.safeQuit()
Expand Down
4 changes: 1 addition & 3 deletions src/main/classes/windows/BaseWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,13 @@ export class BaseWindow {
this._window = createWindow(id, config, params)
const onReady = (_e, completed_id) => {
if (id === completed_id) {
//log('on build completition of', completed_id)
this._callbacks.forEach((c) => c())
//una volta chiamate le rimuovo
//once called I remove them
this._callbacks = []
}
}

const onOpenDevTools = (_e, page_id) => {
//log('on build completition of', id, page_id, this._window?.webContents.isDevToolsOpened())
log('open dev tool of', page_id === PAGES.SPLASHSCREEN)
let targetWindow: BaseWindow | undefined
switch (page_id) {
Expand Down
1 change: 0 additions & 1 deletion src/main/classes/windows/DevToolsWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,5 @@ export class DevToolsWindow extends BaseWindow {
title: 'NethLink DevTools',

})
//this._window?.webContents.openDevTools({ mode: 'detach' })
}
}
4 changes: 0 additions & 4 deletions src/main/classes/windows/LoginWindow.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { PAGES } from '@shared/types'
import { AccountController } from '../controllers'
import { BaseWindow } from './BaseWindow'
import { log } from '@shared/utils/logger'

export const LOGIN_WINDOW_WIDTH = 500
export class LoginWindow extends BaseWindow {
Expand All @@ -28,10 +27,8 @@ export class LoginWindow extends BaseWindow {
fullscreen: false,
acceptFirstMouse: false,
frame: false,
//tabbingIdentifier: 'nethconnector',
thickFrame: false
})
//this._window?.webContents.openDevTools({ mode: 'detach' })
}

show(..._args: any): void {
Expand All @@ -51,7 +48,6 @@ export class LoginWindow extends BaseWindow {
loginWindowHeight = 535
break
}
//log(accounts, loginWindowHeight)
const bounds = this._window?.getBounds()
this._window!.setBounds({ ...bounds, height: loginWindowHeight }, true)
super.show(_args)
Expand Down
2 changes: 0 additions & 2 deletions src/main/classes/windows/NethLinkWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,12 @@ export class NethLinkWindow extends BaseWindow {
fullscreen: false,
acceptFirstMouse: false,
frame: false,
//tabbingIdentifier: 'nethconnector',
thickFrame: false,
trafficLightPosition: { x: 0, y: 0 }
})
this.size = size
this.screenBounds = screen.getPrimaryDisplay().bounds
NethLinkWindow.instance = this
//this._window?.webContents.openDevTools({ mode: 'detach' })
}

_setBounds() {
Expand Down
2 changes: 0 additions & 2 deletions src/main/classes/windows/PhoneIslandWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,11 @@ export class PhoneIslandWindow extends BaseWindow {
fullscreen: false,
enableLargerThanScreen: false,
frame: false,
//tabbingIdentifier: 'nethconnector',
thickFrame: false,
trafficLightPosition: { x: 0, y: 0 },
webPreferences: {
nodeIntegration: true
}
})
//this._window?.webContents.openDevTools({ mode: 'detach' })
}
}
2 changes: 0 additions & 2 deletions src/main/classes/windows/SplashScreenWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,8 @@ export class SplashScreenWindow extends BaseWindow {
fullscreen: false,
acceptFirstMouse: false,
frame: false,
//tabbingIdentifier: 'nethconnector',
thickFrame: false,
trafficLightPosition: { x: 0, y: 0 }
})
//this._window?.webContents.openDevTools({ mode: 'detach' })
}
}
43 changes: 16 additions & 27 deletions src/main/lib/ipcEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,9 @@ function onSyncEmitter<T>(

export function registerIpcEvents() {

//TODO: spostare ogni evento nel controller di appartenenza
//TODO: move each event to the controller it belongs to
onSyncEmitter(IPC_EVENTS.LOGIN, async (...args) => {
const [host, username, password] = args
//log(args)
const tempAccount: Account = {
host,
username,
Expand Down Expand Up @@ -145,24 +144,20 @@ export function registerIpcEvents() {
}
const notification: Notification = new Notification(options)

// notification.on('click', () => {
// log('RECEIVED CLICK ON NOTIFICATION', options, openUrl)
// if (openUrl) {
// shell.openExternal(openUrl)
// }
// })
notification.on('failed', () => log('NOTIFICATION failed'))
notification.on('action', () => log('NOTIFICATION action'))
notification.on('close', () => log('NOTIFICATION close'))
notification.on('reply', () => log('NOTIFICATION reply'))
notification.on('show', () => log('NOTIFICATION show'))

notification.on("click", () => {
log('RECEIVED CLICK ON NOTIFICATION', options, openUrl)
if (openUrl) {
shell.openExternal(openUrl)
}
})
setTimeout(() => {
notification.on('failed', () => log('NOTIFICATION failed'))
notification.on('action', () => log('NOTIFICATION action'))
notification.on('close', () => log('NOTIFICATION close'))
notification.on('reply', () => log('NOTIFICATION reply'))
notification.on('show', () => log('NOTIFICATION show'))

notification.on("click", () => {
log('RECEIVED CLICK ON NOTIFICATION', options, openUrl)
if (openUrl) {
shell.openExternal(openUrl)
}
})
}, 100);

notification.show()
log('RECEIVED SEND NOTIFICATION', options, openUrl, notification)
Expand All @@ -173,7 +168,7 @@ export function registerIpcEvents() {
Object.keys(PHONE_ISLAND_EVENTS).forEach((ev) => {
ipcMain.on(ev, async (_event, ...args) => {
const evName = `on-${ev}`
log('send back', evName, /*...args*/)
log('send back', evName)
NethLinkController.instance.window.emit(evName, ...args)
switch (ev) {
case PHONE_ISLAND_EVENTS['phone-island-call-answered']:
Expand All @@ -194,12 +189,6 @@ export function registerIpcEvents() {
NethVoiceAPI.api().User.setPresence('online')
break;
}
// if (ev === PHONE_ISLAND_EVENTS['phone-island-call-answered']) {
// const username = AccountController.instance.getLoggedAccount()?.username
// if (username) {
// log(Object.keys(args[0]?.[username]?.conversations || {}).length > 0)
// }
// }
})
})
}
Expand Down
11 changes: 1 addition & 10 deletions src/main/lib/windowConstructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,8 @@ export function createWindow(
})
}

// mainWindow.on('show', () => {
// if (is.dev) {
// mainWindow.webContents.openDevTools({
// mode: 'detach'
// })
// }
// })

mainWindow.on('hide', () => {
//mainWindow.webContents.closeDevTools()
})
mainWindow.on('hide', () => { })

mainWindow.on('close', () => {
AccountController.instance.stopAuthPolling()
Expand Down
Loading

0 comments on commit d8866c2

Please sign in to comment.