electron#IpcMain TypeScript Examples

The following examples show how to use electron#IpcMain. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
constructor(window: BrowserWindow) {
        // This won't work in dev-mode because it checks Electron's Version
        this.currentVersion = app.getVersion();
        this.isOpen = false;
        this.window = window;

        // Correct current version if needed
        if (this.currentVersion.split(".").length > 3) {
            this.currentVersion = semver.coerce(this.currentVersion).format();
        }

        const autoUpdate = Server().repo.getConfig("auto_install_updates") as boolean;
        if (autoUpdate) {
            autoUpdater.autoDownload = true;
            autoUpdater.autoInstallOnAppQuit = true;
        } else {
            autoUpdater.autoDownload = false;
            autoUpdater.autoInstallOnAppQuit = false;
        }

        autoUpdater.on("update-downloaded", info => {
            Server().log("Installing update...");
            autoUpdater.quitAndInstall(false, true);
        });

        ipcMain.handle("install-update", async (_, __) => {
            Server().log("Downloading update...");
            await autoUpdater.downloadUpdate();
            Server().log("Finished downloading update...");
        });
    }
Example #2
Source File: theme.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
constructor(ipc: IpcMain) {
    this.ipc = ipc;

    let autoTheme = false;
    try {
      autoTheme = JSON.parse(
        JSON.parse(electronStore.get('persist:root') as string).settings
      ).autoTheme;
    } catch(error) {} finally {
      if (autoTheme) {
        this.listenForUpdate();
      }
    }
  }
Example #3
Source File: index.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
public async setWikiLanguage(view: BrowserView, workspaceID: string, tiddlywikiLanguageName: string): Promise<void> {
    const twLanguageUpdateTimeout = 15_000;
    const retryTime = 2000;
    return await new Promise<void>((resolve, reject) => {
      const onRetryOrDo = (): void => {
        view.webContents.send(WikiChannel.setTiddlerText, '$:/language', tiddlywikiLanguageName, workspaceID);
      };
      const intervalHandle = setInterval(onRetryOrDo, retryTime);
      const onTimeout = (): void => {
        ipcMain.removeListener(WikiChannel.setTiddlerTextDone + workspaceID, onDone);
        clearInterval(intervalHandle);
        const errorMessage = `setWikiLanguage("${tiddlywikiLanguageName}"), language "${tiddlywikiLanguageName}" in workspaceID ${workspaceID} is too slow to update after ${twLanguageUpdateTimeout}ms.`;
        logger.error(errorMessage);
        reject(new Error(errorMessage));
      };
      const timeoutHandle = setTimeout(onTimeout, twLanguageUpdateTimeout);
      const onDone = (): void => {
        clearTimeout(timeoutHandle);
        clearInterval(intervalHandle);
        resolve();
      };
      ipcMain.once(WikiChannel.setTiddlerTextDone + workspaceID, onDone);
      onRetryOrDo();
    });
  }
Example #4
Source File: main.ts    From Account-Manager with MIT License 6 votes vote down vote up
ipcMain.on(IpcChannel.restartApp, (event) => {
  try {
    console.log('Trying to restart app');
    mainWindow.webContents.reloadIgnoringCache();
    setTimeout(() => {
      event.reply(getSuccessChannel(IpcChannel.restartApp));
    }, 1000);
  } catch (error) {
    console.log('Failed to restart app', error);
    setTimeout(() => {
      event.reply(getFailChannel(IpcChannel.restartApp), error.toString());
    }, 1000);
  }
});
Example #5
Source File: code-runner.ts    From electron-playground with MIT License 6 votes vote down vote up
// 在主进程执行electron的代码
export function addCodeRunnerListener() {
  ipcMain.on('ACTION_CODE', (event: IpcMainEvent, fnStr: string) => {
    try {
      const mockConsole = new MockConsole()
      const fn = new Function(
        'exports',
        'require',
        'module',
        '__filename',
        '__dirname',
        'console',
        `return function(){
              try{
                ${fnStr}
              }catch(error){
                console.error('程序执行错误',error)
              }
             }`,
      )(exports, nativeRequire, module, __filename, __dirname, mockConsole)
      const result = fn()
      if (result) {
        mockConsole.log(result)
      }
      event.returnValue = mockConsole.logs
    } catch (err) {
      console.log('执行动态代码错误', err)
    }
  })
}
Example #6
Source File: utils.ts    From MagicUI with Apache License 2.0 6 votes vote down vote up
onMinimizeWidget = (callback: CallbackType) => {
  ipcMain.on(IpcEvent.MINIMIZE, callback);
}
Example #7
Source File: chat.ts    From sapio-studio with Mozilla Public License 2.0 6 votes vote down vote up
export function setup_chat() {
    ipcMain.handle('chat::init', async (event) => {
        if (g_chat_server) return;
        const privateKey = ed.utils.randomPrivateKey();
        const publicKey = await ed.getPublicKey(privateKey);
        g_chat_server = new ChatServer(privateKey, publicKey);
    });
    ipcMain.handle('chat::send', async (event, message: EnvelopeIn) => {
        if (!g_chat_server) return;
        return g_chat_server.send_message(message);
    });
    ipcMain.handle('chat::add_user', (event, name: string, key: string) => {
        if (!g_chat_server) return;
        return g_chat_server.add_user(name, key);
    });
    ipcMain.handle('chat::list_users', (event) => {
        if (!g_chat_server) return;
        return g_chat_server.list_users();
    });
    ipcMain.handle('chat::list_channels', (event) => {
        if (!g_chat_server) return;
        return g_chat_server.list_channels();
    });
    ipcMain.handle('chat::list_messages_channel', (event, channel, since) => {
        if (!g_chat_server) return;
        return g_chat_server.list_messages_channel(channel, since);
    });
}
Example #8
Source File: chrome-webNavigation-spec.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
describe('chrome.webNavigation', () => {
  const server = useServer()
  const browser = useExtensionBrowser({ url: server.getUrl, extensionName: 'chrome-webNavigation' })

  // TODO: for some reason 'onCommitted' will sometimes not arrive
  it.skip('emits events in the correct order', async () => {
    const expectedEventLog = [
      'onBeforeNavigate',
      'onCommitted',
      'onDOMContentLoaded',
      'onCompleted',
    ]

    const eventsPromise = new Promise((resolve) => {
      const eventLog: string[] = []
      ipcMain.on('logEvent', (e, eventName) => {
        if (eventLog.length === 0 && eventName !== 'onBeforeNavigate') {
          // ignore events that come in late from initial load
          return
        }

        eventLog.push(eventName)

        if (eventLog.length === expectedEventLog.length) {
          resolve(eventLog)
        }
      })
    })

    await browser.window.webContents.loadURL(`${server.getUrl()}`)

    const eventLog = await eventsPromise
    expect(eventLog).to.deep.equal(expectedEventLog)
  })
})
Example #9
Source File: hook.ts    From CrewLink with GNU General Public License v3.0 6 votes vote down vote up
ipcMain.on(IpcSyncMessages.GET_INITIAL_STATE, (event) => {
	if (!readingGame) {
		console.error(
			'Recieved GET_INITIAL_STATE message before the START_HOOK message was received'
		);
		event.returnValue = null;
		return;
	}
	event.returnValue = gameReader.lastState;
});
Example #10
Source File: channels.ts    From SeeQR with MIT License 6 votes vote down vote up
// Run query passed from the front-end, and send back an updated DB List
// DB will rollback if query is unsuccessful
ipcMain.handle(
  'update-db',
  async (event, { sqlString, selectedDb }: UpdatePayload) => {
    event.sender.send('async-started');
    try {
      let error: string | undefined;
      // connect to db to run query
      await db.connectToDB(selectedDb);

      // Run Query
      // let returnedRows;
      try {
        await db.query(sqlString);
      } catch (e) {
        if (e) throw new Error('Failed to update schema');
      }
    } finally {
      // send updated db info in case query affected table or database information
      // must be run after we connect back to the originally selected so tables information is accurate
      const dbsAndTables: DBList = await db.getLists();
      event.sender.send('db-lists', dbsAndTables);

      event.sender.send('async-complete');
    }
  }
);
Example #11
Source File: electron.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
/* -------------- electron life cycle -------------- */

app.on("ready", async () => {
  let mainProfiler: any;

  electronApp.afterReady(app, (err, app) => { if (err) console.log(err); });
  electronApp.ready(app);
  isInspect && (mainProfiler = await startProfiler('main', 5222));
  ipcMainProcess = new IpcMainProcess(ipcMain);
  await setupAfterInstall(true);

  ipcMainWindow = new IpcMainWindow({
    width: 460,
    height: 540
  });

  ipcMainWindow.create().then((win: BrowserWindow) => {
    (global as any).win = win;
    if (isDev) {
      win.webContents.openDevTools({ mode: 'undocked' });
      ProcessManager.openWindow();
    }
    setMainWindow(win);
  });

  ipcMainWindow.createTray();

  !isDev && autoUpdater.checkForUpdatesAndNotify();
  isInspect && setTimeout(() => { mainProfiler?.stop(); }, 5e3);

  electronApp.registryHooksSync('beforeQuit', 'ipcMainWindowActions', () => {
    ipcMainWindow.beforeQuitting();
  });

});
Example #12
Source File: ipc.ts    From Aragorn with MIT License 6 votes vote down vote up
protected fileManageHandle() {
    ipcMain.on('file-list-get', (_, uploaderProfileId: string, directoryPath?: string) => {
      this.uploaderManager.getFileList(uploaderProfileId, directoryPath);
    });

    ipcMain.on('file-delete', (_, uploaderProfileId: string, fileNames: string[]) => {
      this.uploaderManager.deleteFile(uploaderProfileId, fileNames);
    });

    ipcMain.on('file-upload', (_, uploaderProfileId: string, filesPath: string[], directoryPath?: string) => {
      this.uploaderManager.upload({
        files: filesPath,
        customUploaderProfileId: uploaderProfileId,
        directoryPath,
        isFromFileManage: true
      });
    });

    ipcMain.on('directory-create', (_, uploaderProfileId: string, directoryPath: string) => {
      this.uploaderManager.createDirectory(uploaderProfileId, directoryPath);
    });

    ipcMain.on('file-download', (_, name: string, url: string) => {
      this.uploaderManager.download(name, url);
    });

    ipcMain.on('export', (_, data) => {
      this.uploaderManager.export(data);
    });
  }
Example #13
Source File: push.ts    From mysterium-vpn-desktop with MIT License 6 votes vote down vote up
initialize = (): void => {
    Pushy.listen()
    Pushy.register({ appId: packageJson.pushyAppId })
        .then((deviceToken: string) => {
            // Display an alert with device token
            log.info("Pushy device token:", deviceToken)
        })
        .catch((err: Error) => {
            // Display error dialog
            log.error("Pushy registration error", err.message)
        })
    Pushy.setNotificationListener(listener)
    ipcMain.on(MainIpcListenChannels.PushSubscribe, (evt, pushTopic) => {
        if (Pushy.isRegistered()) {
            const qualifiedTopic = "desktop." + pushTopic
            log.info("Subscribing to:", qualifiedTopic)
            Pushy.subscribe(qualifiedTopic)
        }
    })
    ipcMain.on(MainIpcListenChannels.PushUnsubscribe, (evt, pushTopic) => {
        if (Pushy.isRegistered()) {
            const qualifiedTopic = "desktop." + pushTopic
            log.info("Unsubscribing from:", qualifiedTopic)
            Pushy.unsubscribe(qualifiedTopic)
        }
    })
}
Example #14
Source File: background.ts    From nodemaker with MIT License 6 votes vote down vote up
/**Registers all the IPC channels for handling requests from the renderer process.*/
  private async registerIpcChannels() {
    const ipcChannels: IpcChannel[] = [];

    for (let module of this.getChannelModules()) {
      const ChannelClass = require(`../channels/${module}`).default; // dynamic import
      ipcChannels.push(new ChannelClass());
    }

    ipcChannels.forEach((channel) =>
      ipcMain.on(channel.name, (event, argument?: any) =>
        channel.handle(event, argument)
      )
    );
  }
Example #15
Source File: App.ts    From YoutubeLiveApp with MIT License 6 votes vote down vote up
private registIPCEventListeners() {
    ipcMain.on(IPCEvent.InitialState.CHANNEL_NAME_FROM_PRELOAD, (event) => {
      event.sender.send(IPCEvent.InitialState.CHANNEL_NAME_FROM_MAIN, this.store?.getState());
    });
    ipcMain.on(IPCEvent.StateChanged.CHANNEL_NAME_FROM_PRELOAD, (_, action: Action<AppState>) => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      this.store?.dispatch(action as any);
    });
    ipcMain.on(IPCEvent.BouyomiChan.SPEAK_BOUYOMICHAN_FROM_PRELOAD, (_, chatInfo: ChatInfo) => {
      this.bouyomiChan.speak(`${chatInfo.author} ${chatInfo.message}`);
    });
  }
Example #16
Source File: telemetry.ts    From desktop with MIT License 6 votes vote down vote up
export function initializeTelemetry(): void {
  setDefaultComponentId(`gatsby-desktop`)
  setGatsbyCliVersion(app.getVersion())
  startBackgroundUpdate()
  store = new Store<IConfigType>()

  const telemetryEnabled = store.get(`telemetryOptIn`)

  if (telemetryEnabled === false) {
    console.log(`running with telemetry disabled`)
    trackCli(`RUNNING_WITH_TELEMETRY_DISABLED`)
  } else {
    trackCli(`GATSBY_DESKTOP_STARTED`)
    console.log(`telemetry enabled or not chosen`, { telemetryEnabled })
  }
  ipcMain.on(
    `telemetry-trackFeatureIsUsed`,
    (event: IpcMainEvent, name: string): void =>
      telemetryTrackFeatureIsUsed(name)
  )
  ipcMain.on(
    `telemetry-trackEvent`,
    (
      event: IpcMainEvent,
      input: string | Array<string>,
      tags?: ITelemetryTagsPayload
    ): void => trackEvent(input, tags)
  )
}
Example #17
Source File: index.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
ipcMain.on('update-rpc-permission', (_, allowed: boolean) => {
    if (allowed) {
        client.setActivity({
            largeImageKey: 'ace-icon-large',
            state: 'Idling',
        });
    } else {
        client.clearActivity();
    }
});
Example #18
Source File: main.ts    From EXOS-Core with MIT License 6 votes vote down vote up
ipcMain.on('get-wallet-seed', (event, arg: string) => {

    writeLog('get-wallet-seed: Send the encrypted seed and chain code to the UI.');

    // TODO: Consider doing this async to avoid UI hanging, but to simplify the integration at the moment and
    // use return value, we rely on sync read.  "readChunk(filePath, startPosition, length)" <- async
    // Read 300 characters, that should be more than enough to get the encryptedSeed. Consider doing a loop until we find it.
    const dataBuffer = readChunk.sync(arg, 1, 500);
    const data = dataBuffer.toString('utf8');

    const key = '"encryptedSeed":"';
    const startIndex = data.indexOf(key);
    const endIndex = data.indexOf('",', startIndex);
    const seed = data.substring(startIndex + key.length, endIndex);

    const keyChainCode = '"chainCode":"';
    const startIndexChainCode = data.indexOf(keyChainCode);
    const endIndexChainCode = data.indexOf('",', startIndexChainCode);
    const chainCode = data.substring(startIndexChainCode + keyChainCode.length, endIndexChainCode);

    // chainCodeDecoded: Buffer.from(chainCode, 'base64')
    event.returnValue = { encryptedSeed: seed, chainCode };
});
Example #19
Source File: main.ts    From blockcore-hub with MIT License 6 votes vote down vote up
// ipcMain.on('get-wallet-seed', (event, arg: string) => {
//     writeLog('get-wallet-seed: Send the encrypted seed and chain code to the UI.');

//     // TODO: Consider doing this async to avoid UI hanging, but to simplify the integration at the moment and
//     // use return value, we rely on sync read.  "readChunk(filePath, startPosition, length)" <- async
//     // Read 300 characters, that should be more than enough to get the encryptedSeed. Consider doing a loop until we find it.
//     const dataBuffer = readChunk.sync(arg, 1, 500);
//     const data = dataBuffer.toString('utf8');

//     const key = '"encryptedSeed":"';
//     const startIndex = data.indexOf(key);
//     const endIndex = data.indexOf('",', startIndex);
//     const seed = data.substring(startIndex + key.length, endIndex);

//     const keyChainCode = '"chainCode":"';
//     const startIndexChainCode = data.indexOf(keyChainCode);
//     const endIndexChainCode = data.indexOf('",', startIndexChainCode);
//     const chainCode = data.substring(startIndexChainCode + keyChainCode.length, endIndexChainCode);

//     // chainCodeDecoded: Buffer.from(chainCode, 'base64')
//     event.returnValue = { encryptedSeed: seed, chainCode };
// });

ipcMain.on('update-icon', (event, arg: { icon, title }) => {
    if (arg) {
        mainWindow.setOverlayIcon(__dirname + arg.icon, arg.title);
    }
    else {
        mainWindow.setOverlayIcon(null, '');
    }
});
Example #20
Source File: window.ts    From noteworthy with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
	 * Wraps window.webContents.send() in a Promise. Expects the render
	 * process to send back a response after handling the message.
	 * 
	 * This is needed because unlike `ipcRenderer`, electron `WebContents`
	 * has no invoke() method for when we expect a message result.  See:
	 *
	 *
	 */
	async invoke<T>(channel:string, ...args:any[]):Promise<T> {
		return new Promise<T>((resolve, reject) => {
			// generate unique id for event
			let responseId = `RENDER_DID_HANDLE::${channel}::${randomId()}`;
			// send message from main --> render
			this.window.webContents.send(channel, responseId, ...args);
			// expect response -- promise won't resolve otherwise
			/** @todo (7/12/20) accept timeout (seconds) as argument? */
			ipcMain.once(responseId, (evt:IpcMainEvent, success:boolean, result:any) => {
				if(success) { resolve(result); }
				else        { reject(result);  }
			});
		});
	}
Example #21
Source File: main.ts    From simulator with Apache License 2.0 6 votes vote down vote up
ipcMain.on('editor/action', (_event, actionName) => {
  const managerInstance = requestManager();
  managerInstance
    .createReqHandler(dataFromParser)
    .then(() => {
      managerInstance.startScenario(actionName);
    })
    .catch((err: any) => {
      console.log(err);
    });
  console.log('Sending to manager');
});
Example #22
Source File: main-store.ts    From kliveide with MIT License 6 votes vote down vote up
/**
   * Initializes the listener that processes responses
   */
  constructor(public readonly window: BrowserWindow) {
    super();
    ipcMain.on(
      this.responseChannel,
      (_ev: IpcMainEvent, response: ResponseMessage) =>
        this.processResponse(response)
    );
  }
Example #23
Source File: ipcApp.ts    From wiregui with MIT License 6 votes vote down vote up
ipcMain.on("check-for-updates", (event) => {
  const request = net.request("https://api.github.com/repos/devsfy/wiregui/releases/latest");
    request.on("response", (response) => {
      response.on("data", (chunk) => {
        if (response.statusCode !== 200) {
          return;
        }

        const body = JSON.parse(chunk.toString());
        if (body.tag_name !== version) {
          event.reply("update-available");
        }
      });
    });
    request.end();
});
Example #24
Source File: MainToEmuForwarder.ts    From kliveide with MIT License 6 votes vote down vote up
/**
   * Initializes the listener that processes responses
   */
  constructor(public readonly window: BrowserWindow) {
    super();
    ipcMain.on(
      this.responseChannel,
      (_ev: IpcMainEvent, response: ResponseMessage) =>
        this.processResponse(response)
    );
  }
Example #25
Source File: background.ts    From project_nodeSnap with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Renderer -> mainThread communication
 */
ipcMain.on("setModalVisibility", (event, arg) => {
    ModalsManager.getInstance().setModalVisibility(
        arg.name,
        arg.state,
        arg.data
    );
});
Example #26
Source File: serverlistpage.ts    From Creators.TF-Community-Launcher with MIT License 6 votes vote down vote up
ipcMain.on("GetServerList", async (event) => {
    try {
        const serverList = await ServerListPage.GetServerList();
        event.reply("GetServerList-Reply", serverList);
    }
    catch (error) {
        event.reply("GetServerList-Reply", error.toString());
    }
});
Example #27
Source File: MainToEmulatorMessenger.ts    From kliveide with MIT License 6 votes vote down vote up
/**
   * Initializes the listener that processes responses
   */
  constructor(public readonly window: BrowserWindow) {
    super();
    ipcMain.on(
      this.responseChannel,
      (_ev: IpcMainEvent, response: ResponseMessage) =>
        this.processResponse(response)
    );
  }
Example #28
Source File: main.ts    From Creators.TF-Community-Launcher with MIT License 6 votes vote down vote up
ipcMain.on("Remove-Mod", async () => {
    if (mod_manager.currentModData != null && (mod_manager.currentModState == "INSTALLED" || mod_manager.currentModState == "UPDATE")) {
        dialog.showMessageBox(Main.mainWindow, {
            type: "warning",
            title: `Remove Mod - ${mod_manager.currentModData.name}`,
            message: `Would you like to uninstall "${mod_manager.currentModData.name}"?`,
            buttons: ["Yes", "Cancel"],
            cancelId: 1
        }).then(async (button) => {
            if (button.response == 0) {
                log.info(`Starting the mod removal process for "${mod_manager.currentModData.name}". User said yes.`);
                await mod_manager.RemoveCurrentMod();
            }
        });
    }
});
Example #29
Source File: MainToIdeMessenger.ts    From kliveide with MIT License 6 votes vote down vote up
/**
   * Initializes the listener that processes responses
   */
  constructor(public readonly window: BrowserWindow) {
    super();
    ipcMain.on(
      this.responseChannel,
      (_ev: IpcMainEvent, response: ResponseMessage) =>
        this.processResponse(response)
    );
  }