diff --git a/desktop/flow-typed/npm/electron_v22.0.0.js b/desktop/flow-typed/npm/electron_v22.0.0.js index 836b39f56..a5e49ed5b 100644 --- a/desktop/flow-typed/npm/electron_v22.0.0.js +++ b/desktop/flow-typed/npm/electron_v22.0.0.js @@ -1,414 +1,485 @@ // @flow // flow-typed signature: f8bfa3876f1890f644b65b1ebd801ed8 // flow-typed version: <>/electron_v22.0.0/flow_v0.182.0 declare module 'electron' { declare export var app: App; declare type App = { quit(): void, whenReady(): Promise, hide(): void, show(): void, setName: (name: string) => void, getVersion: () => string, dock: Dock, isPackaged: boolean, name: string, on: >( event: T, listener: $ElementType, ) => void, removeListener: >( event: T, listener: $ElementType, ) => void, }; declare type AppEvents = { 'window-all-closed': () => void, 'activate': (event: Event, hasVisibleWindows: boolean) => void, }; declare export class BrowserWindow { constructor(options?: { +width?: number, +height?: number, +x?: number, +y?: number, +useContentSize?: boolean, +center?: boolean, +minWidth?: number, +minHeight?: number, +maxWidth?: number, +maxHeight?: number, +resizable?: boolean, +movable?: boolean, +minimizable?: boolean, +maximizable?: boolean, +closable?: boolean, +focusable?: boolean, +alwaysOnTop?: boolean, +fullscreen?: boolean, +fullscreenable?: boolean, +simpleFullscreen?: boolean, +skipTaskbar?: boolean, +kiosk?: boolean, +title?: string, +icon?: string, +show?: boolean, +paintWhenInitiallyHidden?: boolean, +frame?: boolean, +parent?: BrowserWindow, +modal?: boolean, +acceptFirstMouse?: boolean, +disableAutoHideCursor?: boolean, +autoHideMenuBar?: boolean, +enableLargerThanScreen?: boolean, +backgroundColor?: string, +hasShadow?: boolean, +opacity?: number, +darkTheme?: boolean, +transparent?: boolean, +type?: string, +visualEffectState?: 'followWindow' | 'active' | 'inactive', +titleBarStyle?: | 'default' | 'hidden' | 'hiddenInset' | 'customButtonsOnHover', +trafficLightPosition?: { +x: number, +y: number }, +roundedCorners?: boolean, +fullscreenWindowTitle?: boolean, +thickFrame?: boolean, +vibrancy?: | 'appearance-based' | 'light' | 'dark' | 'titlebar' | 'selection' | 'menu' | 'popover' | 'sidebar' | 'medium-light' | 'ultra-dark' | 'header' | 'sheet' | 'window' | 'hud' | 'fullscreen-ui' | 'tooltip' | 'content' | 'under-window' | 'under-page', +zoomToPageWidth?: boolean, +tabbingIdentifier?: string, +webPreferences?: { +preload?: string, }, +titleBarOverlay?: | { +color?: string, +symbolColor?: string, +height?: number } | boolean, }): void; destroy(): void; close(): void; show(): void; hide(): void; maximize(): void; unmaximize(): void; isMaximized(): boolean; minimize(): void; loadURL( url: string, options?: { +userAgent?: string, +extraHeaders?: string, +baseURLForDataURL?: string, }, ): Promise; loadFile( filePath: string, options?: { +query?: { [string]: string }, +search?: string, +hash?: string, }, ): Promise; reload(): void; setMenu(menu: Menu | null): void; isDestroyed(): boolean; static getAllWindows(): $ReadOnlyArray; webContents: WebContents; on>( event: T, listener: $ElementType, ): void; removeListener>( event: T, listener: $ElementType, ): void; } declare type BrowserWindowEvents = { close: (event: Event) => void, closed: () => void, }; declare export type Event = { preventDefault: () => void, }; declare export var contextBridge: ContextBridge; declare type ContextBridge = { exposeInMainWorld(apiKey: string, api: mixed): void, }; declare export var autoUpdater: AutoUpdater; declare class AutoUpdater { setFeedURL(options: { +url: string, +headers?: { +[string]: string }, +serverType?: 'json' | 'default', }): void; getFeedURL(): string; checkForUpdates(): void; quitAndInstall(): void; on>( event: T, listener: $ElementType, ): void; removeListener>( event: T, listener: $ElementType, ): void; } declare type AutoUpdaterEvents = { 'checking-for-update': () => void, 'update-available': () => void, 'update-not-available': () => void, 'update-downloaded': ( event: Event, releaseNotes?: string, releaseName: string, releaseDate?: Date, updateURL?: string, ) => void, }; declare class Dock { setBadge(text: string): void; getBadge(): string; hide(): void; show(): Promise; } declare export var ipcMain: IpcMain; declare type IpcMain = { on( channel: string, listener: (event: IpcMainEvent, ...args: $ReadOnlyArray) => void, ): void, removeListener( channel: string, listener: (...args: $ReadOnlyArray) => void, ): void, }; declare export type IpcMainEvent = { +processId: number, +frameId: number, returnValue: mixed, +sender: WebContents, +reply: (channel: string, ...args: $ReadOnlyArray) => void, }; declare export var ipcRenderer: IpcRenderer; declare type IpcRenderer = { on( channel: string, listener: (event: IpcRendererEvent, ...args: $ReadOnlyArray) => void, ): void, removeListener( channel: string, listener: (...args: $ReadOnlyArray) => void, ): void, send(channel: string, ...args: $ReadOnlyArray): void, sendSync(channel: string, ...args: $ReadOnlyArray): any, }; declare export type MenuItemConstructorOptions = { label?: string, submenu?: $ReadOnlyArray, type?: 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio', role?: | 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteAndMatchStyle' | 'delete' | 'selectAll' | 'reload' | 'forceReload' | 'toggleDevTools' | 'resetZoom' | 'zoomIn' | 'zoomOut' | 'toggleSpellChecker' | 'togglefullscreen' | 'window' | 'minimize' | 'close' | 'help' | 'about' | 'services' | 'hide' | 'hideOthers' | 'unhide' | 'quit' | 'showSubstitutions' | 'toggleSmartQuotes' | 'toggleSmartDashes' | 'toggleTextReplacement' | 'startSpeaking' | 'stopSpeaking' | 'zoom' | 'front' | 'appMenu' | 'fileMenu' | 'editMenu' | 'viewMenu' | 'shareMenu' | 'recentDocuments' | 'toggleTabBar' | 'selectNextTab' | 'selectPreviousTab' | 'mergeAllWindows' | 'clearRecentDocuments' | 'moveTabToNewWindow' | 'windowMenu', }; declare export class Menu { constructor(): void; static setApplicationMenu(menu: Menu | null): void; static buildFromTemplate( template: $ReadOnlyArray, ): Menu; } + declare export var pushNotifications: PushNotifications; + declare class PushNotifications { + registerForAPNSNotifications(): Promise; + unregisterForAPNSNotifications(): void; + + on>( + event: T, + listener: $ElementType, + ): void; + removeListener>( + event: T, + listener: $ElementType, + ): void; + } + declare type PushNotificationsEvents = { + 'received-apns-notification': ( + event: Event, + userInfo: { +[string]: mixed }, + ) => void, + }; + + declare export class Notification { + constructor(options?: { + +title?: string, + +subtitle?: string, + +body?: string, + +silent?: boolean, + +hasReply?: boolean, + +timeoutType?: 'default' | 'never', + +replyPlaceholder?: string, + +sound?: string, + +urgency?: 'normal' | 'critical' | 'low', + +actions?: NotificationAction[], + +closeButtonText?: string, + +toastXml?: string, + }): void; + static isSupported(): boolean; + show(): void; + close(): void; + +title: string; + +subtitle: string; + +body: string; + +replyPlaceholder: string; + +sound: string; + +closeButtonText: string; + +silent: boolean; + +hasReply: boolean; + +urgency: 'normal' | 'critical' | 'low'; + +timeoutType: 'default' | 'never'; + +toastXml: string; + + on>( + event: T, + listener: $ElementType, + ): void; + removeListener>( + event: T, + listener: $ElementType, + ): void; + } + declare type NotificationEvents = { + show: (event: Event) => void, + click: (event: Event) => void, + close: (event: Event) => void, + reply: (event: Event, reply: string) => void, + action: (event: Event, index: number) => void, + failed: (event: Event, error: string) => void, + }; + declare export var shell: Shell; declare type Shell = { openExternal( url: string, options?: { +activate?: boolean, +workingDirectory?: string }, ): Promise, }; declare export var systemPreferences: SystemPreferences; declare type SystemPreferences = { getUserDefault>( key: string, type: Type, ): $ElementType, }; declare export type UserDefaultTypes = { string: string, boolean: boolean, integer: number, float: number, double: number, url: string, array: Array, dictionary: { [string]: mixed }, }; declare class WebContents { loadURL( url: string, options?: { +userAgent?: string, +extraHeaders?: string, +baseURLForDataURL?: string, }, ): Promise; loadFile( filePath: string, options?: { +query?: { [string]: string }, +search?: string, +hash?: string, }, ): Promise; canGoBack(): boolean; canGoForward(): boolean; clearHistory(): void; insertCSS(css: string, options?: { +cssOrigin?: string }): Promise; setWindowOpenHandler( handler: (details: { +url: string, +frameName: string, +features: string, +disposition: | 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'save-to-disk' | 'other', }) => | { +action: 'deny' } | { +action: 'allow', +outlivesOpener?: boolean }, ): void; send(channel: string, ...args: $ReadOnlyArray): void; on>( event: T, listener: $ElementType, ): void; } declare type WebContentsEvents = { 'did-finish-load': () => void, 'did-fail-load': ( event: Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean, frameProcessId: number, frameRoutingId: number, ) => void, 'did-navigate-in-page': ( event: Event, url: string, isMainFrame: boolean, frameProcessId: number, frameRoutingId: number, ) => void, }; declare export type IpcRendererEvent = { sender: IpcRenderer, senderId: number, ports: $ReadOnlyArray, }; } declare module 'electron/main' { declare export { app, BrowserWindow, shell, Menu, ipcMain, systemPreferences, autoUpdater, + pushNotifications, + Notification, } from 'electron'; } declare module 'electron/renderer' { declare export { IpcRendererEvent, contextBridge, ipcRenderer, } from 'electron'; } diff --git a/desktop/src/main.js b/desktop/src/main.js index 0981a32eb..fae66922f 100644 --- a/desktop/src/main.js +++ b/desktop/src/main.js @@ -1,288 +1,311 @@ // @flow import { app, BrowserWindow, shell, Menu, ipcMain, systemPreferences, autoUpdater, // eslint-disable-next-line import/extensions } from 'electron/main'; import fs from 'fs'; import path from 'path'; import { initAutoUpdate } from './auto-update.js'; import { handleSquirrelEvent } from './handle-squirrel-event.js'; +import { + listenForNotifications, + registerForNotifications, +} from './push-notifications.js'; const isDev = process.env.ENV === 'dev'; const url = isDev ? 'http://localhost:3000/comm/' : 'https://web.comm.app'; const isMac = process.platform === 'darwin'; const scrollbarCSS = fs.promises.readFile( path.resolve(__dirname, '../scrollbar.css'), 'utf8', ); const setApplicationMenu = () => { let mainMenu = []; if (isMac) { mainMenu = [ { label: app.name, submenu: [ { role: 'about' }, { type: 'separator' }, { role: 'services' }, { type: 'separator' }, { role: 'hide' }, { role: 'hideOthers' }, { role: 'unhide' }, { type: 'separator' }, { role: 'quit' }, ], }, ]; } const viewMenu = { label: 'View', submenu: [ { role: 'reload' }, { type: 'separator' }, { role: 'resetZoom' }, { role: 'zoomIn' }, { role: 'zoomOut' }, { type: 'separator' }, { role: 'togglefullscreen' }, { role: 'toggleDevTools' }, ], }; const windowMenu = { label: 'Window', submenu: [ { role: 'minimize' }, ...(isMac ? [ { type: 'separator' }, { role: 'front' }, { type: 'separator' }, { role: 'window' }, ] : [{ role: 'close' }]), ], }; const menu = Menu.buildFromTemplate([ ...mainMenu, { role: 'fileMenu' }, { role: 'editMenu' }, viewMenu, windowMenu, ]); Menu.setApplicationMenu(menu); }; -const createMainWindow = () => { +let mainWindow = null; +const createMainWindow = (urlPath?: string) => { const win = new BrowserWindow({ show: false, width: 1300, height: 800, minWidth: 1100, minHeight: 600, titleBarStyle: 'hidden', trafficLightPosition: { x: 20, y: 24 }, titleBarOverlay: { color: '#0A0A0A', symbolColor: '#FFFFFF', height: 64, }, backgroundColor: '#0A0A0A', webPreferences: { preload: path.resolve(__dirname, 'preload.js'), }, }); const updateNavigationState = () => { win.webContents.send('on-navigate', { canGoBack: win.webContents.canGoBack(), canGoForward: win.webContents.canGoForward(), }); }; win.webContents.on('did-navigate-in-page', updateNavigationState); const clearHistory = () => { win.webContents.clearHistory(); updateNavigationState(); }; ipcMain.on('clear-history', clearHistory); const doubleClickTopBar = () => { if (isMac) { // Possible values for AppleActionOnDoubleClick are Maximize, // Minimize or None. We handle the last two inside this if. // Maximize (which is the only behaviour for other platforms) // is handled in the later block. const action = systemPreferences.getUserDefault( 'AppleActionOnDoubleClick', 'string', ); if (action === 'None') { return; } else if (action === 'Minimize') { win.minimize(); return; } } if (win.isMaximized()) { win.unmaximize(); } else { win.maximize(); } }; ipcMain.on('double-click-top-bar', doubleClickTopBar); const updateDownloaded = (event, releaseNotes, releaseName) => { win.webContents.send('on-new-version-available', releaseName); }; autoUpdater.on('update-downloaded', updateDownloaded); win.on('closed', () => { + mainWindow = null; ipcMain.removeListener('clear-history', clearHistory); ipcMain.removeListener('double-click-top-bar', doubleClickTopBar); autoUpdater.removeListener('update-downloaded', updateDownloaded); }); win.webContents.setWindowOpenHandler(({ url: openURL }) => { shell.openExternal(openURL); // Returning 'deny' prevents a new electron window from being created return { action: 'deny' }; }); (async () => { const css = await scrollbarCSS; win.webContents.insertCSS(css); })(); - win.loadURL(url); + win.loadURL(url + (urlPath ?? '')); + mainWindow = win; return win; }; const createSplashWindow = () => { const win = new BrowserWindow({ width: 300, height: 300, resizable: false, frame: false, alwaysOnTop: true, center: true, backgroundColor: '#111827', }); win.loadFile(path.resolve(__dirname, '../pages/splash.html')); return win; }; const createErrorWindow = () => { const win = new BrowserWindow({ show: false, width: 400, height: 300, resizable: false, center: true, titleBarStyle: 'hidden', trafficLightPosition: { x: 20, y: 24 }, backgroundColor: '#111827', }); win.on('close', () => { app.quit(); }); win.loadFile(path.resolve(__dirname, '../pages/error.html')); return win; }; -const show = () => { +const show = (urlPath?: string) => { const splash = createSplashWindow(); const error = createErrorWindow(); - const main = createMainWindow(); + const main = createMainWindow(urlPath); let loadedSuccessfully = true; main.webContents.on('did-fail-load', () => { loadedSuccessfully = false; if (!splash.isDestroyed()) { splash.destroy(); } if (!error.isDestroyed()) { error.show(); } setTimeout(() => { loadedSuccessfully = true; main.loadURL(url); }, 1000); }); main.webContents.on('did-finish-load', () => { if (loadedSuccessfully) { if (!splash.isDestroyed()) { splash.destroy(); } if (!error.isDestroyed()) { error.destroy(); } main.show(); + + if (app.isPackaged) { + (async () => { + const token = await registerForNotifications(); + main.webContents.send('on-device-token-registered', token); + })(); + } } }); }; const run = () => { app.setName('Comm'); setApplicationMenu(); (async () => { await app.whenReady(); if (app.isPackaged) { try { initAutoUpdate(); } catch (error) { console.error(error); } + listenForNotifications(threadID => { + if (mainWindow) { + mainWindow.webContents.send('on-notification-clicked', { + threadID, + }); + } else { + show(`chat/thread/${threadID}/`); + } + }); } ipcMain.on('set-badge', (event, value) => { if (isMac) { app.dock.setBadge(value?.toString() ?? ''); } }); ipcMain.on('get-version', event => { event.returnValue = app.getVersion().toString(); }); show(); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { show(); } }); })(); app.on('window-all-closed', () => { if (!isMac) { app.quit(); } }); }; if (app.isPackaged && process.platform === 'win32') { if (!handleSquirrelEvent()) { run(); } } else { run(); } diff --git a/desktop/src/push-notifications.js b/desktop/src/push-notifications.js new file mode 100644 index 000000000..a94aa372a --- /dev/null +++ b/desktop/src/push-notifications.js @@ -0,0 +1,49 @@ +// @flow + +// eslint-disable-next-line import/extensions +import { pushNotifications, Notification } from 'electron/main'; + +async function registerForNotifications(): Promise { + if (process.platform !== 'darwin') { + return null; + } + + try { + const token = await pushNotifications.registerForAPNSNotifications(); + return token; + } catch (err) { + console.error(err); + } + + return null; +} + +function listenForNotifications(handleClick: (threadID: string) => void) { + if (process.platform !== 'darwin') { + return; + } + pushNotifications.on('received-apns-notification', (event, userInfo) => { + if ( + typeof userInfo.title !== 'string' || + typeof userInfo.body !== 'string' || + typeof userInfo.threadID !== 'string' + ) { + console.error( + 'Notification must contain a string title, body and threadID', + ); + return; + } + const { title, body, threadID } = userInfo; + + const notif = new Notification({ + title, + body, + }); + notif.on('click', () => { + handleClick(threadID); + }); + notif.show(); + }); +} + +export { listenForNotifications, registerForNotifications };