electron#Notification TypeScript Examples

The following examples show how to use electron#Notification. 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
async checkForUpdate({ showNoUpdateDialog = false, showUpdateDialog = true } = {}): Promise<boolean> {
        const res = await autoUpdater.checkForUpdates();
        this.hasUpdate = !!res?.updateInfo && semver.lt(this.currentVersion, res.updateInfo.version);
        this.updateInfo = res;

        if (this.hasUpdate) {
            Server().emitMessage("server-update", res.updateInfo.version);
            Server().emitToUI("update-available", res.updateInfo.version);

            if (showUpdateDialog) {
                const notification = {
                    title: "BlueBubbles Update Available!",
                    body: `BlueBubbles macOS Server v${res.updateInfo.version} is now available to be installed!`
                };
                new Notification(notification).show();
            }
        }

        if (!this.hasUpdate && showNoUpdateDialog) {
            const dialogOpts = {
                type: "info",
                title: "BlueBubbles Update",
                message: "You have the latest version installed!",
                detail: `You are running the latest version of BlueBubbles! v${this.currentVersion}`
            };

            dialog.showMessageBox(this.window, dialogOpts);
        }

        return this.hasUpdate;
    }
Example #2
Source File: AppUpdater.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
// noinspection JSUnusedGlobalSymbols
  checkForUpdatesAndNotify(
    downloadNotification?: DownloadNotification
  ): Promise<UpdateCheckResult | null> {
    if (!this.isUpdaterActive()) {
      return Promise.resolve(null);
    }

    return this.checkForUpdates().then(it => {
      const downloadPromise = it && it.downloadPromise;
      if (downloadPromise == null) {
        const debug = this._logger.debug;
        if (debug != null) {
          debug("checkForUpdatesAndNotify called, downloadPromise is null");
        }
        return it;
      }

      downloadPromise.then(() => {
        const notificationContent = this.formatDownloadNotification(
          it ? it.updateInfo.version : "",
          this.app.name,
          downloadNotification
        );
        new Notification(notificationContent).show();
      });

      return it;
    });
  }
Example #3
Source File: push.ts    From mysterium-vpn-desktop with MIT License 6 votes vote down vote up
listener = (data: PushPayload) => {
    log.info("Push notification received: ", JSON.stringify(data))
    const notification = new Notification({
        title: data.title ?? packageJson.productName,
        body: data.message ?? "",
    })
    notification.on("click", () => {
        if (data.url != null) {
            shell.openExternal(data.url)
        }
    })
    notification.show()
}
Example #4
Source File: updater.ts    From Aragorn with MIT License 6 votes vote down vote up
protected sendMessage(channelData: UpdaterChannelData, useSystemNotification: boolean) {
    if (useSystemNotification) {
      const notification = new Notification({ title: channelData.message, body: channelData.description || '' });
      if (channelData.url) {
        notification.on('click', () => {
          shell.openExternal(channelData.url as string);
        });
      }
      notification.show();
    } else {
      Ipc.sendMessage('app-updater-message', channelData);
    }
  }
Example #5
Source File: uploaderManager.ts    From Aragorn with MIT License 6 votes vote down vote up
protected handleBatchUploaded(successFilesCount: number, failFilesCount: number) {
    if (failFilesCount === 0) {
      const notification = new Notification({ title: '批量上传成功', body: `总共${successFilesCount}个文件` });
      notification.show();
    } else if (successFilesCount === 0) {
      const notification = new Notification({ title: '批量上传失败', body: `总共${failFilesCount}个文件` });
      notification.show();
    } else {
      const notification = new Notification({
        title: '批量上传结束',
        body: `成功${successFilesCount}个,失败${failFilesCount}个`
      });
      notification.show();
    }
  }
Example #6
Source File: desktop.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
async openNotification(
    params: { title?: string, body: string, subtitle?: string, urgency?: "normal" | "critical" | "low" | undefined }
  ): Promise<ServiceResult> {
    return new Promise(resolve => {
      new Notification({
        title: params.title ?? 'shadowsocks-electron',
        subtitle: params.subtitle,
        body: params.body,
        urgency: params.urgency ?? 'normal'
      }).show();
    });
  }
Example #7
Source File: uploaderManager.ts    From Aragorn with MIT License 5 votes vote down vote up
protected handleSingleUploaded(successFile: UploadedFileInfo, failFile: UploadedFileInfo) {
    if (successFile) {
      // 根据urlType转换图片链接格式
      let clipboardUrl = successFile.url;
      switch (this.setting.configuration.urlType) {
        case 'URL':
          break;
        case 'HTML':
          clipboardUrl = `<img src="${successFile.url}" />`;
          break;
        case 'Markdown':
          clipboardUrl = `![${successFile.url}](${successFile.url})`;
          break;
        default:
          return successFile.url;
      }
      if (this.setting.configuration.autoCopy) {
        let preClipBoardText = '';
        if (this.setting.configuration.autoRecover) {
          preClipBoardText = clipboard.readText();
        }
        // 开启自动复制
        clipboard.writeText(clipboardUrl || '');
        const notification = new Notification({
          title: '上传成功',
          body: '链接已自动复制到粘贴板',
          silent: !this.setting.configuration.sound
        });
        this.setting.configuration.showNotifaction && notification.show();
        this.setting.configuration.autoRecover &&
          setTimeout(() => {
            clipboard.writeText(preClipBoardText);
            const notification = new Notification({
              title: '粘贴板已恢复',
              body: '已自动恢复上次粘贴板中的内容',
              silent: !this.setting.configuration.sound
            });
            notification.show();
          }, 5000);
      } else {
        const notification = new Notification({
          title: '上传成功',
          body: clipboardUrl || '',
          silent: !this.setting.configuration.sound
        });
        this.setting.configuration.showNotifaction && notification.show();
      }
    } else {
      const notification = new Notification({ title: '上传失败', body: failFile.errorMessage || '错误未捕获' });
      notification.show();
    }
  }
Example #8
Source File: notifications.ts    From electron-browser-shell with GNU General Public License v3.0 5 votes vote down vote up
private registry = new Map<string, Notification>()
Example #9
Source File: notifications.ts    From electron-browser-shell with GNU General Public License v3.0 5 votes vote down vote up
private create = async ({ extension }: ExtensionEvent, arg1: unknown, arg2?: unknown) => {
    let id: string
    let opts: chrome.notifications.NotificationOptions

    if (typeof arg1 === 'object') {
      id = 'guid' // TODO: generate uuid
      opts = arg1 as chrome.notifications.NotificationOptions
    } else if (typeof arg1 === 'string') {
      id = arg1
      opts = arg2 as chrome.notifications.NotificationOptions
    } else {
      throw new Error('Invalid arguments')
    }

    if (typeof opts !== 'object' || !opts.type || !opts.iconUrl || !opts.title || !opts.message) {
      throw new Error('Missing required notification options')
    }

    const notificationId = createScopedIdentifier(extension, id)

    if (this.registry.has(notificationId)) {
      this.registry.get(notificationId)?.close()
    }

    let icon

    if (opts.iconUrl) {
      let url
      try {
        url = new URL(opts.iconUrl)
      } catch {}

      if (url?.protocol === 'data:') {
        icon = opts.iconUrl
      } else {
        icon = await validateExtensionResource(extension, opts.iconUrl)
      }

      if (!icon) {
        throw new Error('Invalid iconUrl')
      }
    }

    // TODO: buttons, template types

    const notification = new Notification({
      title: opts.title,
      subtitle: app.name,
      body: getBody(opts),
      silent: opts.silent,
      icon,
      urgency: getUrgency(opts.priority),
      timeoutType: opts.requireInteraction ? 'never' : 'default',
    })

    this.registry.set(notificationId, notification)

    notification.on('click', () => {
      this.ctx.router.sendEvent(extension.id, 'notifications.onClicked', id)
    })

    notification.once('close', () => {
      const byUser = true // TODO
      this.ctx.router.sendEvent(extension.id, 'notifications.onClosed', id, byUser)
      this.registry.delete(notificationId)
    })

    notification.show()

    return id
  }
Example #10
Source File: notifications.ts    From electron-browser-shell with GNU General Public License v3.0 5 votes vote down vote up
private getPermissionLevel = (event: ExtensionEvent) => {
    return Notification.isSupported() ? 'granted' : 'denied'
  }
Example #11
Source File: index.ts    From TidGi-Desktop with Mozilla Public License 2.0 5 votes vote down vote up
public async show(options: NotificationConstructorOptions): Promise<void> {
    if (Notification.isSupported()) {
      const notification = new Notification(options);
      notification.show();
    }
  }
Example #12
Source File: uploaderManager.ts    From Aragorn with MIT License 4 votes vote down vote up
async upload(uploadOptions: UploadOptions) {
    try {
      console.log('upload start');
      const { files, customUploaderProfileId, directoryPath, isFromFileManage, testProfile, isTest } = uploadOptions;
      const {
        configuration: { defaultUploaderProfileId, proxy, rename, renameFormat }
      } = this.setting;
      const uploaderProfiles = this.uploaderProfileManager.getAll();
      let uploaderProfile: UploaderProfile | undefined;

      if (isTest) {
        uploaderProfile = testProfile;
      } else {
        uploaderProfile = uploaderProfiles.find(
          uploaderProfile => uploaderProfile.id === (customUploaderProfileId || defaultUploaderProfileId)
        );
      }

      if (!uploaderProfile) {
        let notification;
        if (customUploaderProfileId) {
          console.warn('upload failed: no uploader profile');
          notification = new Notification({ title: '上传操作异常', body: `上传器配置不存在` });
        } else {
          console.warn('upload failed: no default uploader profile');
          const message = uploaderProfiles.length > 0 ? '请配置默认的上传器' : '请添加上传器配置';
          notification = new Notification({ title: '上传操作异常', body: message });
        }
        notification.show();
        return false;
      }

      const uploader = this.core.getUploaderByName(uploaderProfile.uploaderName);

      if (!uploader) {
        console.warn('upload failed: not found uploader');
        const message = `没有找到${uploaderProfile.uploaderName}上传器`;
        const notification = new Notification({ title: '上传操作异常', body: message });
        notification.show();
        return false;
      }

      uploader.changeOptions(uploaderProfile.uploaderOptions, proxy);

      const successRes: UploadedFileInfo[] = [];
      const failRes: UploadedFileInfo[] = [];

      const uploadQuence = [] as any[];

      const toUpload = async (file: string | FileFormData, index: number, uploadQuence: any[]) => {
        const fileName = this.core.getFileNameByFormat(
          typeof file === 'string' ? file : file.originalname,
          rename,
          renameFormat,
          isFromFileManage
        );
        const fileType = typeof file === 'string' ? mime.lookup(file) || '-' : file.mimetype;
        const baseInfo = {
          id: uuidv4(),
          name: path.basename(fileName),
          type: fileType,
          path: typeof file === 'string' ? file : '',
          date: new Date().getTime(),
          uploaderProfileId: uploaderProfile?.id || ''
        };

        if (uploader.batchUploadMode === 'Sequence' && index > 0) {
          await uploadQuence[index - 1];
        }

        const res = await uploader.upload({
          file: typeof file === 'string' ? file : file.buffer,
          fileName,
          directoryPath,
          isFromFileManage
        });
        if (res.success) {
          successRes.push({ ...baseInfo, ...res.data });
        } else {
          failRes.push({ ...baseInfo, errorMessage: res.desc });
        }
      };

      const promises = files.map((file, index) => {
        const res = toUpload(file, index, uploadQuence);
        uploadQuence.push(res);
        return res;
      });

      await Promise.all(promises);

      this.handleAddHistory([...failRes, ...successRes]);

      if (isFromFileManage) {
        Ipc.sendMessage('file-upload-reply');
      }

      if (isTest) {
        Ipc.sendMessage('uploader-profile-test-reply', successRes.length > 0);
      }

      if (files.length > 1) {
        this.handleBatchUploaded(successRes.length, failRes.length);
      } else {
        this.handleSingleUploaded(successRes[0], failRes[0]);
      }

      console.log('upload finish');

      return successRes;
    } catch (err) {
      console.error(`upload error: ${err.message}`);
      if (uploadOptions.isTest) {
        Ipc.sendMessage('uploader-profile-test-reply', false);
      }
      const notification = new Notification({ title: '上传操作异常', body: err.message });
      notification.show();
    }
  }