refactor: replace tipc to ipcServices (#3863)
* init * refactor: remove @egoist/tipc integration and clean up IPC services - Deleted references to @egoist/tipc, including related imports and methods. - Refactored IPC services to utilize decorators for method registration. - Updated renderer to use new IPC method calls directly. - Cleaned up unused files and dependencies related to tipc. - Enhanced the structure of IPC services for better maintainability. Signed-off-by: Innei <tukon479@gmail.com> * refactor: replace tipcClient with ipcServices and clean up IPC integration - Removed all instances of tipcClient and replaced them with ipcServices for improved IPC method calls. - Deleted the obsolete ipc-client.ts file and related references. - Updated various components and hooks to utilize the new ipcServices structure. - Enhanced type safety and maintainability of IPC service interactions. Signed-off-by: Innei <tukon479@gmail.com> --------- Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
// Export types for renderer to use
|
||||
export type { IpcServices } from "./src/ipc"
|
||||
export type { RendererHandlers } from "./src/renderer-handlers"
|
||||
export type { Router } from "./src/tipc"
|
||||
export { router } from "./src/tipc"
|
||||
|
||||
// Export services for potential main process use
|
||||
export { services } from "./src/ipc"
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./export.d.ts",
|
||||
"import": "./export.js"
|
||||
}
|
||||
},
|
||||
@@ -21,7 +20,6 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@egoist/tipc": "0.3.2",
|
||||
"@electron-toolkit/preload": "3.0.2",
|
||||
"@electron-toolkit/utils": "4.0.0",
|
||||
"@eneris/push-receiver": "4.3.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import path from "node:path"
|
||||
|
||||
import { getRendererHandlers, registerIpcMain } from "@egoist/tipc/main"
|
||||
import { PushReceiver } from "@eneris/push-receiver"
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { APP_PROTOCOL, DEV, LEGACY_APP_PROTOCOL } from "@follow/shared/constants"
|
||||
import { env } from "@follow/shared/env.desktop"
|
||||
import type { MessagingData } from "@follow/shared/hono"
|
||||
@@ -9,15 +9,14 @@ import { app, nativeTheme, Notification, protocol, shell } from "electron"
|
||||
import contextMenu from "electron-context-menu"
|
||||
|
||||
import { getIconPath } from "./helper"
|
||||
import { initializeIpcServices } from "./ipc"
|
||||
import { checkAndCleanCodeCache, clearCacheCronJob } from "./lib/cleaner"
|
||||
import { t } from "./lib/i18n"
|
||||
import { store } from "./lib/store"
|
||||
import { updateNotificationsToken } from "./lib/user"
|
||||
import { logger } from "./logger"
|
||||
import { registerAppMenu } from "./menu"
|
||||
import type { RendererHandlers } from "./renderer-handlers"
|
||||
import { initializeSentry } from "./sentry"
|
||||
import { router } from "./tipc"
|
||||
import { getMainWindowOrCreate } from "./window"
|
||||
|
||||
if (process.argv.length === 3 && process.argv[2]!.startsWith("follow-dev:")) {
|
||||
@@ -29,6 +28,7 @@ if (process.argv.length === 3 && process.argv[2]!.startsWith("follow-dev:")) {
|
||||
*/
|
||||
export function initializeAppStage0() {
|
||||
initializeSentry()
|
||||
initializeIpcServices()
|
||||
}
|
||||
export const initializeAppStage1 = () => {
|
||||
const protocols = [LEGACY_APP_PROTOCOL, APP_PROTOCOL]
|
||||
@@ -43,8 +43,6 @@ export const initializeAppStage1 = () => {
|
||||
}
|
||||
}
|
||||
|
||||
registerIpcMain(router)
|
||||
|
||||
if (app.dock) {
|
||||
app.dock.setIcon(getIconPath())
|
||||
}
|
||||
@@ -189,8 +187,8 @@ const registerPushNotifications = async () => {
|
||||
const mainWindow = getMainWindowOrCreate()
|
||||
mainWindow.restore()
|
||||
mainWindow.focus()
|
||||
const handlers = getRendererHandlers<RendererHandlers>(mainWindow.webContents)
|
||||
handlers.navigateEntry.send({
|
||||
const handlers = callWindowExpose(mainWindow)
|
||||
handlers.navigateEntry({
|
||||
feedId: data.feedId,
|
||||
entryId: data.entryId,
|
||||
view: Number.parseInt(data.view),
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { IpcMainInvokeEvent, WebContents } from "electron"
|
||||
import { ipcMain } from "electron"
|
||||
|
||||
// Base context for IPC methods
|
||||
export interface IpcContext {
|
||||
sender: WebContents
|
||||
event: IpcMainInvokeEvent
|
||||
}
|
||||
|
||||
// Metadata storage for decorated methods
|
||||
const methodMetadata = new WeakMap<any, Map<string, string>>()
|
||||
|
||||
// Decorator for IPC methods
|
||||
export function IpcMethod(methodName?: string) {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const { constructor } = target
|
||||
|
||||
if (!methodMetadata.has(constructor)) {
|
||||
methodMetadata.set(constructor, new Map())
|
||||
}
|
||||
|
||||
const methods = methodMetadata.get(constructor)!
|
||||
const finalMethodName = methodName || propertyKey
|
||||
methods.set(propertyKey, finalMethodName)
|
||||
|
||||
return descriptor
|
||||
}
|
||||
}
|
||||
|
||||
// Handler registry for IPC methods
|
||||
export class IpcHandler {
|
||||
private static instance: IpcHandler
|
||||
private registeredChannels = new Set<string>()
|
||||
|
||||
static getInstance(): IpcHandler {
|
||||
if (!IpcHandler.instance) {
|
||||
IpcHandler.instance = new IpcHandler()
|
||||
}
|
||||
return IpcHandler.instance
|
||||
}
|
||||
|
||||
registerMethod<TOutput>(
|
||||
channel: string,
|
||||
handler: (context: IpcContext, ...args: any[]) => Promise<TOutput> | TOutput,
|
||||
) {
|
||||
if (this.registeredChannels.has(channel)) {
|
||||
return // Already registered
|
||||
}
|
||||
|
||||
this.registeredChannels.add(channel)
|
||||
|
||||
ipcMain.handle(channel, async (event: IpcMainInvokeEvent, ...args: any[]) => {
|
||||
const context: IpcContext = {
|
||||
sender: event.sender,
|
||||
event,
|
||||
}
|
||||
|
||||
try {
|
||||
return await handler(context, ...args)
|
||||
} catch (error) {
|
||||
console.error(`Error in IPC method ${channel}:`, error)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Send events to renderer
|
||||
sendToRenderer<T = any>(webContents: WebContents, channel: string, data: T) {
|
||||
webContents.send(channel, data)
|
||||
}
|
||||
}
|
||||
|
||||
// Base class for IPC service groups
|
||||
export abstract class IpcService {
|
||||
protected handler = IpcHandler.getInstance()
|
||||
|
||||
constructor(protected groupName: string) {
|
||||
this.registerMethods()
|
||||
}
|
||||
|
||||
protected registerMethods(): void {
|
||||
const { constructor } = this
|
||||
const methods = methodMetadata.get(constructor)
|
||||
|
||||
if (methods) {
|
||||
for (const [propertyKey, methodName] of methods) {
|
||||
const method = (this as any)[propertyKey]
|
||||
if (typeof method === "function") {
|
||||
this.registerMethod(methodName, method.bind(this))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected registerMethod<TOutput>(
|
||||
methodName: string,
|
||||
handler: (context: IpcContext, ...args: any[]) => Promise<TOutput> | TOutput,
|
||||
) {
|
||||
const channel = `${this.groupName}.${methodName}`
|
||||
this.handler.registerMethod(channel, handler)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract method signatures from service class, removing context parameter
|
||||
export type ExtractServiceMethods<T> = {
|
||||
[K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] extends (
|
||||
context: IpcContext,
|
||||
...args: infer Args
|
||||
) => infer Output
|
||||
? Args extends []
|
||||
? () => AlwaysPromise<Output>
|
||||
: Args extends [infer Input]
|
||||
? (input: Input) => AlwaysPromise<Output>
|
||||
: (...args: Args) => AlwaysPromise<Output>
|
||||
: never
|
||||
}
|
||||
|
||||
type AlwaysPromise<T> = Promise<Awaited<T>>
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ExtractServiceMethods } from "./base"
|
||||
import { AppService } from "./services/app"
|
||||
import { AuthService } from "./services/auth"
|
||||
import { DebugService } from "./services/debug"
|
||||
import { DockService } from "./services/dock"
|
||||
import { IntegrationService } from "./services/integration"
|
||||
import { MenuService } from "./services/menu"
|
||||
import { ReaderService } from "./services/reader"
|
||||
import { SettingService } from "./services/setting"
|
||||
|
||||
// Initialize all services
|
||||
export const services = {
|
||||
app: new AppService(),
|
||||
auth: new AuthService(),
|
||||
debug: new DebugService(),
|
||||
dock: new DockService(),
|
||||
menu: new MenuService(),
|
||||
reader: new ReaderService(),
|
||||
setting: new SettingService(),
|
||||
integration: new IntegrationService(),
|
||||
} as const
|
||||
|
||||
// Extract method types automatically from services
|
||||
export type IpcServices = {
|
||||
app: ExtractServiceMethods<AppService>
|
||||
auth: ExtractServiceMethods<AuthService>
|
||||
debug: ExtractServiceMethods<DebugService>
|
||||
dock: ExtractServiceMethods<DockService>
|
||||
menu: ExtractServiceMethods<MenuService>
|
||||
reader: ExtractServiceMethods<ReaderService>
|
||||
setting: ExtractServiceMethods<SettingService>
|
||||
integration: ExtractServiceMethods<IntegrationService>
|
||||
}
|
||||
|
||||
// Initialize all services (this will register all IPC handlers)
|
||||
export function initializeIpcServices() {
|
||||
// Services are already initialized in the services constant above
|
||||
console.info("IPC services initialized")
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import path from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { DEV } from "@follow/shared/constants"
|
||||
import { app, BrowserWindow, clipboard, dialog } from "electron"
|
||||
|
||||
import { registerMenuAndContextMenu } from "~/init"
|
||||
import { i18n } from "~/lib/i18n"
|
||||
import { registerAppTray } from "~/lib/tray"
|
||||
import { logger } from "~/logger"
|
||||
import { cleanupOldRender, loadDynamicRenderEntry } from "~/updater/hot-updater"
|
||||
|
||||
import { downloadFile } from "../../lib/download"
|
||||
import { checkForAppUpdates, quitAndInstall } from "../../updater"
|
||||
import { getMainWindow } from "../../window"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
interface WindowActionInput {
|
||||
action: "close" | "minimize" | "maximum"
|
||||
}
|
||||
|
||||
interface SearchInput {
|
||||
text: string
|
||||
options: Electron.FindInPageOptions
|
||||
}
|
||||
|
||||
interface Sender extends Electron.WebContents {
|
||||
getOwnerBrowserWindow: () => Electron.BrowserWindow | null
|
||||
}
|
||||
|
||||
export class AppService extends IpcService {
|
||||
constructor() {
|
||||
super("app")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
getAppVersion(): string {
|
||||
return app.getVersion()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
checkForUpdates(): void {
|
||||
checkForAppUpdates()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
switchAppLocale(context: IpcContext, input: string): void {
|
||||
i18n.changeLanguage(input)
|
||||
registerMenuAndContextMenu()
|
||||
registerAppTray()
|
||||
|
||||
app.commandLine.appendSwitch("lang", input)
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
rendererUpdateReload(): void {
|
||||
const __dirname = fileURLToPath(new URL(".", import.meta.url))
|
||||
const allWindows = BrowserWindow.getAllWindows()
|
||||
const dynamicRenderEntry = loadDynamicRenderEntry()
|
||||
|
||||
const appLoadEntry = dynamicRenderEntry || path.resolve(__dirname, "../renderer/index.html")
|
||||
logger.info("appLoadEntry", appLoadEntry)
|
||||
const mainWindow = getMainWindow()
|
||||
|
||||
for (const window of allWindows) {
|
||||
if (window === mainWindow) {
|
||||
if (DEV) {
|
||||
logger.verbose("[rendererUpdateReload]: skip reload in dev")
|
||||
break
|
||||
}
|
||||
window.loadFile(appLoadEntry)
|
||||
} else window.destroy()
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
cleanupOldRender()
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
windowAction(context: IpcContext, input: WindowActionInput): void {
|
||||
if (context.sender.getType() === "window") {
|
||||
const window: BrowserWindow | null = (context.sender as Sender).getOwnerBrowserWindow()
|
||||
|
||||
if (!window) return
|
||||
switch (input.action) {
|
||||
case "close": {
|
||||
window.close()
|
||||
break
|
||||
}
|
||||
case "minimize": {
|
||||
window.minimize()
|
||||
break
|
||||
}
|
||||
case "maximum": {
|
||||
if (window.isMaximized()) {
|
||||
window.unmaximize()
|
||||
} else {
|
||||
window.maximize()
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
quitAndInstall(_context: IpcContext): void {
|
||||
quitAndInstall()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
readClipboard(_context: IpcContext): string {
|
||||
return clipboard.readText()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async search(context: IpcContext, input: SearchInput): Promise<Electron.Result | null> {
|
||||
const { sender: webContents } = context
|
||||
|
||||
const { promise, resolve } = Promise.withResolvers<Electron.Result | null>()
|
||||
|
||||
let requestId = -1
|
||||
webContents.once("found-in-page", (_, result) => {
|
||||
resolve(result.requestId === requestId ? result : null)
|
||||
})
|
||||
requestId = webContents.findInPage(input.text, input.options)
|
||||
return promise
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
clearSearch(context: IpcContext): void {
|
||||
context.sender.stopFindInPage("keepSelection")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async download(context: IpcContext, input: string): Promise<void> {
|
||||
const result = await dialog.showSaveDialog({
|
||||
defaultPath: input.split("/").pop(),
|
||||
})
|
||||
if (result.canceled) return
|
||||
|
||||
try {
|
||||
await downloadFile(input, result.filePath)
|
||||
|
||||
const senderWindow = (context.sender as Sender).getOwnerBrowserWindow()
|
||||
if (senderWindow) {
|
||||
callWindowExpose(senderWindow).toast.success("Download success!", {
|
||||
duration: 1000,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
const senderWindow = (context.sender as Sender).getOwnerBrowserWindow()
|
||||
if (senderWindow) {
|
||||
callWindowExpose(senderWindow).toast.error("Download failed!", {
|
||||
duration: 1000,
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
getAppPath(_context: IpcContext): string {
|
||||
return app.getAppPath()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
resolveAppAsarPath(context: IpcContext, input: string): string {
|
||||
if (input.startsWith("file://")) {
|
||||
input = fileURLToPath(input)
|
||||
}
|
||||
|
||||
if (path.isAbsolute(input)) {
|
||||
return input
|
||||
}
|
||||
|
||||
return path.join(app.getAppPath(), input)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { deleteNotificationsToken, updateNotificationsToken } from "../../lib/user"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
export class AuthService extends IpcService {
|
||||
constructor() {
|
||||
super("auth")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async sessionChanged(_context: IpcContext): Promise<void> {
|
||||
await updateNotificationsToken()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async signOut(_context: IpcContext): Promise<void> {
|
||||
await deleteNotificationsToken()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
interface InspectElementInput {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export class DebugService extends IpcService {
|
||||
constructor() {
|
||||
super("debug")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
inspectElement(context: IpcContext, input: InspectElementInput): void {
|
||||
context.sender.inspectElement(input.x, input.y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { UNREAD_BACKGROUND_POLLING_INTERVAL } from "../../constants/app"
|
||||
import { apiClient } from "../../lib/api-client"
|
||||
import { setDockCount } from "../../lib/dock"
|
||||
import { sleep } from "../../lib/utils"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
const pollingMap = {
|
||||
unread: false,
|
||||
}
|
||||
|
||||
export class DockService extends IpcService {
|
||||
constructor() {
|
||||
super("dock")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async pollingUpdateUnreadCount(): Promise<void> {
|
||||
if (pollingMap.unread) {
|
||||
return
|
||||
}
|
||||
|
||||
pollingMap.unread = true
|
||||
while (pollingMap.unread) {
|
||||
await sleep(UNREAD_BACKGROUND_POLLING_INTERVAL)
|
||||
if (pollingMap.unread) {
|
||||
await this.updateUnreadCount()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async cancelPollingUpdateUnreadCount(): Promise<void> {
|
||||
pollingMap.unread = false
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async updateUnreadCount(): Promise<void> {
|
||||
const res = await apiClient.reads["total-count"].$get()
|
||||
setDockCount(res.data.count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { existsSync } from "node:fs"
|
||||
import fsp from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
// Input types
|
||||
interface SaveToEagleInput {
|
||||
url: string
|
||||
mediaUrls: string[]
|
||||
}
|
||||
export class IntegrationService extends IpcService {
|
||||
constructor() {
|
||||
super("integration")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async saveToObsidian(
|
||||
context: IpcContext,
|
||||
input: {
|
||||
url: string
|
||||
title: string
|
||||
content: string
|
||||
author: string
|
||||
publishedAt: string
|
||||
vaultPath: string
|
||||
},
|
||||
) {
|
||||
try {
|
||||
const { url, title, content, author, publishedAt, vaultPath } = input
|
||||
|
||||
const fileName = `${(title || publishedAt).trim().slice(0, 20).replaceAll("/", "-")}.md`
|
||||
const filePath = path.join(vaultPath, fileName)
|
||||
const exists = existsSync(filePath)
|
||||
if (exists) {
|
||||
return { success: false, error: "File already exists" }
|
||||
}
|
||||
|
||||
const markdown = `---
|
||||
url: ${url}
|
||||
author: ${author}
|
||||
publishedAt: ${publishedAt}
|
||||
---
|
||||
|
||||
# ${title}
|
||||
|
||||
${content}
|
||||
`
|
||||
|
||||
await fsp.writeFile(filePath, markdown, "utf-8")
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Failed to save to Obsidian:", error)
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
return { success: false, error: errorMessage }
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async saveToEagle(context: IpcContext, input: SaveToEagleInput): Promise<any> {
|
||||
try {
|
||||
const res = await fetch("http://localhost:41595/api/item/addFromURLs", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
items: input.mediaUrls?.map((media) => ({
|
||||
url: media,
|
||||
website: input.url,
|
||||
headers: {
|
||||
referer: input.url,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
})
|
||||
return await res.json()
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { MenuItemConstructorOptions, MessageBoxOptions } from "electron"
|
||||
import { dialog, Menu, ShareMenu } from "electron"
|
||||
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
type SerializableMenuItem = Omit<MenuItemConstructorOptions, "click" | "submenu"> & {
|
||||
submenu?: SerializableMenuItem[]
|
||||
}
|
||||
|
||||
interface ShowContextMenuInput {
|
||||
items: SerializableMenuItem[]
|
||||
}
|
||||
|
||||
interface ShowConfirmDialogInput {
|
||||
title: string
|
||||
message: string
|
||||
options?: Partial<MessageBoxOptions>
|
||||
}
|
||||
|
||||
export class MenuService extends IpcService {
|
||||
constructor() {
|
||||
super("menu")
|
||||
}
|
||||
|
||||
private normalizeMenuItems(
|
||||
items: SerializableMenuItem[],
|
||||
context: IpcContext,
|
||||
path: number[] = [],
|
||||
): MenuItemConstructorOptions[] {
|
||||
return items.map((item, index) => {
|
||||
const curPath = [...path, index]
|
||||
return {
|
||||
...item,
|
||||
click() {
|
||||
context.sender.send("menu-click", {
|
||||
id: item.id,
|
||||
path: curPath,
|
||||
})
|
||||
},
|
||||
submenu: item.submenu ? this.normalizeMenuItems(item.submenu, context, curPath) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async showContextMenu(context: IpcContext, input: ShowContextMenuInput): Promise<void> {
|
||||
const defer = Promise.withResolvers<void>()
|
||||
const normalizedMenuItems = this.normalizeMenuItems(input.items, context)
|
||||
|
||||
const menu = Menu.buildFromTemplate(normalizedMenuItems)
|
||||
menu.popup({
|
||||
callback: () => defer.resolve(),
|
||||
})
|
||||
return defer.promise
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async showConfirmDialog(_context: IpcContext, input: ShowConfirmDialogInput): Promise<boolean> {
|
||||
const result = await dialog.showMessageBox({
|
||||
message: input.title,
|
||||
detail: input.message,
|
||||
buttons: ["Confirm", "Cancel"],
|
||||
...input.options,
|
||||
})
|
||||
return result.response === 0
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async showShareMenu(context: IpcContext, input: string): Promise<void> {
|
||||
const menu = new ShareMenu({
|
||||
urls: [input],
|
||||
})
|
||||
|
||||
menu.popup({
|
||||
callback: () => {
|
||||
context.sender.send("menu-closed")
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { readability } from "@follow-app/readability"
|
||||
import { app, BrowserWindow } from "electron"
|
||||
import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts"
|
||||
import type { ModelResult } from "vscode-languagedetection"
|
||||
|
||||
import { detectCodeStringLanguage } from "../../modules/language-detection"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
const tts = new MsEdgeTTS()
|
||||
|
||||
interface ReadabilityInput {
|
||||
url: string
|
||||
html?: string
|
||||
}
|
||||
|
||||
interface TtsInput {
|
||||
id: string
|
||||
text: string
|
||||
voice: string
|
||||
}
|
||||
|
||||
interface DetectCodeStringLanguageInput {
|
||||
codeString: string
|
||||
}
|
||||
|
||||
export class ReaderService extends IpcService {
|
||||
constructor() {
|
||||
super("reader")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async readability(_context: IpcContext, input: ReadabilityInput) {
|
||||
const { url } = input
|
||||
|
||||
if (!url) {
|
||||
return null
|
||||
}
|
||||
const result = await readability(url)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async tts(context: IpcContext, input: TtsInput): Promise<string | null> {
|
||||
const { id, text, voice } = input
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
|
||||
const window = BrowserWindow.fromWebContents(context.sender)
|
||||
if (!window) return null
|
||||
|
||||
try {
|
||||
await tts.setMetadata(voice, OUTPUT_FORMAT.AUDIO_24KHZ_96KBITRATE_MONO_MP3)
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to set voice", error)
|
||||
if (error instanceof Error) {
|
||||
callWindowExpose(window).toast.error(error.message, {
|
||||
duration: 1000,
|
||||
})
|
||||
} else {
|
||||
callWindowExpose(window).toast.error("Failed to set voice", {
|
||||
duration: 1000,
|
||||
})
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const dirPath = path.join(app.getPath("userData"), "Cache", "tts", id)
|
||||
const possibleFilePathList = ["mp3", "webm"].map((ext) => {
|
||||
return path.join(dirPath, `audio.${ext}`)
|
||||
})
|
||||
const filePath = possibleFilePathList.find((p) => fs.existsSync(p))
|
||||
if (filePath) {
|
||||
return filePath
|
||||
} else {
|
||||
fs.mkdirSync(dirPath, { recursive: true })
|
||||
const { audioFilePath } = await tts.toFile(dirPath, text)
|
||||
return audioFilePath
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async getVoices(context: IpcContext) {
|
||||
const window = BrowserWindow.fromWebContents(context.sender)
|
||||
try {
|
||||
const voices = await tts.getVoices()
|
||||
return voices
|
||||
} catch (error) {
|
||||
console.error("Failed to get voices", error)
|
||||
if (!window) return
|
||||
if (error instanceof Error) {
|
||||
void callWindowExpose(window).toast.error(error.message, { duration: 1000 })
|
||||
return
|
||||
}
|
||||
callWindowExpose(window).toast.error("Failed to get voices", { duration: 1000 })
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async detectCodeStringLanguage(
|
||||
_context: IpcContext,
|
||||
input: DetectCodeStringLanguageInput,
|
||||
): Promise<ModelResult | undefined> {
|
||||
const { codeString } = input
|
||||
const languages = detectCodeStringLanguage(codeString)
|
||||
|
||||
let finalLanguage: ModelResult | undefined
|
||||
for await (const language of languages) {
|
||||
if (!finalLanguage) {
|
||||
finalLanguage = language
|
||||
continue
|
||||
}
|
||||
if (language.confidence > finalLanguage.confidence) {
|
||||
finalLanguage = language
|
||||
}
|
||||
}
|
||||
|
||||
return finalLanguage
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { createRequire } from "node:module"
|
||||
|
||||
import { app, nativeTheme } from "electron"
|
||||
|
||||
import { setDockCount } from "../../lib/dock"
|
||||
import { setProxyConfig, updateProxy } from "../../lib/proxy"
|
||||
import { store } from "../../lib/store"
|
||||
import { getTrayConfig, setTrayConfig } from "../../lib/tray"
|
||||
import { showSetting } from "../../window"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
interface SetLoginItemSettingsInput {
|
||||
openAtLogin: boolean
|
||||
openAsHidden?: boolean
|
||||
path?: string
|
||||
args?: string[]
|
||||
}
|
||||
|
||||
export class SettingService extends IpcService {
|
||||
constructor() {
|
||||
super("setting")
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
getLoginItemSettings(_context: IpcContext): Electron.LoginItemSettings {
|
||||
return app.getLoginItemSettings()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
setLoginItemSettings(_context: IpcContext, input: SetLoginItemSettingsInput): void {
|
||||
app.setLoginItemSettings(input)
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
openSettingWindow(_context: IpcContext): void {
|
||||
showSetting()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async getSystemFonts(_context: IpcContext): Promise<string[]> {
|
||||
const fonts = await require("font-list").getFonts()
|
||||
return fonts.map((font: string) => font.replaceAll('"', ""))
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
getAppearance(_context: IpcContext): "light" | "dark" | "system" {
|
||||
return nativeTheme.themeSource
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
setAppearance(_context: IpcContext, appearance: "light" | "dark" | "system"): void {
|
||||
nativeTheme.themeSource = appearance
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
getMinimizeToTray(_context: IpcContext): boolean {
|
||||
return getTrayConfig()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
setMinimizeToTray(_context: IpcContext, minimize: boolean): void {
|
||||
setTrayConfig(minimize)
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
setDockBadge(_context: IpcContext, count: number): void {
|
||||
setDockCount(count)
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
getProxyConfig(_context: IpcContext) {
|
||||
const proxy = store.get("proxy")
|
||||
return proxy ?? undefined
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
setProxyConfig(_context: IpcContext, config: string) {
|
||||
const result = setProxyConfig(config)
|
||||
updateProxy()
|
||||
return result
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
getMessagingToken(_context: IpcContext): string | null {
|
||||
return store.get("notifications-credentials") as string | null
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { tipc } from "@egoist/tipc/main"
|
||||
|
||||
export const t = tipc.create()
|
||||
|
||||
export type T = typeof t
|
||||
@@ -1,335 +0,0 @@
|
||||
import fs from "node:fs"
|
||||
import fsp from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
import { getRendererHandlers } from "@egoist/tipc/main"
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { DEV } from "@follow/shared/constants"
|
||||
import { app, BrowserWindow, clipboard, dialog, shell } from "electron"
|
||||
|
||||
import { filePathToAppUrl } from "~/helper"
|
||||
import { registerMenuAndContextMenu } from "~/init"
|
||||
import { clearAllData, getCacheSize } from "~/lib/cleaner"
|
||||
import { store, StoreKey } from "~/lib/store"
|
||||
import { registerAppTray } from "~/lib/tray"
|
||||
import { logger, revealLogFile } from "~/logger"
|
||||
import { cleanupOldRender, loadDynamicRenderEntry } from "~/updater/hot-updater"
|
||||
|
||||
import { downloadFile } from "../lib/download"
|
||||
import { i18n } from "../lib/i18n"
|
||||
import type { RendererHandlers } from "../renderer-handlers"
|
||||
import { checkForAppUpdates, quitAndInstall } from "../updater"
|
||||
import { getMainWindow } from "../window"
|
||||
import { t } from "./_instance"
|
||||
|
||||
export const appRoute = {
|
||||
saveToEagle: t.procedure
|
||||
.input<{ url: string; mediaUrls: string[] }>()
|
||||
.action(async ({ input }) => {
|
||||
try {
|
||||
const res = await fetch("http://localhost:41595/api/item/addFromURLs", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
items: input.mediaUrls?.map((media) => ({
|
||||
url: media,
|
||||
website: input.url,
|
||||
headers: {
|
||||
referer: input.url,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
})
|
||||
return await res.json()
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}),
|
||||
|
||||
invalidateQuery: t.procedure
|
||||
.input<(string | number | undefined)[]>()
|
||||
.action(async ({ input }) => {
|
||||
const mainWindow = getMainWindow()
|
||||
if (!mainWindow) return
|
||||
const handlers = getRendererHandlers<RendererHandlers>(mainWindow.webContents)
|
||||
handlers.invalidateQuery.send(input)
|
||||
}),
|
||||
|
||||
windowAction: t.procedure
|
||||
.input<{ action: "close" | "minimize" | "maximum" }>()
|
||||
.action(async ({ input, context }) => {
|
||||
if (context.sender.getType() === "window") {
|
||||
const window: BrowserWindow | null = (context.sender as Sender).getOwnerBrowserWindow()
|
||||
|
||||
if (!window) return
|
||||
switch (input.action) {
|
||||
case "close": {
|
||||
window.close()
|
||||
break
|
||||
}
|
||||
case "minimize": {
|
||||
window.minimize()
|
||||
break
|
||||
}
|
||||
|
||||
case "maximum": {
|
||||
// FIXME: this is a electron bug, see https://github.com/RSSNext/Follow/issues/231
|
||||
// So in this way we use a workaround to fix it, that is manually resize the window
|
||||
// Comemnt the manually handle logic and disable backgroundMaterial for now
|
||||
// if (isWindows11) {
|
||||
// const display = screen.getDisplayMatching(window.getBounds())
|
||||
// const size = display.workAreaSize
|
||||
|
||||
// const isMaximized = size.height === window.getSize()[1]
|
||||
|
||||
// const storeKey = Symbol.for("maximized")
|
||||
// if (isMaximized) {
|
||||
// const stored = window[storeKey]
|
||||
// if (!stored) return
|
||||
|
||||
// window.setResizable(true)
|
||||
// window.setMovable(true)
|
||||
|
||||
// window.setBounds(
|
||||
// {
|
||||
// width: stored.size[0],
|
||||
// height: stored.size[1],
|
||||
// x: stored.position[0],
|
||||
// y: stored.position[1],
|
||||
// },
|
||||
// true,
|
||||
// )
|
||||
|
||||
// delete window[storeKey]
|
||||
// } else {
|
||||
// const currentWindowSize = window.getSize()
|
||||
// const currentWindowPosition = window.getPosition()
|
||||
// window[storeKey] = {
|
||||
// size: currentWindowSize,
|
||||
// position: currentWindowPosition,
|
||||
// }
|
||||
|
||||
// // Maually Resize
|
||||
// const { workArea } = display
|
||||
|
||||
// window.setBounds(
|
||||
// {
|
||||
// x: workArea.x,
|
||||
// y: workArea.y,
|
||||
// width: workArea.width,
|
||||
// height: workArea.height,
|
||||
// },
|
||||
// true,
|
||||
// )
|
||||
|
||||
// window.setResizable(false)
|
||||
// window.setMovable(false)
|
||||
// }
|
||||
|
||||
// return
|
||||
// }
|
||||
|
||||
if (window.isMaximized()) {
|
||||
window.unmaximize()
|
||||
} else {
|
||||
window.maximize()
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
quitAndInstall: t.procedure.action(async () => {
|
||||
quitAndInstall()
|
||||
}),
|
||||
|
||||
/// clipboard
|
||||
|
||||
readClipboard: t.procedure.action(async () => clipboard.readText()),
|
||||
/// search
|
||||
search: t.procedure
|
||||
.input<{
|
||||
text: string
|
||||
options: Electron.FindInPageOptions
|
||||
}>()
|
||||
.action(async ({ input, context }) => {
|
||||
const { sender: webContents } = context
|
||||
|
||||
const { promise, resolve } = Promise.withResolvers<Electron.Result | null>()
|
||||
|
||||
let requestId = -1
|
||||
webContents.once("found-in-page", (_, result) => {
|
||||
resolve(result.requestId === requestId ? result : null)
|
||||
})
|
||||
requestId = webContents.findInPage(input.text, input.options)
|
||||
return promise
|
||||
}),
|
||||
clearSearch: t.procedure.action(async ({ context: { sender: webContents } }) => {
|
||||
webContents.stopFindInPage("keepSelection")
|
||||
}),
|
||||
|
||||
download: t.procedure.input<string>().action(async ({ input, context: { sender } }) => {
|
||||
const result = await dialog.showSaveDialog({
|
||||
defaultPath: input.split("/").pop(),
|
||||
})
|
||||
if (result.canceled) return
|
||||
|
||||
// return result.filePath;
|
||||
await downloadFile(input, result.filePath).catch((err) => {
|
||||
const senderWindow = (sender as Sender).getOwnerBrowserWindow()
|
||||
if (!senderWindow) return
|
||||
callWindowExpose(senderWindow).toast.error("Download failed!", {
|
||||
duration: 1000,
|
||||
})
|
||||
throw err
|
||||
})
|
||||
|
||||
const senderWindow = (sender as Sender).getOwnerBrowserWindow()
|
||||
if (!senderWindow) return
|
||||
callWindowExpose(senderWindow).toast.success("Download success!", {
|
||||
duration: 1000,
|
||||
})
|
||||
}),
|
||||
|
||||
getAppPath: t.procedure.action(async () => app.getAppPath()),
|
||||
resolveAppAsarPath: t.procedure.input<string>().action(async ({ input }) => {
|
||||
return filePathToAppUrl(path.resolve(app.getAppPath(), input))
|
||||
}),
|
||||
|
||||
switchAppLocale: t.procedure.input<string>().action(async ({ input }) => {
|
||||
i18n.changeLanguage(input)
|
||||
registerMenuAndContextMenu()
|
||||
registerAppTray()
|
||||
|
||||
app.commandLine.appendSwitch("lang", input)
|
||||
}),
|
||||
|
||||
clearAllData: t.procedure.action(clearAllData),
|
||||
|
||||
saveToObsidian: t.procedure
|
||||
.input<{
|
||||
url: string
|
||||
title: string
|
||||
content: string
|
||||
author: string
|
||||
publishedAt: string
|
||||
vaultPath: string
|
||||
}>()
|
||||
.action(async ({ input }) => {
|
||||
try {
|
||||
const { url, title, content, author, publishedAt, vaultPath } = input
|
||||
|
||||
const fileName = `${(title || publishedAt).trim().slice(0, 20).replaceAll("/", "-")}.md`
|
||||
const filePath = path.join(vaultPath, fileName)
|
||||
const exists = fs.existsSync(filePath)
|
||||
if (exists) {
|
||||
return { success: false, error: "File already exists" }
|
||||
}
|
||||
|
||||
const markdown = `---
|
||||
url: ${url}
|
||||
author: ${author}
|
||||
publishedAt: ${publishedAt}
|
||||
---
|
||||
|
||||
# ${title}
|
||||
|
||||
${content}
|
||||
`
|
||||
|
||||
await fsp.writeFile(filePath, markdown, "utf-8")
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Failed to save to Obsidian:", error)
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
return { success: false, error: errorMessage }
|
||||
}
|
||||
}),
|
||||
|
||||
getAppVersion: t.procedure.action(async () => {
|
||||
return app.getVersion()
|
||||
}),
|
||||
rendererUpdateReload: t.procedure.action(async () => {
|
||||
const __dirname = fileURLToPath(new URL(".", import.meta.url))
|
||||
const allWindows = BrowserWindow.getAllWindows()
|
||||
const dynamicRenderEntry = loadDynamicRenderEntry()
|
||||
|
||||
const appLoadEntry =
|
||||
dynamicRenderEntry || path.resolve(__dirname, "../../../../../renderer/index.html")
|
||||
logger.info("appLoadEntry", appLoadEntry)
|
||||
const mainWindow = getMainWindow()
|
||||
|
||||
for (const window of allWindows) {
|
||||
if (window === mainWindow) {
|
||||
if (DEV) {
|
||||
logger.verbose("[rendererUpdateReload]: skip reload in dev")
|
||||
break
|
||||
}
|
||||
window.loadFile(appLoadEntry)
|
||||
} else window.destroy()
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
cleanupOldRender()
|
||||
}, 1000)
|
||||
}),
|
||||
|
||||
getCacheSize: t.procedure.action(async () => {
|
||||
return getCacheSize()
|
||||
}),
|
||||
openCacheFolder: t.procedure.action(async () => {
|
||||
const dir = path.join(app.getPath("userData"), "cache")
|
||||
shell.openPath(dir)
|
||||
}),
|
||||
getCacheLimit: t.procedure.action(async () => {
|
||||
return store.get(StoreKey.CacheSizeLimit)
|
||||
}),
|
||||
|
||||
clearCache: t.procedure.action(async () => {
|
||||
const cachePath = path.join(app.getPath("userData"), "cache", "Cache_Data")
|
||||
if (process.platform === "win32") {
|
||||
// Request elevation on Windows
|
||||
|
||||
try {
|
||||
// Create a bat file to delete cache with elevated privileges
|
||||
const batPath = path.join(app.getPath("temp"), "clear_cache.bat")
|
||||
await fsp.writeFile(batPath, `@echo off\nrd /s /q "${cachePath}"\ndel "%~f0"`, "utf-8")
|
||||
|
||||
// Execute the bat file with admin privileges
|
||||
await shell.openPath(batPath)
|
||||
return
|
||||
} catch (err) {
|
||||
logger.error("Failed to clear cache with elevation", { error: err })
|
||||
}
|
||||
}
|
||||
await fsp.rm(cachePath, { recursive: true, force: true }).catch(() => {
|
||||
logger.error("Failed to clear cache")
|
||||
})
|
||||
}),
|
||||
|
||||
limitCacheSize: t.procedure.input<number>().action(async ({ input }) => {
|
||||
logger.info("set limitCacheSize", input)
|
||||
if (input === 0) {
|
||||
store.delete(StoreKey.CacheSizeLimit)
|
||||
} else {
|
||||
store.set(StoreKey.CacheSizeLimit, input)
|
||||
}
|
||||
}),
|
||||
|
||||
revealLogFile: t.procedure.action(async () => {
|
||||
return revealLogFile()
|
||||
}),
|
||||
|
||||
checkForUpdates: t.procedure.action(async () => {
|
||||
return checkForAppUpdates()
|
||||
}),
|
||||
}
|
||||
|
||||
interface Sender extends Electron.WebContents {
|
||||
getOwnerBrowserWindow: () => Electron.BrowserWindow | null
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { deleteNotificationsToken, updateNotificationsToken } from "~/lib/user"
|
||||
|
||||
import { t } from "./_instance"
|
||||
|
||||
export const authRoute = {
|
||||
sessionChanged: t.procedure.action(async () => {
|
||||
await updateNotificationsToken()
|
||||
}),
|
||||
|
||||
signOut: t.procedure.action(async () => {
|
||||
await deleteNotificationsToken()
|
||||
}),
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { t } from "./_instance"
|
||||
|
||||
export const debugRoute = {
|
||||
inspectElement: t.procedure
|
||||
.input<{ x: number; y: number }>()
|
||||
.action(async ({ input, context }) => {
|
||||
context.sender.inspectElement(input.x, input.y)
|
||||
}),
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { UNREAD_BACKGROUND_POLLING_INTERVAL } from "../constants/app"
|
||||
import { apiClient } from "../lib/api-client"
|
||||
import { setDockCount } from "../lib/dock"
|
||||
import { sleep } from "../lib/utils"
|
||||
import { t } from "./_instance"
|
||||
|
||||
const pollingMap = {
|
||||
unread: false,
|
||||
}
|
||||
export const dockRoute = {
|
||||
pollingUpdateUnreadCount: t.procedure.action(pollingUpdateUnreadCount),
|
||||
|
||||
cancelPollingUpdateUnreadCount: t.procedure.action(cancelPollingUpdateUnreadCount),
|
||||
|
||||
updateUnreadCount: t.procedure.action(async () => {
|
||||
await updateUnreadCount()
|
||||
}),
|
||||
}
|
||||
|
||||
async function updateUnreadCount() {
|
||||
const res = await apiClient.reads["total-count"].$get()
|
||||
setDockCount(res.data.count)
|
||||
}
|
||||
|
||||
export async function pollingUpdateUnreadCount() {
|
||||
if (pollingMap.unread) {
|
||||
return
|
||||
}
|
||||
|
||||
pollingMap.unread = true
|
||||
while (pollingMap.unread) {
|
||||
await sleep(UNREAD_BACKGROUND_POLLING_INTERVAL)
|
||||
if (pollingMap.unread) {
|
||||
await updateUnreadCount()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function cancelPollingUpdateUnreadCount() {
|
||||
pollingMap.unread = false
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { appRoute } from "./app"
|
||||
import { authRoute } from "./auth"
|
||||
import { debugRoute } from "./debug"
|
||||
import { dockRoute } from "./dock"
|
||||
import { menuRoute } from "./menu"
|
||||
import { readerRoute } from "./reader"
|
||||
import { settingRoute } from "./setting"
|
||||
|
||||
export const router = {
|
||||
...debugRoute,
|
||||
...menuRoute,
|
||||
...settingRoute,
|
||||
...appRoute,
|
||||
...dockRoute,
|
||||
...readerRoute,
|
||||
...authRoute,
|
||||
}
|
||||
|
||||
export type Router = typeof router
|
||||
@@ -1,107 +0,0 @@
|
||||
import { platform } from "node:os"
|
||||
|
||||
import type { ActionContext } from "@egoist/tipc/main"
|
||||
import type { MenuItemConstructorOptions, MessageBoxOptions } from "electron"
|
||||
import { dialog, Menu, ShareMenu, shell } from "electron"
|
||||
|
||||
import { t } from "./_instance"
|
||||
|
||||
type SerializableMenuItem = Omit<MenuItemConstructorOptions, "click" | "submenu"> & {
|
||||
// id: string
|
||||
submenu?: SerializableMenuItem[]
|
||||
}
|
||||
|
||||
function normalizeMenuItems(
|
||||
items: SerializableMenuItem[],
|
||||
context: ActionContext,
|
||||
path = [] as number[],
|
||||
): MenuItemConstructorOptions[] {
|
||||
return items.map((item, index) => {
|
||||
const curPath = [...path, index]
|
||||
return {
|
||||
...item,
|
||||
click() {
|
||||
context.sender.send("menu-click", {
|
||||
id: item.id,
|
||||
path: curPath,
|
||||
})
|
||||
},
|
||||
submenu: item.submenu ? normalizeMenuItems(item.submenu, context, curPath) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const menuRoute = {
|
||||
showContextMenu: t.procedure
|
||||
.input<{
|
||||
items: SerializableMenuItem[]
|
||||
}>()
|
||||
.action(({ input, context }) => {
|
||||
const defer = Promise.withResolvers<void>()
|
||||
const normalizedMenuItems = normalizeMenuItems(input.items, context)
|
||||
|
||||
// See https://www.electronjs.org/docs/latest/api/menu
|
||||
const menu = Menu.buildFromTemplate(normalizedMenuItems)
|
||||
menu.popup({
|
||||
callback: () => defer.resolve(),
|
||||
})
|
||||
return defer.promise
|
||||
}),
|
||||
|
||||
/** @deprecated */
|
||||
showConfirmDialog: t.procedure
|
||||
.input<{
|
||||
title: string
|
||||
message: string
|
||||
options?: Partial<MessageBoxOptions>
|
||||
}>()
|
||||
.action(async ({ input }) => {
|
||||
const result = await dialog.showMessageBox({
|
||||
message: input.title,
|
||||
detail: input.message,
|
||||
buttons: ["Confirm", "Cancel"],
|
||||
...input.options,
|
||||
})
|
||||
return result.response === 0
|
||||
}),
|
||||
|
||||
showShareMenu: t.procedure.input<string>().action(async ({ input, context }) => {
|
||||
// Check if ShareMenu is supported (macOS only)
|
||||
if (platform() === "darwin" && ShareMenu) {
|
||||
const menu = new ShareMenu({
|
||||
urls: [input],
|
||||
})
|
||||
|
||||
menu.popup({
|
||||
callback: () => {
|
||||
context.sender.send("menu-closed")
|
||||
},
|
||||
})
|
||||
} else {
|
||||
// Fallback for Windows and Linux - create a context menu with share options
|
||||
const shareItems: MenuItemConstructorOptions[] = [
|
||||
{
|
||||
label: "Copy Link",
|
||||
click: () => {
|
||||
require("electron").clipboard.writeText(input)
|
||||
context.sender.send("menu-closed")
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Open in Browser",
|
||||
click: () => {
|
||||
shell.openExternal(input)
|
||||
context.sender.send("menu-closed")
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
const menu = Menu.buildFromTemplate(shareItems)
|
||||
menu.popup({
|
||||
callback: () => {
|
||||
context.sender.send("menu-closed")
|
||||
},
|
||||
})
|
||||
}
|
||||
}),
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { readability } from "@follow-app/readability"
|
||||
import { app, BrowserWindow } from "electron"
|
||||
import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts"
|
||||
import type { ModelResult } from "vscode-languagedetection"
|
||||
|
||||
import { detectCodeStringLanguage } from "~/modules/language-detection"
|
||||
|
||||
import { t } from "./_instance"
|
||||
|
||||
const tts = new MsEdgeTTS()
|
||||
|
||||
export const readerRoute = {
|
||||
readability: t.procedure.input<{ url: string }>().action(async ({ input }) => {
|
||||
const { url } = input
|
||||
|
||||
if (!url) {
|
||||
return null
|
||||
}
|
||||
const result = await readability(url)
|
||||
|
||||
return result
|
||||
}),
|
||||
|
||||
tts: t.procedure
|
||||
.input<{
|
||||
id: string
|
||||
text: string
|
||||
voice: string
|
||||
}>()
|
||||
.action(async ({ input, context: { sender } }) => {
|
||||
const { id, text, voice } = input
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
|
||||
const window = BrowserWindow.fromWebContents(sender)
|
||||
if (!window) return
|
||||
|
||||
// It's ok to set voice every time, because it will be cached by msedge-tts
|
||||
// Don't know why webm is not working, using mp3 instead
|
||||
await tts
|
||||
.setMetadata(voice, OUTPUT_FORMAT.AUDIO_24KHZ_96KBITRATE_MONO_MP3)
|
||||
.catch((error: unknown) => {
|
||||
console.error("Failed to set voice", error)
|
||||
if (error instanceof Error) {
|
||||
return callWindowExpose(window).toast.error(error.message, {
|
||||
duration: 1000,
|
||||
})
|
||||
}
|
||||
return callWindowExpose(window).toast.error("Failed to set voice", {
|
||||
duration: 1000,
|
||||
})
|
||||
})
|
||||
|
||||
const dirPath = path.join(app.getPath("userData"), "Cache", "tts", id)
|
||||
const possibleFilePathList = ["mp3", "webm"].map((ext) => {
|
||||
return path.join(dirPath, `audio.${ext}`)
|
||||
})
|
||||
const filePath = possibleFilePathList.find((p) => fs.existsSync(p))
|
||||
if (filePath) {
|
||||
return filePath
|
||||
} else {
|
||||
fs.mkdirSync(dirPath, { recursive: true })
|
||||
const { audioFilePath } = await tts.toFile(dirPath, text)
|
||||
return audioFilePath
|
||||
}
|
||||
}),
|
||||
|
||||
getVoices: t.procedure.action(async ({ context: { sender } }) => {
|
||||
const window = BrowserWindow.fromWebContents(sender)
|
||||
try {
|
||||
const voices = await tts.getVoices()
|
||||
return voices
|
||||
} catch (error) {
|
||||
console.error("Failed to get voices", error)
|
||||
if (!window) return
|
||||
if (error instanceof Error) {
|
||||
void callWindowExpose(window).toast.error(error.message, { duration: 1000 })
|
||||
return
|
||||
}
|
||||
callWindowExpose(window).toast.error("Failed to get voices", { duration: 1000 })
|
||||
}
|
||||
}),
|
||||
|
||||
detectCodeStringLanguage: t.procedure
|
||||
.input<{ codeString: string }>()
|
||||
.action(async ({ input }) => {
|
||||
const { codeString } = input
|
||||
const languages = detectCodeStringLanguage(codeString)
|
||||
|
||||
let finalLanguage: ModelResult | undefined
|
||||
for await (const language of languages) {
|
||||
if (!finalLanguage) {
|
||||
finalLanguage = language
|
||||
continue
|
||||
}
|
||||
if (language.confidence > finalLanguage.confidence) {
|
||||
finalLanguage = language
|
||||
}
|
||||
}
|
||||
|
||||
return finalLanguage
|
||||
}),
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { createRequire } from "node:module"
|
||||
|
||||
import { app, nativeTheme } from "electron"
|
||||
|
||||
import { START_IN_TRAY_ARGS } from "~/constants/app"
|
||||
import { getTrayConfig, setTrayConfig } from "~/lib/tray"
|
||||
|
||||
import { setDockCount } from "../lib/dock"
|
||||
import { setProxyConfig, updateProxy } from "../lib/proxy"
|
||||
import { store } from "../lib/store"
|
||||
import { showSetting } from "../window"
|
||||
import { t } from "./_instance"
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
export const settingRoute = {
|
||||
getLoginItemSettings: t.procedure.input<void>().action(async () => app.getLoginItemSettings()),
|
||||
setLoginItemSettings: t.procedure.input<boolean>().action(async ({ input }) => {
|
||||
app.setLoginItemSettings({
|
||||
openAtLogin: input,
|
||||
openAsHidden: true,
|
||||
args: [START_IN_TRAY_ARGS],
|
||||
})
|
||||
}),
|
||||
openSettingWindow: t.procedure.action(async () => showSetting()),
|
||||
getSystemFonts: t.procedure.action(
|
||||
async (): Promise<string[]> =>
|
||||
new Promise((resolve) => {
|
||||
// NOTE: should external font-list deps
|
||||
// use `require` to avoid bundling, vite behavior
|
||||
require("font-list")
|
||||
.getFonts()
|
||||
.then((fonts) => {
|
||||
resolve(fonts.map((font) => font.replaceAll('"', "")))
|
||||
})
|
||||
}),
|
||||
),
|
||||
getAppearance: t.procedure.action(async () => nativeTheme.themeSource),
|
||||
setAppearance: t.procedure.input<"light" | "dark" | "system">().action(async ({ input }) => {
|
||||
nativeTheme.themeSource = input
|
||||
|
||||
store.set("appearance", input)
|
||||
}),
|
||||
getMinimizeToTray: t.procedure.action(async () => getTrayConfig()),
|
||||
setMinimizeToTray: t.procedure.input<boolean>().action(async ({ input }) => setTrayConfig(input)),
|
||||
setDockBadge: t.procedure.input<number>().action(async ({ input }) => {
|
||||
setDockCount(input)
|
||||
}),
|
||||
getProxyConfig: t.procedure.action(async () => store.get("proxy")),
|
||||
setProxyConfig: t.procedure.input<string>().action(async ({ input }) => {
|
||||
const result = setProxyConfig(input)
|
||||
updateProxy()
|
||||
return result
|
||||
}),
|
||||
getMessagingToken: t.procedure.action(async () => {
|
||||
return store.get("notifications-credentials")
|
||||
}),
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getRendererHandlers } from "@egoist/tipc/main"
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { DEV } from "@follow/shared/constants"
|
||||
import { autoUpdater as defaultAutoUpdater } from "electron-updater"
|
||||
|
||||
@@ -7,7 +7,6 @@ import { canUpdateRender, CanUpdateRenderState, hotUpdateRender } from "~/update
|
||||
|
||||
import { channel, isWindows } from "../env"
|
||||
import { logger } from "../logger"
|
||||
import type { RendererHandlers } from "../renderer-handlers"
|
||||
import { destroyMainWindow, getMainWindow } from "../window"
|
||||
import { appUpdaterConfig } from "./configs"
|
||||
import { CustomGitHubProvider } from "./custom-github-provider"
|
||||
@@ -145,9 +144,9 @@ export const registerUpdater = async () => {
|
||||
|
||||
const mainWindow = getMainWindow()
|
||||
if (!mainWindow) return
|
||||
const handlers = getRendererHandlers<RendererHandlers>(mainWindow.webContents)
|
||||
const handlers = callWindowExpose(mainWindow)
|
||||
|
||||
handlers.updateDownloaded.send()
|
||||
handlers.updateDownloaded()
|
||||
})
|
||||
autoUpdater.on("error", (e) => {
|
||||
logger.error("Error while updating client", e)
|
||||
|
||||
@@ -12,12 +12,12 @@ import type { Event } from "electron/main"
|
||||
import { START_IN_TRAY_ARGS } from "./constants/app"
|
||||
import { isMacOS, isWindows, isWindows11 } from "./env"
|
||||
import { filePathToAppUrl, getIconPath } from "./helper"
|
||||
import { services } from "./ipc"
|
||||
import { t } from "./lib/i18n"
|
||||
import { store } from "./lib/store"
|
||||
import { getTrayConfig } from "./lib/tray"
|
||||
import { refreshBound } from "./lib/utils"
|
||||
import { logger } from "./logger"
|
||||
import { cancelPollingUpdateUnreadCount, pollingUpdateUnreadCount } from "./tipc/dock"
|
||||
import { loadDynamicRenderEntry } from "./updater/hot-updater"
|
||||
|
||||
const windows = {
|
||||
@@ -313,7 +313,7 @@ export const createMainWindow = () => {
|
||||
})
|
||||
|
||||
window.on("show", () => {
|
||||
cancelPollingUpdateUnreadCount()
|
||||
services.dock.pollingUpdateUnreadCount()
|
||||
|
||||
const caller = callWindowExpose(window)
|
||||
|
||||
@@ -325,7 +325,7 @@ export const createMainWindow = () => {
|
||||
const settings = await caller.getUISettings()
|
||||
|
||||
if (settings?.showDockBadge) {
|
||||
pollingUpdateUnreadCount()
|
||||
services.dock.pollingUpdateUnreadCount()
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"noUnusedParameters": false,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"experimentalDecorators": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@pkg": ["../../package.json"],
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "6.3.1",
|
||||
"@dnd-kit/sortable": "10.0.0",
|
||||
"@egoist/tipc": "0.3.2",
|
||||
"@electron-toolkit/preload": "3.0.2",
|
||||
"@follow/electron-main": "workspace:*",
|
||||
"@follow/shared": "workspace:*",
|
||||
|
||||
@@ -5,33 +5,15 @@ import { cn, getOS } from "@follow/utils/utils"
|
||||
import { useEffect } from "react"
|
||||
import { Outlet } from "react-router"
|
||||
|
||||
import { queryClient } from "~/lib/query-client"
|
||||
|
||||
import { useAppIsReady } from "./atoms/app"
|
||||
import { useUISettingKey } from "./atoms/settings/ui"
|
||||
import { navigateEntry } from "./hooks/biz/useNavigateEntry"
|
||||
import { applyAfterReadyCallbacks } from "./initialize/queue"
|
||||
import { removeAppSkeleton } from "./lib/app"
|
||||
import { appLog } from "./lib/log"
|
||||
import { Titlebar } from "./modules/app/Titlebar"
|
||||
import { RootProviders } from "./providers/root-providers"
|
||||
import { handlers } from "./tipc"
|
||||
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
const cleanup = handlers?.invalidateQuery.listen((queryKey) => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey,
|
||||
})
|
||||
})
|
||||
|
||||
handlers?.navigateEntry.listen((options) => {
|
||||
navigateEntry(options)
|
||||
})
|
||||
|
||||
return cleanup
|
||||
}, [])
|
||||
|
||||
const windowsElectron = IN_ELECTRON && getOS() === "Windows"
|
||||
return (
|
||||
<RootProviders>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { getOS, transformShortcut } from "@follow/utils/utils"
|
||||
import { atom } from "jotai"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { createAtomHooks } from "~/lib/jotai"
|
||||
import type { ElectronMenuItem } from "~/lib/native-menu"
|
||||
import { showElectronContextMenu } from "~/lib/native-menu"
|
||||
@@ -118,7 +118,7 @@ function withDebugMenu(menuItems: Array<FollowMenuItem>, e: MouseEvent | React.M
|
||||
new MenuItemText({
|
||||
label: "Inspect Element",
|
||||
click: () => {
|
||||
tipcClient?.inspectElement({
|
||||
ipcServices?.debug.inspectElement({
|
||||
x: e.pageX,
|
||||
y: e.pageY,
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
} from "shiki"
|
||||
|
||||
import { useUISettingKey } from "~/atoms/settings/ui"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
import { CopyButton } from "../../button/CopyButton"
|
||||
import { getLanguageIcon } from "../constants"
|
||||
@@ -57,7 +57,7 @@ export const ShikiHighLighter: FC<ShikiProps> = (props) => {
|
||||
}
|
||||
|
||||
function guessLanguage() {
|
||||
return tipcClient?.detectCodeStringLanguage({ codeString: code }).then((result) => {
|
||||
return ipcServices?.reader.detectCodeStringLanguage({ codeString: code }).then((result) => {
|
||||
if (!result) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import { useWindowSize } from "usehooks-ts"
|
||||
|
||||
import { m } from "~/components/common/Motion"
|
||||
import { COPY_MAP } from "~/constants"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { replaceImgUrlIfNeed } from "~/lib/img-proxy"
|
||||
|
||||
import { FixedModalCloseButton } from "../modal/components/close"
|
||||
@@ -114,7 +114,7 @@ const Wrapper: Component<{
|
||||
<ActionButton
|
||||
tooltip={t("common:words.download")}
|
||||
onClick={() => {
|
||||
tipcClient?.download(src)
|
||||
ipcServices?.app.download(src)
|
||||
}}
|
||||
>
|
||||
<i className="i-mgc-download-2-cute-re" />
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
import { useShowSourceContent } from "~/atoms/source-content"
|
||||
import { useUserRole, whoami } from "~/atoms/user"
|
||||
import { apiClient } from "~/lib/api-fetch"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { COMMAND_ID } from "~/modules/command/commands/id"
|
||||
import { getCommand, useRunCommandFn } from "~/modules/command/hooks/use-command"
|
||||
import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding"
|
||||
@@ -58,7 +58,7 @@ export const toggleEntryReadability = async ({ id, url }: { id: string; url: str
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
const result = await tipcClient?.readability({ url })
|
||||
const result = await ipcServices?.reader.readability({ url })
|
||||
if (result) {
|
||||
setReadabilityContent({
|
||||
[id]: result,
|
||||
|
||||
@@ -2,12 +2,12 @@ import { IN_ELECTRON } from "@follow/shared/constants"
|
||||
import { atom, useAtomValue, useSetAtom } from "jotai"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
const proxyAtom = atom("")
|
||||
|
||||
proxyAtom.onMount = (setAtom) => {
|
||||
tipcClient?.getProxyConfig().then((proxy) => {
|
||||
ipcServices?.setting.getProxyConfig().then((proxy) => {
|
||||
setAtom(proxy || "")
|
||||
})
|
||||
}
|
||||
@@ -22,7 +22,7 @@ export const useSetProxy = () => {
|
||||
return
|
||||
}
|
||||
setProxy(proxyString)
|
||||
tipcClient?.setProxyConfig(proxyString)
|
||||
ipcServices?.setting.setProxyConfig(proxyString)
|
||||
},
|
||||
[setProxy],
|
||||
)
|
||||
|
||||
@@ -2,13 +2,16 @@ import { IN_ELECTRON } from "@follow/shared/constants"
|
||||
import { atom, useAtomValue, useSetAtom } from "jotai"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
const minimizeToTrayAtom = atom<boolean>(true)
|
||||
|
||||
minimizeToTrayAtom.onMount = (setAtom) => {
|
||||
tipcClient?.getMinimizeToTray().then((proxy: boolean) => {
|
||||
setAtom(proxy)
|
||||
const result = ipcServices?.setting.getMinimizeToTray()
|
||||
Promise.resolve(result).then((proxy) => {
|
||||
if (typeof proxy === "boolean") {
|
||||
setAtom(proxy)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -20,7 +23,7 @@ export const useSetMinimizeToTray = () => {
|
||||
(value: boolean) => {
|
||||
if (!IN_ELECTRON) return
|
||||
setMinimizeToTray(value)
|
||||
tipcClient?.setMinimizeToTray(value)
|
||||
ipcServices?.setting.setMinimizeToTray(value)
|
||||
},
|
||||
[setMinimizeToTray],
|
||||
)
|
||||
|
||||
@@ -8,14 +8,14 @@ import {
|
||||
import { IN_ELECTRON } from "@follow/shared/constants"
|
||||
import { useCallback, useLayoutEffect } from "react"
|
||||
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
const useSyncThemeElectron = () => {
|
||||
const appIsDark = useDarkQuery()
|
||||
const setTheme = internal_useSetTheme()
|
||||
useLayoutEffect(() => {
|
||||
let isMounted = true
|
||||
tipcClient?.getAppearance().then((appearance) => {
|
||||
ipcServices?.setting.getAppearance().then((appearance) => {
|
||||
if (!isMounted) return
|
||||
setTheme(appearance)
|
||||
disableTransition(["[role=switch]>*"])()
|
||||
@@ -38,7 +38,7 @@ export const useSetTheme = () => {
|
||||
setTheme(colorMode)
|
||||
|
||||
if (IN_ELECTRON) {
|
||||
tipcClient?.setAppearance(colorMode)
|
||||
ipcServices?.setting.setAppearance(colorMode)
|
||||
}
|
||||
},
|
||||
[setTheme],
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
import { createClient } from "@egoist/tipc/renderer"
|
||||
import type { Router } from "@follow/electron-main"
|
||||
import type { IpcServices } from "@follow/electron-main"
|
||||
|
||||
export const tipcClient = window.electron
|
||||
? createClient<Router>({
|
||||
ipcInvoke: window.electron.ipcRenderer.invoke,
|
||||
})
|
||||
: null
|
||||
function createIpcProxy(): IpcServices | null {
|
||||
if (!window.electron) {
|
||||
return null
|
||||
}
|
||||
|
||||
return new Proxy({} as IpcServices, {
|
||||
get(target, groupName: string) {
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_, methodName: string) {
|
||||
return (...args: any[]) => {
|
||||
const channel = `${groupName}.${methodName}`
|
||||
return window.electron!.ipcRenderer.invoke(channel, args[0])
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const ipcServices = createIpcProxy()
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { RendererHandlers } from "@follow/electron-main"
|
||||
|
||||
type EventCallback<T> = (data: T) => void
|
||||
|
||||
export function createEventHandlers() {
|
||||
if (!window.electron) {
|
||||
// Web fallback - return empty handlers
|
||||
return {
|
||||
invalidateQuery: {
|
||||
listen: () => () => {},
|
||||
},
|
||||
updateDownloaded: {
|
||||
listen: () => () => {},
|
||||
},
|
||||
navigateEntry: {
|
||||
listen: () => () => {},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
invalidateQuery: {
|
||||
listen: (callback: EventCallback<Parameters<RendererHandlers["invalidateQuery"]>[0]>) => {
|
||||
const channel = "renderer-event:invalidateQuery"
|
||||
const handler = (_: any, data: Parameters<RendererHandlers["invalidateQuery"]>[0]) => {
|
||||
callback(data)
|
||||
}
|
||||
window.electron!.ipcRenderer.on(channel, handler)
|
||||
return () => {
|
||||
window.electron!.ipcRenderer.removeListener(channel, handler)
|
||||
}
|
||||
},
|
||||
},
|
||||
updateDownloaded: {
|
||||
listen: (callback: EventCallback<void>) => {
|
||||
const channel = "renderer-event:updateDownloaded"
|
||||
const handler = () => {
|
||||
callback()
|
||||
}
|
||||
window.electron!.ipcRenderer.on(channel, handler)
|
||||
return () => {
|
||||
window.electron!.ipcRenderer.removeListener(channel, handler)
|
||||
}
|
||||
},
|
||||
},
|
||||
navigateEntry: {
|
||||
listen: (callback: EventCallback<Parameters<RendererHandlers["navigateEntry"]>[0]>) => {
|
||||
const channel = "renderer-event:navigateEntry"
|
||||
const handler = (_: any, data: Parameters<RendererHandlers["navigateEntry"]>[0]) => {
|
||||
callback(data)
|
||||
}
|
||||
window.electron!.ipcRenderer.on(channel, handler)
|
||||
return () => {
|
||||
window.electron!.ipcRenderer.removeListener(channel, handler)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { defaultResources } from "~/@types/default-resource"
|
||||
import { i18nAtom, langChain, LocaleCache } from "~/i18n"
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
|
||||
import { tipcClient } from "./client"
|
||||
import { ipcServices } from "./client"
|
||||
import { appLog } from "./log"
|
||||
|
||||
const loadingLangLock = new Set<string>()
|
||||
@@ -29,7 +29,7 @@ export const loadLanguageAndApply = async (lang: string) => {
|
||||
})
|
||||
}
|
||||
|
||||
tipcClient?.switchAppLocale(lang)
|
||||
ipcServices?.app.switchAppLocale(lang)
|
||||
|
||||
const { t } = jotaiStore.get(i18nAtom)
|
||||
if (loadingLangLock.has(lang)) return
|
||||
@@ -78,7 +78,8 @@ export const loadLanguageAndApply = async (lang: string) => {
|
||||
|
||||
if (IN_ELECTRON) {
|
||||
importFilePath =
|
||||
(await tipcClient?.resolveAppAsarPath(`dist/renderer/locales/${lang}.js`)) || ""
|
||||
(await (ipcServices as any)?.app.resolveAppAsarPath(`dist/renderer/locales/${lang}.js`)) ||
|
||||
""
|
||||
} else {
|
||||
importFilePath = `/locales/${lang}.js`
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { MenuItemConstructorOptions } from "electron"
|
||||
|
||||
import { tipcClient } from "./client"
|
||||
import { ipcServices } from "./client"
|
||||
|
||||
export type ElectronMenuItem = Omit<MenuItemConstructorOptions, "click" | "submenu"> & {
|
||||
click?: () => void
|
||||
@@ -21,34 +21,34 @@ export const showElectronContextMenu = async (items: Array<ElectronMenuItem>) =>
|
||||
},
|
||||
)
|
||||
const itemsWithoutClick = removeClick(items)
|
||||
await tipcClient?.showContextMenu({ items: itemsWithoutClick })
|
||||
await ipcServices?.menu.showContextMenu({ items: itemsWithoutClick })
|
||||
dispose()
|
||||
}
|
||||
|
||||
const removeClick = (item: ElectronMenuItem[]): ElectronMenuItem[] =>
|
||||
item.map(({ click, ...rest }) => {
|
||||
if (rest.submenu)
|
||||
return {
|
||||
...rest,
|
||||
submenu: removeClick(rest.submenu),
|
||||
}
|
||||
return rest
|
||||
})
|
||||
|
||||
// Function to retrieve the menu item based on the provided path
|
||||
const getMenuItemByPath = (items: ElectronMenuItem[], path: number[]): ElectronMenuItem | null => {
|
||||
let currentItems = items
|
||||
let currentItem: ElectronMenuItem | null = null
|
||||
function getMenuItemByPath(
|
||||
items: Array<ElectronMenuItem>,
|
||||
path: number[],
|
||||
): ElectronMenuItem | null {
|
||||
let current: ElectronMenuItem | null = null
|
||||
let currentLevel = items
|
||||
|
||||
for (const index of path) {
|
||||
if (!currentItems || index >= currentItems.length) return null
|
||||
currentItem = currentItems[index]!
|
||||
|
||||
if (currentItem.submenu && Array.isArray(currentItem.submenu)) {
|
||||
currentItems = currentItem.submenu
|
||||
} else {
|
||||
currentItems = []
|
||||
if (index >= currentLevel.length) {
|
||||
return null
|
||||
}
|
||||
current = currentLevel[index] || null
|
||||
if (current?.submenu && path.indexOf(index) < path.length - 1) {
|
||||
currentLevel = current.submenu
|
||||
}
|
||||
}
|
||||
return currentItem
|
||||
|
||||
return current
|
||||
}
|
||||
|
||||
function removeClick(items: Array<ElectronMenuItem>): Array<ElectronMenuItem> {
|
||||
return items.map((item) => ({
|
||||
...item,
|
||||
click: undefined,
|
||||
submenu: item.submenu ? removeClick(item.submenu) : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { preventDefault } from "@follow/utils/dom"
|
||||
import { useWindowState } from "~/atoms/app"
|
||||
import { useUISettingKey } from "~/atoms/settings/ui"
|
||||
import { ElECTRON_CUSTOM_TITLEBAR_HEIGHT } from "~/constants"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
export const Titlebar = () => {
|
||||
const isMaximized = useWindowState() === WindowState.MAXIMIZED
|
||||
@@ -24,7 +24,7 @@ export const Titlebar = () => {
|
||||
className="no-drag-region hover:bg-theme-item-active pointer-events-auto flex h-full w-[50px] items-center justify-center duration-200"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
tipcClient?.windowAction({ action: "minimize" })
|
||||
ipcServices?.app.windowAction({ action: "minimize" })
|
||||
}}
|
||||
>
|
||||
<i className="i-mingcute-minimize-line" />
|
||||
@@ -34,7 +34,7 @@ export const Titlebar = () => {
|
||||
type="button"
|
||||
className="no-drag-region hover:bg-theme-item-active pointer-events-auto flex h-full w-[50px] items-center justify-center duration-200"
|
||||
onClick={async () => {
|
||||
await tipcClient?.windowAction({ action: "maximum" })
|
||||
await ipcServices?.app.windowAction({ action: "maximum" })
|
||||
}}
|
||||
>
|
||||
{isMaximized ? (
|
||||
@@ -48,7 +48,7 @@ export const Titlebar = () => {
|
||||
type="button"
|
||||
className="no-drag-region pointer-events-auto flex h-full w-[50px] items-center justify-center duration-200 hover:bg-red-500 hover:!text-white"
|
||||
onClick={() => {
|
||||
tipcClient?.windowAction({ action: "close" })
|
||||
ipcServices?.app.windowAction({ action: "close" })
|
||||
}}
|
||||
>
|
||||
<i className="i-mingcute-close-line" />
|
||||
|
||||
@@ -19,7 +19,7 @@ import { useUserRole } from "~/atoms/user"
|
||||
import { toggleEntryReadability } from "~/hooks/biz/useEntryActions"
|
||||
import { navigateEntry } from "~/hooks/biz/useNavigateEntry"
|
||||
import { getRouteParams } from "~/hooks/biz/useRouteParams"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { parseHtml } from "~/lib/parse-html"
|
||||
import { useActivationModal } from "~/modules/activation"
|
||||
import { markAllByRoute } from "~/modules/entry-column/hooks/useMarkAll"
|
||||
@@ -286,7 +286,7 @@ export const useRegisterEntryCommands = () => {
|
||||
if (!entry.entries.url) return
|
||||
|
||||
if (IN_ELECTRON) {
|
||||
return tipcClient?.showShareMenu(entry.entries.url)
|
||||
return ipcServices?.menu.showShareMenu(entry.entries.url)
|
||||
} else {
|
||||
const { title, description } = entry.entries
|
||||
navigator.share({
|
||||
@@ -362,7 +362,7 @@ export const useRegisterEntryCommands = () => {
|
||||
if (!entryContent) {
|
||||
return
|
||||
}
|
||||
const filePath = await tipcClient?.tts({
|
||||
const filePath = await ipcServices?.reader.tts({
|
||||
id: entryId,
|
||||
text: parseHtml(entryContent).toText(),
|
||||
voice,
|
||||
|
||||
@@ -20,7 +20,7 @@ import { getReadabilityContent, getReadabilityStatus, ReadabilityStatus } from "
|
||||
import { getActionLanguage } from "~/atoms/settings/general"
|
||||
import { getIntegrationSettings, useIntegrationSettingKey } from "~/atoms/settings/integration"
|
||||
import { useRouteParams } from "~/hooks/biz/useRouteParams"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { parseHtml } from "~/lib/parse-html"
|
||||
import { queryClient } from "~/lib/query-client"
|
||||
import { Queries } from "~/queries"
|
||||
@@ -90,7 +90,7 @@ const useRegisterEagleCommands = () => {
|
||||
})
|
||||
return
|
||||
}
|
||||
const response = await tipcClient?.saveToEagle({
|
||||
const response = await ipcServices?.integration.saveToEagle({
|
||||
url: entry.entries.url,
|
||||
mediaUrls: entry.entries.media.map((m) => m.url),
|
||||
})
|
||||
@@ -283,7 +283,7 @@ const useRegisterObsidianCommands = () => {
|
||||
publishedAt: string
|
||||
vaultPath: string
|
||||
}) => {
|
||||
return await tipcClient?.saveToObsidian(data)
|
||||
return await ipcServices?.integration.saveToObsidian(data)
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data?.success) {
|
||||
|
||||
@@ -31,7 +31,6 @@ import { useCurrentModal, useIsInModal } from "~/components/ui/modal/stacked/hoo
|
||||
import { getRouteParams } from "~/hooks/biz/useRouteParams"
|
||||
import { useAuthQuery, useI18n } from "~/hooks/common"
|
||||
import { apiClient } from "~/lib/api-fetch"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { toastFetchError } from "~/lib/error-parser"
|
||||
import { entries as entriesQuery } from "~/queries/entries"
|
||||
import { feed as feedQuery, useFeedQuery } from "~/queries/feed"
|
||||
@@ -264,12 +263,10 @@ const FeedInnerForm = ({
|
||||
unreadActions.upsertMany(data.unread)
|
||||
}
|
||||
subscriptionQuery.all().invalidate()
|
||||
tipcClient?.invalidateQuery(subscriptionQuery.all().key)
|
||||
|
||||
const feedId = feed.id
|
||||
if (feedId) {
|
||||
feedQuery.byId({ id: feedId }).invalidate()
|
||||
tipcClient?.invalidateQuery(feedQuery.byId({ id: feedId }).key)
|
||||
}
|
||||
toast(isSubscribed ? t("feed_form.updated") : t("feed_form.followed"), {
|
||||
duration: 1000,
|
||||
|
||||
@@ -27,7 +27,6 @@ import { getGeneralSettings } from "~/atoms/settings/general"
|
||||
import { useCurrentModal } from "~/components/ui/modal/stacked/hooks"
|
||||
import { useI18n } from "~/hooks/common"
|
||||
import { apiClient } from "~/lib/api-fetch"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { getFetchErrorMessage, toastFetchError } from "~/lib/error-parser"
|
||||
import { getNewIssueUrl } from "~/lib/issues"
|
||||
import { entries as entriesQuery } from "~/queries/entries"
|
||||
@@ -241,12 +240,10 @@ const ListInnerForm = ({
|
||||
unreadActions.upsertMany(unread)
|
||||
}
|
||||
subscriptionQuery.all().invalidate()
|
||||
tipcClient?.invalidateQuery(subscriptionQuery.all().key)
|
||||
|
||||
const listId = list.id
|
||||
if (listId) {
|
||||
listsQuery.byId({ id: listId }).invalidate()
|
||||
tipcClient?.invalidateQuery(listsQuery.byId({ id: listId }).key)
|
||||
}
|
||||
toast(isSubscribed ? t("feed_form.updated") : t("feed_form.followed"), {
|
||||
duration: 1000,
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { FC } from "react"
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
|
||||
import { useDebounceCallback, useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { observeResize } from "~/lib/observe-resize"
|
||||
|
||||
const CmdFImpl: FC<{
|
||||
@@ -28,8 +28,8 @@ const CmdFImpl: FC<{
|
||||
const [scrollLeft, setScrollLeft] = useState(0)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
tipcClient?.readClipboard().then((text) => {
|
||||
if (!currentValue.current) {
|
||||
Promise.resolve(ipcServices?.app.readClipboard()).then((text) => {
|
||||
if (!currentValue.current && text) {
|
||||
setValue(text)
|
||||
}
|
||||
})
|
||||
@@ -76,20 +76,21 @@ const CmdFImpl: FC<{
|
||||
|
||||
let findNext = true
|
||||
if (!text) {
|
||||
await tipcClient?.clearSearch().finally(() => {
|
||||
Promise.resolve(ipcServices?.app.clearSearch()).finally(() => {
|
||||
if (searchId === searchIdRef.current) {
|
||||
setIsSearching(false)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
await tipcClient
|
||||
?.search({
|
||||
Promise.resolve(
|
||||
ipcServices?.app.search({
|
||||
text,
|
||||
options: {
|
||||
findNext,
|
||||
forward: dir === "forward",
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
.then((result) => {
|
||||
setMatches(result?.matches || 0)
|
||||
setActiveMatchOrdinal(result?.activeMatchOrdinal || 0)
|
||||
|
||||
@@ -16,7 +16,7 @@ import { m } from "~/components/common/Motion"
|
||||
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { getRouteParams } from "~/hooks/biz/useRouteParams"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
import { COMMAND_ID } from "../command/commands/id"
|
||||
import { useCommandBinding } from "../command/hooks/use-command-binding"
|
||||
@@ -35,7 +35,7 @@ const CmdNPanel = () => {
|
||||
})
|
||||
|
||||
useLayoutEffect(() => {
|
||||
tipcClient?.readClipboard().then((clipboardText) => {
|
||||
ipcServices?.app.readClipboard().then((clipboardText) => {
|
||||
if (clipboardText) {
|
||||
form.setValue("url", clipboardText)
|
||||
form.control._setValid()
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useTranslation } from "react-i18next"
|
||||
|
||||
import { setUISetting, useUISettingSelector } from "~/atoms/settings/ui"
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
const FALLBACK_FONT = "Default (UI Font)"
|
||||
const DEFAULT_FONT = "SN Pro"
|
||||
@@ -19,7 +19,7 @@ const CUSTOM_FONT = "Custom"
|
||||
const useFontDataElectron = () => {
|
||||
const { t } = useTranslation("settings")
|
||||
const { data } = useQuery({
|
||||
queryFn: () => tipcClient?.getSystemFonts(),
|
||||
queryFn: () => ipcServices?.setting.getSystemFonts(),
|
||||
queryKey: ["systemFonts"],
|
||||
})
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useQuery } from "@tanstack/react-query"
|
||||
import { Trans, useTranslation } from "react-i18next"
|
||||
|
||||
import { CopyButton } from "~/components/ui/button/CopyButton"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { getNewIssueUrl } from "~/lib/issues"
|
||||
|
||||
export const SettingAbout = () => {
|
||||
@@ -18,13 +18,13 @@ export const SettingAbout = () => {
|
||||
const currentEnvironment = getCurrentEnvironment().join("\n")
|
||||
const { data: appVersion } = useQuery({
|
||||
queryKey: ["appVersion"],
|
||||
queryFn: () => tipcClient?.getAppVersion() || "",
|
||||
queryFn: () => ipcServices?.app.getAppVersion(),
|
||||
})
|
||||
|
||||
const rendererVersion = PKG.version
|
||||
|
||||
const handleCheckForUpdates = () => {
|
||||
tipcClient?.checkForUpdates()
|
||||
ipcServices?.app.checkForUpdates()
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -24,7 +24,7 @@ import { z } from "zod"
|
||||
import { setGeneralSetting, useGeneralSettingValue } from "~/atoms/settings/general"
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { exportDB } from "~/database"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { queryClient } from "~/lib/query-client"
|
||||
import { clearLocalPersistStoreData } from "~/store/utils/clear"
|
||||
|
||||
@@ -117,7 +117,7 @@ export const SettingDataControl = () => {
|
||||
description: t("general.log_file.description"),
|
||||
buttonText: t("general.log_file.button"),
|
||||
action: () => {
|
||||
tipcClient?.revealLogFile()
|
||||
;(ipcServices as any)?.revealLogFile?.()
|
||||
},
|
||||
},
|
||||
]}
|
||||
@@ -247,7 +247,7 @@ const CleanElectronCache = () => {
|
||||
{t("data_control.clean_cache.button")}
|
||||
<MotionButtonBase
|
||||
onClick={() => {
|
||||
tipcClient?.openCacheFolder()
|
||||
;(ipcServices as any)?.openCacheFolder?.()
|
||||
}}
|
||||
className="center flex"
|
||||
>
|
||||
@@ -256,7 +256,7 @@ const CleanElectronCache = () => {
|
||||
</span>
|
||||
}
|
||||
action={async () => {
|
||||
await tipcClient?.clearCache()
|
||||
await (ipcServices as any)?.clearCache?.()
|
||||
queryClient.setQueryData(["app", "cache", "size"], 0)
|
||||
}}
|
||||
buttonText={t("data_control.clean_cache.button")}
|
||||
@@ -270,7 +270,7 @@ const AppCacheLimit = () => {
|
||||
const { data: cacheSize, isLoading: isLoadingCacheSize } = useQuery({
|
||||
queryKey: ["app", "cache", "size"],
|
||||
queryFn: async () => {
|
||||
const byteSize = (await tipcClient?.getCacheSize()) ?? 0
|
||||
const byteSize = (await (ipcServices as any)?.getCacheSize?.()) ?? 0
|
||||
return Math.round(byteSize / 1024 / 1024)
|
||||
},
|
||||
refetchOnMount: "always",
|
||||
@@ -282,13 +282,13 @@ const AppCacheLimit = () => {
|
||||
} = useQuery({
|
||||
queryKey: ["app", "cache", "limit"],
|
||||
queryFn: async () => {
|
||||
const size = (await tipcClient?.getCacheLimit()) ?? 0
|
||||
const size = (await (ipcServices as any)?.getCacheLimit?.()) ?? 0
|
||||
return size
|
||||
},
|
||||
})
|
||||
|
||||
const onChange = (value: number[]) => {
|
||||
tipcClient?.limitCacheSize(value[0]!)
|
||||
;(ipcServices as any)?.limitCacheSize?.(value[0]!)
|
||||
refetchCacheLimit()
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
import { useProxyValue, useSetProxy } from "~/hooks/biz/useProxySetting"
|
||||
import { useMinimizeToTrayValue, useSetMinimizeToTray } from "~/hooks/biz/useTraySetting"
|
||||
import { fallbackLanguage } from "~/i18n"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { setTranslationCache } from "~/modules/entry-content/atoms"
|
||||
|
||||
import { SettingDescription, SettingInput, SettingSwitch } from "../control"
|
||||
@@ -40,15 +40,21 @@ const { defineSettingItem: _defineSettingItem, SettingBuilder } = createSetting(
|
||||
)
|
||||
|
||||
const saveLoginSetting = (checked: boolean) => {
|
||||
tipcClient?.setLoginItemSettings(checked)
|
||||
ipcServices?.setting.setLoginItemSettings({
|
||||
openAtLogin: checked,
|
||||
openAsHidden: true,
|
||||
args: ["--startup"],
|
||||
})
|
||||
setGeneralSetting("appLaunchOnStartup", checked)
|
||||
}
|
||||
|
||||
export const SettingGeneral = () => {
|
||||
const { t } = useTranslation("settings")
|
||||
useEffect(() => {
|
||||
tipcClient?.getLoginItemSettings().then((settings) => {
|
||||
setGeneralSetting("appLaunchOnStartup", settings.openAtLogin)
|
||||
ipcServices?.setting.getLoginItemSettings().then((settings) => {
|
||||
if (settings) {
|
||||
setGeneralSetting("appLaunchOnStartup", settings.openAtLogin)
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
@@ -73,7 +79,7 @@ export const SettingGeneral = () => {
|
||||
|
||||
defineSettingItem("appLaunchOnStartup", {
|
||||
label: t("general.launch_at_login"),
|
||||
disabled: !tipcClient,
|
||||
disabled: !ipcServices,
|
||||
onChange(value) {
|
||||
saveLoginSetting(value)
|
||||
},
|
||||
@@ -173,7 +179,7 @@ const VoiceSelector = () => {
|
||||
const { t } = useTranslation("settings")
|
||||
|
||||
const { data } = useQuery({
|
||||
queryFn: () => tipcClient?.getVoices(),
|
||||
queryFn: () => ipcServices?.reader.getVoices(),
|
||||
queryKey: ["voices"],
|
||||
meta: {
|
||||
persist: true,
|
||||
|
||||
@@ -24,7 +24,7 @@ import { toast } from "sonner"
|
||||
import { setAppMessagingToken, useAppMessagingToken } from "~/atoms/app"
|
||||
import { useCurrentModal } from "~/components/ui/modal/stacked/hooks"
|
||||
import { useI18n } from "~/hooks/common"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { useMessaging, useTestMessaging } from "~/queries/messaging"
|
||||
|
||||
export const SettingNotifications = () => {
|
||||
@@ -37,8 +37,8 @@ export const SettingNotifications = () => {
|
||||
const testMessaging = useTestMessaging()
|
||||
|
||||
useEffect(() => {
|
||||
tipcClient?.getMessagingToken().then((credentials) => {
|
||||
setAppMessagingToken(credentials?.fcm?.token || null)
|
||||
ipcServices?.setting.getMessagingToken().then((credentials) => {
|
||||
setAppMessagingToken(credentials || null)
|
||||
})
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -2,27 +2,17 @@ import { Spring } from "@follow/components/constants/spring.js"
|
||||
import { tracker } from "@follow/tracker"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import { m, useMotionTemplate, useMotionValue } from "motion/react"
|
||||
import { useCallback, useEffect, useRef } from "react"
|
||||
import { useCallback, useRef } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { useAudioPlayerAtomSelector } from "~/atoms/player"
|
||||
import { getUpdaterStatus, setUpdaterStatus, useUpdaterStatus } from "~/atoms/updater"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { handlers } from "~/tipc"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
|
||||
export const UpdateNotice = () => {
|
||||
const updaterStatus = useUpdaterStatus()
|
||||
const { t } = useTranslation()
|
||||
|
||||
useEffect(() => {
|
||||
return handlers?.updateDownloaded.listen(() => {
|
||||
setUpdaterStatus({
|
||||
type: "app",
|
||||
status: "ready",
|
||||
})
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handleClick = useRef(() => {
|
||||
const status = getUpdaterStatus()
|
||||
if (!status) return
|
||||
@@ -31,11 +21,11 @@ export const UpdateNotice = () => {
|
||||
})
|
||||
switch (status.type) {
|
||||
case "app": {
|
||||
tipcClient?.quitAndInstall()
|
||||
ipcServices?.app.quitAndInstall()
|
||||
break
|
||||
}
|
||||
case "renderer": {
|
||||
tipcClient?.rendererUpdateReload()
|
||||
ipcServices?.app.rendererUpdateReload()
|
||||
break
|
||||
}
|
||||
case "pwa": {
|
||||
|
||||
@@ -7,11 +7,13 @@ import { toast } from "sonner"
|
||||
import { setWindowState } from "~/atoms/app"
|
||||
import { getGeneralSettings } from "~/atoms/settings/general"
|
||||
import { getUISettings, useToggleZenMode } from "~/atoms/settings/ui"
|
||||
import { setUpdaterStatus } from "~/atoms/updater"
|
||||
import { setUpdaterStatus, useUpdaterStatus } from "~/atoms/updater"
|
||||
import { useDialog, useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { useDiscoverRSSHubRouteModal } from "~/hooks/biz/useDiscoverRSSHubRoute"
|
||||
import { useFollow } from "~/hooks/biz/useFollow"
|
||||
import { navigateEntry } from "~/hooks/biz/useNavigateEntry"
|
||||
import { oneTimeToken } from "~/lib/auth"
|
||||
import { queryClient } from "~/lib/query-client"
|
||||
import { usePresentUserProfileModal } from "~/modules/profile/hooks"
|
||||
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal"
|
||||
import { handleSessionChanges } from "~/queries/auth"
|
||||
@@ -26,7 +28,17 @@ declare module "@follow/components/providers/stable-router-provider.js" {
|
||||
export const ExtensionExposeProvider = () => {
|
||||
const { present } = useModalStack()
|
||||
const showSettings = useSettingModal()
|
||||
|
||||
const updaterStatus = useUpdaterStatus()
|
||||
useLayoutEffect(() => {
|
||||
registerGlobalContext({
|
||||
updateDownloaded() {
|
||||
setUpdaterStatus({
|
||||
type: "app",
|
||||
status: "ready",
|
||||
})
|
||||
},
|
||||
})
|
||||
}, [updaterStatus])
|
||||
useLayoutEffect(() => {
|
||||
registerGlobalContext({
|
||||
showSetting: (path) => window.router.showSettings(path),
|
||||
@@ -55,6 +67,12 @@ export const ExtensionExposeProvider = () => {
|
||||
status: "ready",
|
||||
})
|
||||
},
|
||||
invalidateQuery(queryKey: string | string[]) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: Array.isArray(queryKey) ? queryKey : [queryKey],
|
||||
})
|
||||
},
|
||||
navigateEntry,
|
||||
})
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { I18N_LOCALE_KEY } from "~/constants"
|
||||
import { useReduceMotion } from "~/hooks/biz/useReduceMotion"
|
||||
import { useSyncTheme } from "~/hooks/common"
|
||||
import { langChain } from "~/i18n"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { loadLanguageAndApply } from "~/lib/load-language"
|
||||
import { unreadActions } from "~/store/unread"
|
||||
|
||||
@@ -38,9 +38,12 @@ const useUISettingSync = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (setting.showDockBadge) {
|
||||
return unreadActions.subscribeUnreadCount((count) => tipcClient?.setDockBadge(count), true)
|
||||
return unreadActions.subscribeUnreadCount(
|
||||
(count) => ipcServices?.setting.setDockBadge(count),
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
tipcClient?.setDockBadge(0)
|
||||
ipcServices?.setting.setDockBadge(0)
|
||||
}
|
||||
return
|
||||
}, [setting.showDockBadge])
|
||||
|
||||
@@ -6,7 +6,7 @@ import { setWhoami } from "~/atoms/user"
|
||||
import { QUERY_PERSIST_KEY } from "~/constants"
|
||||
import { useAuthQuery } from "~/hooks/common"
|
||||
import { getAccountInfo, getSession, signOut as signOutFn } from "~/lib/auth"
|
||||
import { tipcClient } from "~/lib/client"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { defineQuery } from "~/lib/defineQuery"
|
||||
import { clearLocalPersistStoreData } from "~/store/utils/clear"
|
||||
|
||||
@@ -72,7 +72,7 @@ export const useSession = (options?: { enabled?: boolean }) => {
|
||||
}
|
||||
|
||||
export const handleSessionChanges = () => {
|
||||
tipcClient?.sessionChanged()
|
||||
ipcServices?.auth.sessionChanged()
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ export const signOut = async () => {
|
||||
// Clear local storage
|
||||
clearStorage()
|
||||
// Sign out
|
||||
await tipcClient?.signOut()
|
||||
await ipcServices?.auth.signOut()
|
||||
await signOutFn()
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { createEventHandlers } from "@egoist/tipc/renderer"
|
||||
import type { RendererHandlers } from "@follow/electron-main"
|
||||
|
||||
export const handlers = window.electron
|
||||
? createEventHandlers<RendererHandlers>({
|
||||
on: (channel, callback) => {
|
||||
if (!window.electron) return () => {}
|
||||
const remover = window.electron.ipcRenderer.on(channel, callback)
|
||||
return () => {
|
||||
remover()
|
||||
}
|
||||
},
|
||||
|
||||
send: window.electron.ipcRenderer.send,
|
||||
})
|
||||
: null
|
||||
@@ -66,6 +66,11 @@ interface RenderGlobalContext {
|
||||
|
||||
// View
|
||||
zenMode: () => void
|
||||
|
||||
// Utils
|
||||
invalidateQuery: (queryKey: string | string[]) => void
|
||||
navigateEntry: (options: { feedId: string; entryId: string; view: number }) => void
|
||||
updateDownloaded: () => void
|
||||
}
|
||||
|
||||
export const registerGlobalContext = (context: Partial<RenderGlobalContext>) => {
|
||||
|
||||
Generated
-36
@@ -330,9 +330,6 @@ importers:
|
||||
|
||||
apps/desktop/layer/main:
|
||||
dependencies:
|
||||
'@egoist/tipc':
|
||||
specifier: 0.3.2
|
||||
version: 0.3.2(electron@35.1.5)(react@19.0.0)
|
||||
'@electron-toolkit/preload':
|
||||
specifier: 3.0.2
|
||||
version: 3.0.2(electron@35.1.5)
|
||||
@@ -451,9 +448,6 @@ importers:
|
||||
'@dnd-kit/sortable':
|
||||
specifier: 10.0.0
|
||||
version: 10.0.0(@dnd-kit/core@6.3.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react@19.0.0)
|
||||
'@egoist/tipc':
|
||||
specifier: 0.3.2
|
||||
version: 0.3.2(electron@35.1.5)(react@19.0.0)
|
||||
'@electron-toolkit/preload':
|
||||
specifier: 3.0.2
|
||||
version: 3.0.2(electron@35.1.5)
|
||||
@@ -2699,11 +2693,6 @@ packages:
|
||||
peerDependencies:
|
||||
tailwindcss: '*'
|
||||
|
||||
'@egoist/tipc@0.3.2':
|
||||
resolution: {integrity: sha512-p8g35BhErVkYIgDqkw/HQJSli1TOsZRIUU9U7PYnYfwru6J/Ep1lwFGH2N6+sQMFi1HkqGTTUlJEISJ1DClfQw==}
|
||||
peerDependencies:
|
||||
electron: '>=26.0.0'
|
||||
|
||||
'@electron-forge/cli@7.8.0':
|
||||
resolution: {integrity: sha512-XZ+Hg7pxeE9pgrahqcpMlND+VH0l0UTZLyO5wkI+YfanNyBQksB2mw24XeEtCA6x8F2IaEYdIGgijmPF6qpjzA==}
|
||||
engines: {node: '>= 16.4.0'}
|
||||
@@ -6035,9 +6024,6 @@ packages:
|
||||
peerDependencies:
|
||||
tailwindcss: '>=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1'
|
||||
|
||||
'@tanstack/query-core@5.74.7':
|
||||
resolution: {integrity: sha512-X3StkN/Y6KGHndTjJf8H8th7AX4bKfbRpiVhVqevf0QWlxl6DhyJ0TYG3R0LARa/+xqDwzU9mA4pbJxzPCI29A==}
|
||||
|
||||
'@tanstack/query-core@5.77.2':
|
||||
resolution: {integrity: sha512-1lqJwPsR6GX6nZFw06erRt518O19tWU6Q+x0fJUygl4lxHCYF2nhzBPwLKk2NPjYOrpR0K567hxPc5K++xDe9Q==}
|
||||
|
||||
@@ -6062,11 +6048,6 @@ packages:
|
||||
'@tanstack/react-query': ^5.77.2
|
||||
react: 19.0.0
|
||||
|
||||
'@tanstack/react-query@5.74.7':
|
||||
resolution: {integrity: sha512-u4o/RIWnnrq26orGZu2NDPwmVof1vtAiiV6KYUXd49GuK+8HX+gyxoAYqIaZogvCE1cqOuZAhQKcrKGYGkrLxg==}
|
||||
peerDependencies:
|
||||
react: 19.0.0
|
||||
|
||||
'@tanstack/react-query@5.77.2':
|
||||
resolution: {integrity: sha512-BRHxWdy1mHmgAcYA/qy2IPLylT81oebLgkm9K85viN2Qol/Vq48t1dzDFeDIVQjTWDV96AmqsLNPlH5HjyKCxA==}
|
||||
peerDependencies:
|
||||
@@ -17141,14 +17122,6 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@egoist/tipc@0.3.2(electron@35.1.5)(react@19.0.0)':
|
||||
dependencies:
|
||||
electron: 35.1.5
|
||||
optionalDependencies:
|
||||
'@tanstack/react-query': 5.74.7(react@19.0.0)
|
||||
transitivePeerDependencies:
|
||||
- react
|
||||
|
||||
'@electron-forge/cli@7.8.0(encoding@0.1.13)':
|
||||
dependencies:
|
||||
'@electron-forge/core': 7.8.0(encoding@0.1.13)
|
||||
@@ -21662,9 +21635,6 @@ snapshots:
|
||||
postcss-selector-parser: 6.0.10
|
||||
tailwindcss: 3.4.17(ts-node@10.9.2(@types/node@22.15.23)(typescript@5.8.3))
|
||||
|
||||
'@tanstack/query-core@5.74.7':
|
||||
optional: true
|
||||
|
||||
'@tanstack/query-core@5.77.2': {}
|
||||
|
||||
'@tanstack/query-devtools@5.76.0': {}
|
||||
@@ -21690,12 +21660,6 @@ snapshots:
|
||||
'@tanstack/react-query': 5.77.2(react@19.0.0)
|
||||
react: 19.0.0
|
||||
|
||||
'@tanstack/react-query@5.74.7(react@19.0.0)':
|
||||
dependencies:
|
||||
'@tanstack/query-core': 5.74.7
|
||||
react: 19.0.0
|
||||
optional: true
|
||||
|
||||
'@tanstack/react-query@5.77.2(react@19.0.0)':
|
||||
dependencies:
|
||||
'@tanstack/query-core': 5.77.2
|
||||
|
||||
Reference in New Issue
Block a user