Whalebird-desktop-client-ma.../src/main/index.ts

1512 lines
43 KiB
TypeScript
Raw Normal View History

2018-03-07 14:28:48 +01:00
'use strict'
2019-04-20 08:44:22 +02:00
import {
app,
ipcMain,
shell,
session,
2019-04-20 08:44:22 +02:00
Menu,
Tray,
BrowserWindow,
BrowserWindowConstructorOptions,
MenuItemConstructorOptions,
2019-10-23 16:07:20 +02:00
IpcMainEvent,
Notification,
2020-02-05 17:16:29 +01:00
NotificationConstructorOptions,
nativeTheme,
IpcMainInvokeEvent
2019-04-20 08:44:22 +02:00
} from 'electron'
2018-03-08 15:08:33 +01:00
import Datastore from 'nedb'
2019-04-16 13:38:02 +02:00
import { isEmpty } from 'lodash'
import log from 'electron-log'
2018-03-24 15:23:25 +01:00
import windowStateKeeper from 'electron-window-state'
import simplayer from 'simplayer'
import path from 'path'
2018-06-01 07:19:56 +02:00
import ContextMenu from 'electron-context-menu'
import { initSplashScreen, Config } from '@trodi/electron-splashscreen'
2018-08-10 17:40:06 +02:00
import openAboutWindow from 'about-window'
import { Entity, detector, NotificationType } from 'megalodon'
import sanitizeHtml from 'sanitize-html'
2019-09-23 12:31:25 +02:00
import AutoLaunch from 'auto-launch'
import minimist from 'minimist'
2018-03-08 15:08:33 +01:00
import pkg from '~/package.json'
2018-03-08 09:41:39 +01:00
import Authentication from './auth'
import Account from './account'
2020-03-15 09:47:40 +01:00
import { StreamingURL, UserStreaming, DirectStreaming, LocalStreaming, PublicStreaming, ListStreaming, TagStreaming } from './websocket'
import Preferences from './preferences'
2018-09-25 18:02:36 +02:00
import Fonts from './fonts'
2018-06-01 07:19:56 +02:00
import Hashtags from './hashtags'
import UnreadNotification from './unreadNotification'
2020-01-11 13:48:22 +01:00
import i18next from '~/src/config/i18n'
import { i18n as I18n } from 'i18next'
import Language, { LanguageType } from '../constants/language'
import { LocalAccount } from '~/src/types/localAccount'
import { LocalTag } from '~/src/types/localTag'
import { UnreadNotification as UnreadNotificationConfig } from '~/src/types/unreadNotification'
import { Notify } from '~/src/types/notify'
import { StreamingError } from '~/src/errors/streamingError'
2019-07-30 17:17:30 +02:00
import HashtagCache from './cache/hashtag'
2019-08-08 16:39:27 +02:00
import AccountCache from './cache/account'
import { InsertAccountCache } from '~/src/types/insertAccountCache'
import { Proxy } from '~/src/types/proxy'
import ProxyConfiguration from './proxy'
import confirm from './timelines'
import { EnabledTimelines } from '~/src/types/enabledTimelines'
import { Menu as MenuPreferences } from '~/src/types/preference'
2018-05-30 13:54:21 +02:00
/**
* Context menu
*/
ContextMenu({
showCopyImageAddress: true,
showSaveImageAs: true
})
2018-03-07 14:28:48 +01:00
/**
* Set log level
*/
log.transports.console.level = 'debug'
log.transports.file.level = 'info'
declare namespace global {
let __static: string
}
2018-03-07 14:28:48 +01:00
/**
* Set `__static` path to static files in production
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
*/
if (process.env.NODE_ENV !== 'development') {
global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
2018-03-07 14:28:48 +01:00
}
let mainWindow: BrowserWindow | null
let tray: Tray | null
2020-11-30 14:50:31 +01:00
const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:9080` : path.join('file://', __dirname, '/index.html')
2018-03-07 14:28:48 +01:00
// MAS build is not allowed requestSingleInstanceLock.
// ref: https://github.com/h3poteto/whalebird-desktop/issues/1030
// ref: https://github.com/electron/electron-osx-sign/issues/137#issuecomment-307626305
if (process.platform !== 'darwin') {
// Enforces single instance for linux and windows.
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', () => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore()
if (!mainWindow!.isVisible()) {
mainWindow!.show()
mainWindow!.setSkipTaskbar(false)
}
mainWindow.focus()
}
})
}
}
const appId = pkg.build.appId
2019-04-20 08:44:22 +02:00
const splashURL =
process.env.NODE_ENV === 'development'
? path.resolve(__dirname, '../../static/splash-screen.html')
2020-11-30 14:50:31 +01:00
: path.join(__dirname, '/static/splash-screen.html')
2018-03-22 08:55:58 +01:00
// https://github.com/louischatriot/nedb/issues/459
2018-03-22 08:49:39 +01:00
const userData = app.getPath('userData')
2019-09-23 12:31:25 +02:00
const appPath = app.getPath('exe')
2019-04-20 08:44:22 +02:00
const accountDBPath = process.env.NODE_ENV === 'production' ? userData + '/db/account.db' : 'account.db'
2020-05-17 09:31:37 +02:00
const accountDB = new Datastore({
filename: accountDBPath,
2018-03-08 15:08:33 +01:00
autoload: true
})
const accountManager = new Account(accountDB)
2019-04-20 08:44:22 +02:00
accountManager.initialize().catch((err: Error) => log.error(err))
2019-04-20 08:44:22 +02:00
const hashtagsDBPath = process.env.NODE_ENV === 'production' ? userData + '/db/hashtags.db' : 'hashtags.db'
2020-05-17 09:31:37 +02:00
const hashtagsDB = new Datastore({
2018-06-01 07:19:56 +02:00
filename: hashtagsDBPath,
autoload: true
})
2019-04-20 08:44:22 +02:00
const unreadNotificationDBPath = process.env.NODE_ENV === 'production' ? userData + '/db/unread_notification.db' : 'unread_notification.db'
const unreadNotification = new UnreadNotification(unreadNotificationDBPath)
2019-04-20 08:44:22 +02:00
unreadNotification.initialize().catch((err: Error) => log.error(err))
2019-04-20 08:44:22 +02:00
const preferencesDBPath = process.env.NODE_ENV === 'production' ? userData + './db/preferences.json' : 'preferences.json'
2018-03-08 15:08:33 +01:00
2019-07-30 17:17:30 +02:00
/**
* Cache path
*/
const hashtagCachePath = process.env.NODE_ENV === 'production' ? userData + '/cache/hashtag.db' : 'cache/hashtag.db'
2019-07-31 17:40:28 +02:00
const hashtagCache = new HashtagCache(hashtagCachePath)
2019-07-30 17:17:30 +02:00
2019-08-08 16:39:27 +02:00
const accountCachePath = process.env.NODE_ENV === 'production' ? userData + '/cache/account.db' : 'cache/account.db'
const accountCache = new AccountCache(accountCachePath)
2019-04-20 08:44:22 +02:00
const soundBasePath =
process.env.NODE_ENV === 'development' ? path.join(__dirname, '../../build/sounds/') : path.join(process.resourcesPath!, 'build/sounds/')
let launcher: AutoLaunch | null = null
const proxyConfiguration = new ProxyConfiguration(preferencesDBPath)
// On MAS build, auto launch is not working.
// We have to use Launch Agent: https://github.com/Teamwork/node-auto-launch/issues/43
// But it is too difficult to build, and Slack does not provide this function in MAS build.
// Therefore I don't provide this function for MacOS.
if (process.platform !== 'darwin') {
launcher = new AutoLaunch({
name: 'Whalebird',
path: appPath
})
}
2019-04-20 08:44:22 +02:00
async function listAccounts(): Promise<Array<LocalAccount>> {
2018-03-21 04:22:45 +01:00
try {
const accounts = await accountManager.listAccounts()
2018-03-21 04:22:45 +01:00
return accounts
} catch (err) {
return []
}
}
2019-04-20 08:44:22 +02:00
async function changeAccount(account: LocalAccount, index: number) {
// Sometimes application is closed to tray.
// In this time, mainWindow in not exist, so we have to create window.
if (mainWindow === null) {
await createWindow()
// We have to wait the web contents is loaded.
mainWindow!.webContents.on('did-finish-load', () => {
mainWindow!.webContents.send('change-account', Object.assign(account, { index: index }))
})
} else {
mainWindow.show()
mainWindow.webContents.send('change-account', Object.assign(account, { index: index }))
}
}
2019-04-20 08:44:22 +02:00
async function getLanguage() {
try {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.load()
return conf.language.language
} catch (err) {
log.warn(err)
return Language.en.key
}
}
const getSpellChecker = async (): Promise<boolean> => {
try {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.load()
return conf.language.spellchecker.enabled
} catch (err) {
return true
}
}
const getMenuPreferences = async (): Promise<MenuPreferences> => {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.load()
return conf.menu
}
2019-04-20 08:44:22 +02:00
async function createWindow() {
/**
2018-03-21 04:22:45 +01:00
* List accounts
*/
const accounts = await listAccounts()
2019-04-17 12:52:01 +02:00
const accountsChange: Array<MenuItemConstructorOptions> = accounts.map((a, index) => {
return {
label: a.domain,
accelerator: `CmdOrCtrl+${index + 1}`,
click: () => changeAccount(a, index)
}
})
/**
* Get language
*/
const language = await getLanguage()
2020-01-11 13:48:22 +01:00
i18next.changeLanguage(language)
/**
* Get spellcheck
*/
const spellcheck = await getSpellChecker()
2020-02-05 17:16:29 +01:00
/**
* Load system theme color for dark mode
*/
nativeTheme.themeSource = 'system'
/**
* Set application menu
*/
const menuPreferences = await getMenuPreferences()
const menu = ApplicationMenu(accountsChange, menuPreferences, i18next)
Menu.setApplicationMenu(menu)
let autoHideMenuBar = false
if (menuPreferences.autoHideMenu) {
autoHideMenuBar = true
}
/**
* Set dock menu for mac
*/
2018-07-21 07:29:52 +02:00
if (process.platform === 'darwin') {
const dockMenu = Menu.buildFromTemplate(accountsChange)
app.dock.setMenu(dockMenu)
}
/**
* Windows10 don't notify, so we have to set appId
* https://github.com/electron/electron/issues/10864
*/
app.setAppUserModelId(appId)
2019-03-10 13:07:19 +01:00
/**
* Enable accessibility
*/
2019-10-23 16:07:20 +02:00
app.accessibilitySupportEnabled = true
2019-03-10 13:07:19 +01:00
/**
* Initial window options
*/
2020-05-17 09:31:37 +02:00
const mainWindowState = windowStateKeeper({
defaultWidth: 1000,
defaultHeight: 563
})
const mainOpts: BrowserWindowConstructorOptions = {
titleBarStyle: 'hidden',
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
backgroundColor: '#fff',
useContentSize: true,
icon: path.resolve(__dirname, '../../build/icons/256x256.png'),
autoHideMenuBar: autoHideMenuBar,
webPreferences: {
// It is required to use ipcRenderer in renderer process.
// But it is not secure, so if you want to disable this option, please use preload script.
nodeIntegration: true,
contextIsolation: false,
2020-06-09 15:47:21 +02:00
preload: path.resolve(__dirname, './preload.js'),
spellcheck: spellcheck
}
}
const config: Config = {
windowOpts: mainOpts,
templateUrl: splashURL,
splashScreenOpts: {
width: 425,
height: 325
}
}
mainWindow = initSplashScreen(config)
2018-03-07 14:28:48 +01:00
mainWindowState.manage(mainWindow)
2018-07-28 13:44:16 +02:00
/**
* Get system proxy configuration.
*/
if (session && session.defaultSession) {
2020-02-05 15:46:17 +01:00
const proxyInfo = await session.defaultSession.resolveProxy('https://mastodon.social')
proxyConfiguration.setSystemProxy(proxyInfo)
log.info(`System proxy configuration: ${proxyInfo}`)
}
/**
* Set proxy for BrowserWindow
*/
const proxyConfig = await proxyConfiguration.forMastodon()
if (proxyConfig) {
await mainWindow.webContents.session.setProxy({ proxyRules: `${proxyConfig.protocol}://${proxyConfig.host}:${proxyConfig.port}` })
}
mainWindow.loadURL(winURL)
mainWindow.webContents.on('will-navigate', event => event.preventDefault())
// Show tray icon only linux and windows.
if (process.platform !== 'darwin') {
// Show tray icon
2019-08-18 06:47:09 +02:00
tray = new Tray(path.join(__dirname, '../../build/icons/tray_icon.png'))
2020-01-11 13:48:22 +01:00
const trayMenu = TrayMenu(accountsChange, i18next)
tray.setContextMenu(trayMenu)
// For Windows
2020-01-11 13:48:22 +01:00
tray.setToolTip(i18next.t('main_menu.application.name'))
tray.on('click', () => {
if (mainWindow!.isVisible()) {
mainWindow!.hide()
mainWindow!.setSkipTaskbar(true)
} else {
mainWindow!.show()
mainWindow!.setSkipTaskbar(false)
}
})
// Minimize to tray
mainWindow.on('close', event => {
mainWindow!.hide()
mainWindow!.setSkipTaskbar(true)
event.preventDefault()
})
} else {
mainWindow.on('closed', () => {
mainWindow = null
})
}
2018-03-07 14:28:48 +01:00
}
// Parse command line arguments and show help command.
const args = minimist(process.argv.slice(process.env.NODE_ENV === 'development' ? 2 : 1))
if (args.help) {
console.log(`
Whalebird is Mastodon, Pleroma and Misskey client for desktop.
Usage
$ whalebird
Options
--help show help
`)
process.exit(0)
}
// Do not lower the rendering priority of Chromium when background
app.commandLine.appendSwitch('disable-renderer-backgrounding')
2018-03-07 14:28:48 +01:00
app.on('ready', createWindow)
app.on('window-all-closed', () => {
// this action is called when user click the close button.
// In macOS, close button does not shutdown application. It is hide application window.
if (process.platform !== 'darwin') {
app.quit()
} else {
// In MacOS, we should change disable some menu items.
const menu = Menu.getApplicationMenu()
2020-02-05 15:46:17 +01:00
if (menu) {
if (menu.items[0].submenu) {
// Preferences
menu.items[0].submenu.items[2].enabled = false
}
if (menu.items[1].submenu) {
// New Toot
menu.items[1].submenu.items[0].enabled = false
}
if (menu.items[4].submenu) {
// Open Window
menu.items[4].submenu.items[1].enabled = true
// Jump to
menu.items[4].submenu.items[4].enabled = false
}
}
}
2018-03-07 14:28:48 +01:00
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
2020-05-17 09:31:37 +02:00
const auth = new Authentication(accountManager)
2018-03-08 09:41:39 +01:00
type AuthRequest = {
instance: string
sns: 'mastodon' | 'pleroma' | 'misskey'
}
ipcMain.handle('get-auth-url', async (_: IpcMainInvokeEvent, request: AuthRequest) => {
const proxy = await proxyConfiguration.forMastodon()
const url = await auth.getAuthorizationUrl(request.sns, request.instance, proxy)
log.debug(url)
// Open authorize url in default browser.
shell.openExternal(url)
return url
2018-03-08 09:41:39 +01:00
})
type TokenRequest = {
code: string | null
sns: 'mastodon' | 'pleroma' | 'misskey'
}
ipcMain.handle('get-access-token', async (_: IpcMainInvokeEvent, request: TokenRequest) => {
const proxy = await proxyConfiguration.forMastodon()
const token = await auth.getAccessToken(request.sns, request.code, proxy)
return new Promise((resolve, reject) => {
accountDB.findOne(
{
accessToken: token
},
(err, doc: any) => {
if (err) return reject(err)
if (isEmpty(doc)) return reject(err)
resolve(doc._id)
}
)
})
2018-03-08 09:41:39 +01:00
})
// nedb
ipcMain.handle('list-accounts', async (_: IpcMainInvokeEvent) => {
const accounts = await accountManager.listAccounts()
return accounts
2018-03-08 15:08:33 +01:00
})
ipcMain.handle('get-local-account', async (_: IpcMainInvokeEvent, id: string) => {
const account = await accountManager.getAccount(id)
return account
2018-03-09 09:36:57 +01:00
})
ipcMain.handle('update-account', async (_: IpcMainInvokeEvent, acct: LocalAccount) => {
const proxy = await proxyConfiguration.forMastodon()
const ac: LocalAccount = await accountManager.refresh(acct, proxy)
return ac
})
ipcMain.handle('remove-account', async (_: IpcMainInvokeEvent, id: string) => {
const accountId = await accountManager.removeAccount(id)
stopUserStreaming(accountId)
})
ipcMain.handle('forward-account', async (_: IpcMainInvokeEvent, acct: LocalAccount) => {
await accountManager.forwardAccount(acct)
2018-04-02 02:07:09 +02:00
})
ipcMain.handle('backward-account', async (_: IpcMainInvokeEvent, acct: LocalAccount) => {
await accountManager.backwardAccount(acct)
})
ipcMain.handle('refresh-accounts', async (_: IpcMainInvokeEvent) => {
const proxy = await proxyConfiguration.forMastodon()
const accounts = await accountManager.refreshAccounts(proxy)
return accounts
})
ipcMain.handle('remove-all-accounts', async (_: IpcMainInvokeEvent) => {
await accountManager.removeAll()
})
ipcMain.handle('change-auto-launch', async (_: IpcMainInvokeEvent, enable: boolean) => {
if (launcher) {
const enabled = await launcher.isEnabled()
if (!enabled && enable && launcher) {
launcher.enable()
} else if (enabled && !enable && launcher) {
launcher.disable()
}
return enable
} else {
return false
}
2019-09-23 12:31:25 +02:00
})
// badge
ipcMain.on('reset-badge', () => {
if (process.platform === 'darwin') {
app.dock.setBadge('')
}
})
ipcMain.handle(
'confirm-timelines',
async (_event: IpcMainInvokeEvent, account: LocalAccount): Promise<EnabledTimelines> => {
const proxy = await proxyConfiguration.forMastodon()
const timelines = await confirm(account, proxy)
return timelines
}
)
// user streaming
2020-05-17 09:31:37 +02:00
const userStreamings: { [key: string]: UserStreaming | null } = {}
2019-10-23 16:07:20 +02:00
ipcMain.on('start-all-user-streamings', (event: IpcMainEvent, accounts: Array<LocalAccount>) => {
accounts.map(async account => {
const id: string = account._id!
try {
const acct = await accountManager.getAccount(id)
// Stop old user streaming
if (userStreamings[id]) {
userStreamings[id]!.stop()
userStreamings[id] = null
}
const proxy = await proxyConfiguration.forMastodon()
2020-03-15 09:47:40 +01:00
const sns = await detector(acct.baseURL, proxy)
const url = await StreamingURL(sns, acct, proxy)
userStreamings[id] = new UserStreaming(sns, acct, url, proxy)
userStreamings[id]!.start(
async (update: Entity.Status) => {
if (!event.sender.isDestroyed()) {
event.sender.send(`update-start-all-user-streamings-${id}`, update)
}
2019-07-31 17:40:28 +02:00
// Cache hashtag
update.tags.map(async tag => {
await hashtagCache.insertHashtag(tag.name).catch(err => console.error(err))
2019-07-31 17:40:28 +02:00
})
// Cache account
await accountCache.insertAccount(id, update.account.acct).catch(err => console.error(err))
},
2020-03-15 09:47:40 +01:00
(notification: Entity.Notification) => {
const preferences = new Preferences(preferencesDBPath)
preferences.load().then(conf => {
const options = createNotification(notification, conf.notification.notify)
if (options !== null) {
const notify = new Notification(options)
notify.on('click', _ => {
if (!event.sender.isDestroyed()) {
event.sender.send('open-notification-tab', id)
}
})
notify.show()
}
})
if (process.platform === 'darwin') {
app.dock.setBadge('•')
}
// In macOS and Windows, sometimes window is closed (not quit).
// But streamings are always running.
// When window is closed, we can not send event to webContents; because it is already destroyed.
// So we have to guard it.
if (!event.sender.isDestroyed()) {
// To update notification timeline
event.sender.send(`notification-start-all-user-streamings-${id}`, notification)
// Does not exist a endpoint for only mention. And mention is a part of notification.
// So we have to get mention from notification.
if (notification.type === 'mention') {
event.sender.send(`mention-start-all-user-streamings-${id}`, notification)
}
}
},
(statusId: string) => {
if (!event.sender.isDestroyed()) {
event.sender.send(`delete-start-all-user-streamings-${id}`, statusId)
}
},
(err: Error) => {
log.error(err)
// In macOS, sometimes window is closed (not quit).
// When window is closed, we can not send event to webContents; because it is destroyed.
// So we have to guard it.
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-all-user-streamings', err)
}
}
)
} catch (err) {
log.error(err)
const streamingError = new StreamingError(err.message, account.domain)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-all-user-streamings', streamingError)
}
}
})
})
ipcMain.on('stop-all-user-streamings', () => {
Object.keys(userStreamings).forEach((key: string) => {
if (userStreamings[key]) {
userStreamings[key]!.stop()
userStreamings[key] = null
}
})
})
/**
* Stop an user streaming in all user streamings.
* @param id specified user id in nedb.
*/
const stopUserStreaming = (id: string) => {
Object.keys(userStreamings).forEach((key: string) => {
if (key === id && userStreamings[id]) {
userStreamings[id]!.stop()
userStreamings[id] = null
}
})
}
type StreamingSetting = {
2019-04-20 08:44:22 +02:00
account: LocalAccount
}
2020-03-15 09:47:40 +01:00
let directMessagesStreaming: DirectStreaming | null = null
2019-10-23 16:07:20 +02:00
ipcMain.on('start-directmessages-streaming', async (event: IpcMainEvent, obj: StreamingSetting) => {
const { account } = obj
try {
const acct = await accountManager.getAccount(account._id!)
// Stop old directmessages streaming
if (directMessagesStreaming !== null) {
directMessagesStreaming.stop()
directMessagesStreaming = null
}
const proxy = await proxyConfiguration.forMastodon()
2020-03-15 09:47:40 +01:00
const sns = await detector(acct.baseURL, proxy)
const url = await StreamingURL(sns, acct, proxy)
directMessagesStreaming = new DirectStreaming(sns, acct, url, proxy)
directMessagesStreaming.start(
2020-03-15 09:47:40 +01:00
(update: Entity.Status) => {
if (!event.sender.isDestroyed()) {
event.sender.send('update-start-directmessages-streaming', update)
}
},
(id: string) => {
if (!event.sender.isDestroyed()) {
event.sender.send('delete-start-directmessages-streaming', id)
}
},
(err: Error) => {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-directmessages-streaming', err)
}
}
)
} catch (err) {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-directmessages-streaming', err)
}
}
})
2019-04-17 12:52:01 +02:00
ipcMain.on('stop-directmessages-streaming', () => {
if (directMessagesStreaming !== null) {
directMessagesStreaming.stop()
directMessagesStreaming = null
}
})
2020-03-15 09:47:40 +01:00
let localStreaming: LocalStreaming | null = null
2019-10-23 16:07:20 +02:00
ipcMain.on('start-local-streaming', async (event: IpcMainEvent, obj: StreamingSetting) => {
const { account } = obj
try {
const acct = await accountManager.getAccount(account._id!)
// Stop old local streaming
if (localStreaming !== null) {
localStreaming.stop()
localStreaming = null
}
const proxy = await proxyConfiguration.forMastodon()
2020-03-15 09:47:40 +01:00
const sns = await detector(acct.baseURL, proxy)
const url = await StreamingURL(sns, acct, proxy)
localStreaming = new LocalStreaming(sns, acct, url, proxy)
localStreaming.start(
2020-03-15 09:47:40 +01:00
(update: Entity.Status) => {
if (!event.sender.isDestroyed()) {
event.sender.send('update-start-local-streaming', update)
}
},
(id: string) => {
if (!event.sender.isDestroyed()) {
event.sender.send('delete-start-local-streaming', id)
}
},
(err: Error) => {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-local-streaming', err)
}
}
)
} catch (err) {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-local-streaming', err)
}
}
})
2019-04-17 12:52:01 +02:00
ipcMain.on('stop-local-streaming', () => {
if (localStreaming !== null) {
localStreaming.stop()
localStreaming = null
}
})
2020-03-15 09:47:40 +01:00
let publicStreaming: PublicStreaming | null = null
2019-10-23 16:07:20 +02:00
ipcMain.on('start-public-streaming', async (event: IpcMainEvent, obj: StreamingSetting) => {
const { account } = obj
try {
const acct = await accountManager.getAccount(account._id!)
// Stop old public streaming
if (publicStreaming !== null) {
publicStreaming.stop()
publicStreaming = null
}
const proxy = await proxyConfiguration.forMastodon()
2020-03-15 09:47:40 +01:00
const sns = await detector(acct.baseURL, proxy)
const url = await StreamingURL(sns, acct, proxy)
publicStreaming = new PublicStreaming(sns, acct, url, proxy)
publicStreaming.start(
2020-03-15 09:47:40 +01:00
(update: Entity.Status) => {
if (!event.sender.isDestroyed()) {
event.sender.send('update-start-public-streaming', update)
}
},
(id: string) => {
if (!event.sender.isDestroyed()) {
event.sender.send('delete-start-public-streaming', id)
}
},
(err: Error) => {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-public-streaming', err)
}
}
)
} catch (err) {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-public-streaming', err)
}
}
})
2019-04-17 12:52:01 +02:00
ipcMain.on('stop-public-streaming', () => {
if (publicStreaming !== null) {
publicStreaming.stop()
publicStreaming = null
}
})
2020-03-15 09:47:40 +01:00
let listStreaming: ListStreaming | null = null
type ListID = {
2019-05-27 15:56:54 +02:00
listID: string
}
2019-10-23 16:07:20 +02:00
ipcMain.on('start-list-streaming', async (event: IpcMainEvent, obj: ListID & StreamingSetting) => {
const { listID, account } = obj
try {
const acct = await accountManager.getAccount(account._id!)
// Stop old list streaming
if (listStreaming !== null) {
listStreaming.stop()
listStreaming = null
}
const proxy = await proxyConfiguration.forMastodon()
2020-03-15 09:47:40 +01:00
const sns = await detector(acct.baseURL, proxy)
const url = await StreamingURL(sns, acct, proxy)
listStreaming = new ListStreaming(sns, acct, url, proxy)
listStreaming.start(
2020-03-15 09:47:40 +01:00
listID,
(update: Entity.Status) => {
if (!event.sender.isDestroyed()) {
event.sender.send('update-start-list-streaming', update)
}
},
(id: string) => {
if (!event.sender.isDestroyed()) {
event.sender.send('delete-start-list-streaming', id)
}
},
(err: Error) => {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-list-streaming', err)
}
}
)
} catch (err) {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-list-streaming', err)
}
}
})
2019-04-17 12:52:01 +02:00
ipcMain.on('stop-list-streaming', () => {
2018-06-01 06:09:42 +02:00
if (listStreaming !== null) {
listStreaming.stop()
listStreaming = null
}
})
2020-03-15 09:47:40 +01:00
let tagStreaming: TagStreaming | null = null
type Tag = {
tag: string
}
2019-10-23 16:07:20 +02:00
ipcMain.on('start-tag-streaming', async (event: IpcMainEvent, obj: Tag & StreamingSetting) => {
const { tag, account } = obj
try {
const acct = await accountManager.getAccount(account._id!)
// Stop old tag streaming
if (tagStreaming !== null) {
tagStreaming.stop()
tagStreaming = null
}
const proxy = await proxyConfiguration.forMastodon()
2020-03-15 09:47:40 +01:00
const sns = await detector(acct.baseURL, proxy)
const url = await StreamingURL(sns, acct, proxy)
tagStreaming = new TagStreaming(sns, acct, url, proxy)
tagStreaming.start(
2020-03-15 09:47:40 +01:00
tag,
(update: Entity.Status) => {
if (!event.sender.isDestroyed()) {
event.sender.send('update-start-tag-streaming', update)
}
},
(id: string) => {
if (!event.sender.isDestroyed()) {
event.sender.send('delete-start-tag-streaming', id)
}
},
(err: Error) => {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-tag-streaming', err)
}
}
)
} catch (err) {
log.error(err)
if (!event.sender.isDestroyed()) {
event.sender.send('error-start-tag-streaming', err)
}
}
})
2019-04-17 12:52:01 +02:00
ipcMain.on('stop-tag-streaming', () => {
if (tagStreaming !== null) {
tagStreaming.stop()
tagStreaming = null
}
})
// sounds
2019-04-17 12:52:01 +02:00
ipcMain.on('fav-rt-action-sound', () => {
const preferences = new Preferences(preferencesDBPath)
2019-04-20 08:44:22 +02:00
preferences
.load()
.then(conf => {
if (conf.general.sound.fav_rb) {
const sound = path.join(soundBasePath, 'operation_sound01.wav')
simplayer(sound, (err: Error) => {
if (err) log.error(err)
})
}
})
.catch(err => log.error(err))
})
2019-04-17 12:52:01 +02:00
ipcMain.on('toot-action-sound', () => {
const preferences = new Preferences(preferencesDBPath)
2019-04-20 08:44:22 +02:00
preferences
.load()
.then(conf => {
if (conf.general.sound.toot) {
const sound = path.join(soundBasePath, 'operation_sound02.wav')
simplayer(sound, (err: Error) => {
if (err) log.error(err)
})
}
})
.catch(err => log.error(err))
})
// preferences
ipcMain.handle('get-preferences', async (_: IpcMainInvokeEvent) => {
const preferences = new Preferences(preferencesDBPath)
let enabled = false
if (launcher) {
enabled = await launcher.isEnabled()
}
await preferences
.update({
general: {
other: {
launch: enabled
}
}
})
.catch(err => console.error(err))
const conf = await preferences.load()
return conf
})
ipcMain.handle('update-preferences', async (_: IpcMainInvokeEvent, data: any) => {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.update(data)
return conf
})
2019-10-23 16:07:20 +02:00
ipcMain.on('change-collapse', (_event: IpcMainEvent, value: boolean) => {
const preferences = new Preferences(preferencesDBPath)
2019-04-20 08:44:22 +02:00
preferences
.update({
state: {
collapse: value
}
})
2019-04-20 08:44:22 +02:00
.catch(err => {
log.error(err)
})
})
ipcMain.handle('get-collapse', async (_: IpcMainInvokeEvent) => {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.load()
return conf.state.collapse
})
ipcMain.handle('change-global-header', async (_: IpcMainInvokeEvent, value: boolean) => {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.update({
state: {
hideGlobalHeader: value
}
})
return conf
})
ipcMain.handle('get-global-header', async (_: IpcMainInvokeEvent) => {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.load()
return conf.state.hideGlobalHeader
})
// proxy
ipcMain.handle('update-proxy-config', async (_event: IpcMainInvokeEvent, proxy: Proxy) => {
const preferences = new Preferences(preferencesDBPath)
try {
const conf = await preferences.update({
proxy: proxy
})
const proxyConfig = await proxyConfiguration.forMastodon()
if (proxyConfig) {
await mainWindow?.webContents.session.setProxy({ proxyRules: `${proxyConfig.protocol}://${proxyConfig.host}:${proxyConfig.port}` })
} else {
await mainWindow?.webContents.session.setProxy({})
}
return conf
} catch (err) {
log.error(err)
}
return null
})
// language
ipcMain.handle('change-language', async (_: IpcMainInvokeEvent, value: string) => {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.update({
language: {
language: value
}
})
i18next.changeLanguage(conf.language.language)
return conf.language.language
})
ipcMain.handle('toggle-spellchecker', async (_: IpcMainInvokeEvent, value: boolean) => {
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.update({
language: {
spellchecker: {
enabled: value
}
}
})
return conf.language.spellchecker.enabled
})
ipcMain.handle('update-spellchecker-languages', async (_: IpcMainInvokeEvent, languages: Array<string>) => {
const decoded: Array<string> = languages.map(l => {
const d = decodeLanguage(l)
return d.rfc4646
})
mainWindow?.webContents.session.setSpellCheckerLanguages(decoded)
const preferences = new Preferences(preferencesDBPath)
const conf = await preferences.update({
language: {
spellchecker: {
languages: languages
}
}
})
return conf.language.spellchecker.languages
})
2018-06-01 07:19:56 +02:00
// hashtag
ipcMain.handle('save-hashtag', async (_: IpcMainInvokeEvent, tag: string) => {
2018-06-01 07:19:56 +02:00
const hashtags = new Hashtags(hashtagsDB)
await hashtags.insertTag(tag)
2018-06-01 07:19:56 +02:00
})
ipcMain.handle('list-hashtags', async (_: IpcMainInvokeEvent) => {
const hashtags = new Hashtags(hashtagsDB)
const tags = await hashtags.listTags()
return tags
})
ipcMain.handle('remove-hashtag', async (_: IpcMainInvokeEvent, tag: LocalTag) => {
2018-06-02 08:30:20 +02:00
const hashtags = new Hashtags(hashtagsDB)
await hashtags.removeTag(tag)
2018-06-02 08:30:20 +02:00
})
2018-09-25 18:02:36 +02:00
// Fonts
ipcMain.handle('list-fonts', async (_: IpcMainInvokeEvent) => {
const list = await Fonts()
return list
2018-09-25 18:02:36 +02:00
})
// Unread notifications
ipcMain.handle('get-unread-notification', async (_: IpcMainInvokeEvent, accountID: string) => {
const doc = await unreadNotification.findOne({
accountID: accountID
})
return doc
})
ipcMain.handle('update-unread-notification', async (_: IpcMainInvokeEvent, config: UnreadNotificationConfig) => {
const { accountID } = config
await unreadNotification.insertOrUpdate(accountID!, config)
})
2019-07-30 17:17:30 +02:00
// Cache
ipcMain.handle('get-cache-hashtags', async (_: IpcMainInvokeEvent) => {
2019-07-31 17:40:28 +02:00
const tags = await hashtagCache.listTags()
return tags
2019-07-30 17:17:30 +02:00
})
ipcMain.handle('insert-cache-hashtags', async (_: IpcMainInvokeEvent, tags: Array<string>) => {
await Promise.all(
tags.map(async name => {
await hashtagCache.insertHashtag(name).catch(err => console.error(err))
})
)
2019-08-08 16:39:27 +02:00
})
ipcMain.handle('get-cache-accounts', async (_: IpcMainInvokeEvent, ownerID: string) => {
2019-08-08 16:39:27 +02:00
const accounts = await accountCache.listAccounts(ownerID)
return accounts
2019-08-08 16:39:27 +02:00
})
ipcMain.handle('insert-cache-accounts', async (_: IpcMainInvokeEvent, obj: InsertAccountCache) => {
2019-08-08 16:39:27 +02:00
const { ownerID, accts } = obj
Promise.all(
accts.map(async acct => {
await accountCache.insertAccount(ownerID, acct).catch(err => console.error(err))
})
)
2019-07-30 17:17:30 +02:00
})
// Application control
2019-04-17 12:52:01 +02:00
ipcMain.on('relaunch', () => {
app.relaunch()
app.exit()
})
2018-03-07 14:28:48 +01:00
/**
* Auto Updater
*
* Uncomment the following code below and install `electron-updater` to
* support auto updating. Code Signing with a valid certificate is required.
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
*/
/*
import { autoUpdater } from 'electron-updater'
autoUpdater.on('update-downloaded', () => {
autoUpdater.quitAndInstall()
})
app.on('ready', () => {
if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
*/
2018-08-10 17:40:06 +02:00
/**
* Genrate application menu
2018-08-10 17:40:06 +02:00
*/
const ApplicationMenu = (accountsChange: Array<MenuItemConstructorOptions>, menu: MenuPreferences, i18n: I18n): Menu => {
2018-08-10 17:40:06 +02:00
/**
* For mac menu
*/
2019-04-20 08:44:22 +02:00
const macGeneralMenu: Array<MenuItemConstructorOptions> =
process.platform !== 'darwin'
? []
: [
{
type: 'separator'
},
{
label: i18n.t('main_menu.application.services'),
2019-10-23 16:07:20 +02:00
role: 'services'
2019-04-20 08:44:22 +02:00
},
{
type: 'separator'
},
{
label: i18n.t('main_menu.application.hide'),
role: 'hide'
},
{
label: i18n.t('main_menu.application.hide_others'),
2019-10-23 16:07:20 +02:00
role: 'hideOthers'
2019-04-20 08:44:22 +02:00
},
{
label: i18n.t('main_menu.application.show_all'),
role: 'unhide'
}
]
2018-08-10 17:40:06 +02:00
const macWindowMenu: Array<MenuItemConstructorOptions> =
process.platform === 'darwin'
? []
: [
{
label: i18n.t('main_menu.window.always_show_menu_bar'),
type: 'checkbox',
checked: !menu.autoHideMenu,
click: item => {
changeMenuAutoHide(!item.checked)
}
},
{
type: 'separator'
}
]
const applicationQuitMenu: Array<MenuItemConstructorOptions> =
process.platform === 'darwin'
? [
{
label: i18n.t('main_menu.application.quit'),
accelerator: 'CmdOrCtrl+Q',
role: 'quit'
}
]
: [
{
label: i18n.t('main_menu.application.quit'),
accelerator: 'CmdOrCtrl+Q',
click: () => {
mainWindow!.destroy()
}
}
]
2019-04-17 12:52:01 +02:00
const template: Array<MenuItemConstructorOptions> = [
2018-08-10 17:40:06 +02:00
{
label: i18n.t('main_menu.application.name'),
submenu: [
{
label: i18n.t('main_menu.application.about'),
role: 'about',
click: () => {
openAboutWindow({
icon_path: path.resolve(__dirname, '../../build/icons/256x256.png'),
copyright: 'Copyright (c) 2020 AkiraFukushima',
2018-08-10 17:40:06 +02:00
package_json_dir: path.resolve(__dirname, '../../'),
open_devtools: process.env.NODE_ENV !== 'production'
2018-08-10 17:40:06 +02:00
})
}
},
{
type: 'separator'
},
{
label: i18n.t('main_menu.application.preferences'),
accelerator: 'CmdOrCtrl+,',
click: () => {
mainWindow!.webContents.send('open-preferences')
2018-08-10 17:40:06 +02:00
}
},
...macGeneralMenu,
{
type: 'separator'
},
...applicationQuitMenu
2018-08-10 17:40:06 +02:00
]
},
{
label: i18n.t('main_menu.toot.name'),
submenu: [
{
label: i18n.t('main_menu.toot.new'),
accelerator: 'CmdOrCtrl+N',
click: () => {
mainWindow!.webContents.send('CmdOrCtrl+N')
2018-08-10 17:40:06 +02:00
}
}
]
},
{
label: i18n.t('main_menu.edit.name'),
submenu: [
{
label: i18n.t('main_menu.edit.undo'),
accelerator: 'CmdOrCtrl+Z',
role: 'undo'
},
{
label: i18n.t('main_menu.edit.redo'),
accelerator: 'Shift+CmdOrCtrl+Z',
role: 'redo'
},
{
type: 'separator'
},
{
label: i18n.t('main_menu.edit.cut'),
accelerator: 'CmdOrCtrl+X',
role: 'cut'
},
{
label: i18n.t('main_menu.edit.copy'),
accelerator: 'CmdOrCtrl+C',
role: 'copy'
},
{
label: i18n.t('main_menu.edit.paste'),
accelerator: 'CmdOrCtrl+V',
role: 'paste'
},
{
label: i18n.t('main_menu.edit.select_all'),
accelerator: 'CmdOrCtrl+A',
role: 'selectall'
}
2019-10-23 16:07:20 +02:00
] as Array<MenuItemConstructorOptions>
2018-08-10 17:40:06 +02:00
},
{
label: i18n.t('main_menu.view.name'),
submenu: [
{
label: i18n.t('main_menu.view.toggle_full_screen'),
role: 'togglefullscreen'
}
]
},
{
label: i18n.t('main_menu.window.name'),
submenu: [
...macWindowMenu,
2018-08-10 17:40:06 +02:00
{
label: i18n.t('main_menu.window.close'),
role: 'close'
},
{
label: i18n.t('main_menu.window.open'),
enabled: false,
click: () => {
reopenWindow()
}
},
2018-08-10 17:40:06 +02:00
{
label: i18n.t('main_menu.window.minimize'),
role: 'minimize'
},
{
type: 'separator'
},
{
label: i18n.t('main_menu.window.jump_to'),
accelerator: 'CmdOrCtrl+K',
enabled: true,
click: () => {
mainWindow!.webContents.send('CmdOrCtrl+K')
2018-08-10 17:40:06 +02:00
}
},
{
type: 'separator'
},
...accountsChange
]
}
]
return Menu.buildFromTemplate(template)
2018-08-10 17:40:06 +02:00
}
2020-01-11 13:48:22 +01:00
const TrayMenu = (accountsChange: Array<MenuItemConstructorOptions>, i18n: I18n): Menu => {
const template: Array<MenuItemConstructorOptions> = [
...accountsChange,
{
label: i18n.t('main_menu.application.open'),
click: async () => {
if (mainWindow) {
mainWindow.show()
} else {
await createWindow()
}
}
},
{
label: i18n.t('main_menu.application.quit'),
click: () => {
mainWindow!.destroy()
}
}
]
const menu: Menu = Menu.buildFromTemplate(template)
return menu
}
const changeMenuAutoHide = async (autoHide: boolean) => {
2020-06-06 17:19:41 +02:00
if (mainWindow === null) {
return null
}
mainWindow.autoHideMenuBar = autoHide
mainWindow.setMenuBarVisibility(!autoHide)
const preferences = new Preferences(preferencesDBPath)
preferences.update({
menu: {
autoHideMenu: autoHide
}
})
2020-06-06 17:19:41 +02:00
return null
}
2019-04-20 08:44:22 +02:00
async function reopenWindow() {
if (mainWindow === null) {
await createWindow()
return null
} else {
return null
}
}
2020-03-15 09:47:40 +01:00
const createNotification = (notification: Entity.Notification, notifyConfig: Notify): NotificationConstructorOptions | null => {
switch (notification.type) {
case NotificationType.Favourite:
if (notifyConfig.favourite) {
return {
2020-01-11 13:48:22 +01:00
title: i18next.t('notification.favourite.title'),
body: i18next.t('notification.favourite.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
break
case NotificationType.Follow:
if (notifyConfig.follow) {
return {
2020-01-11 13:48:22 +01:00
title: i18next.t('notification.follow.title'),
body: i18next.t('notification.follow.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
break
case NotificationType.FollowRequest:
if (notifyConfig.follow_request) {
return {
title: i18next.t('notification.follow_request.title'),
body: i18next.t('notification.follow_request.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
break
case NotificationType.Mention:
if (notifyConfig.reply) {
return {
title: `${username(notification.status!.account)}`,
body: sanitizeHtml(notification.status!.content, {
allowedTags: [],
allowedAttributes: []
}),
silent: false
} as NotificationConstructorOptions
}
break
case NotificationType.Reblog:
if (notifyConfig.reblog) {
if (notification.status && notification.status.quote) {
return {
title: i18next.t('notification.quote.title'),
body: i18next.t('notification.quote.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
} else {
return {
title: i18next.t('notification.reblog.title'),
body: i18next.t('notification.reblog.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
}
break
case NotificationType.EmojiReaction:
if (notifyConfig.reaction) {
return {
title: i18next.t('notification.reaction.title'),
body: i18next.t('notification.reaction.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
break
case NotificationType.Status:
if (notifyConfig.status) {
return {
title: i18next.t('notification.status.title'),
body: i18next.t('notification.status.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
break
case NotificationType.PollVote:
if (notifyConfig.poll_vote) {
return {
title: i18next.t('notification.poll_vote.title'),
body: i18next.t('notification.poll_vote.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
break
case NotificationType.PollExpired:
if (notifyConfig.poll_expired) {
return {
title: i18next.t('notification.poll_expired.title'),
body: i18next.t('notification.poll_expired.body', { username: username(notification.account) }),
silent: false
} as NotificationConstructorOptions
}
break
default:
break
}
return null
}
2020-03-15 09:47:40 +01:00
const username = (account: Entity.Account): string => {
if (account.display_name !== '') {
return account.display_name
} else {
return account.username
}
}
const decodeLanguage = (lang: string): LanguageType => {
const l = Object.keys(Language).find(k => Language[k].key === lang)
if (l === undefined) {
return Language.en
} else {
return Language[l]
}
}