Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Restructure and refactor services in desktop

Hakan Shehu74f74ea37af0
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index a399e989..645e83a6 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -5,21 +5,20 @@ import { createDebugger } from '@colanode/core';
import { app, BrowserWindow, ipcMain, protocol, shell } from 'electron';
import path from 'path';
-import { metadataService } from '@/main/services/metadata-service';
-import { notificationService } from '@/main/services/notification-service';
import { WindowSize } from '@/shared/types/metadata';
-import { scheduler } from '@/main/scheduler';
-import { assetService } from '@/main/services/asset-service';
-import { avatarService } from '@/main/services/avatar-service';
-import { commandService } from '@/main/services/command-service';
-import { fileService } from '@/main/services/file-service';
-import { mutationService } from '@/main/services/mutation-service';
-import { queryService } from '@/main/services/query-service';
+import { mediator } from '@/main/mediator';
import { getAppIconPath } from '@/main/utils';
import { CommandInput, CommandMap } from '@/shared/commands';
import { eventBus } from '@/shared/lib/event-bus';
import { MutationInput, MutationMap } from '@/shared/mutations';
import { QueryInput, QueryMap } from '@/shared/queries';
+import { appService } from '@/main/services/app-service';
+import {
+ handleAssetRequest,
+ handleAvatarRequest,
+ handleFilePreviewRequest,
+ handleFileRequest,
+} from '@/main/lib/protocols';
const debug = createDebugger('desktop:main');
@@ -42,11 +41,10 @@ updateElectronApp({
});
const createWindow = async () => {
- await scheduler.init();
- notificationService.checkBadge();
+ await appService.migrate();
// Create the browser window.
- let windowSize = await metadataService.get<WindowSize>('window_size');
+ let windowSize = await appService.metadata.get<WindowSize>('window_size');
const mainWindow = new BrowserWindow({
width: windowSize?.width ?? 1200,
height: windowSize?.height ?? 800,
@@ -70,7 +68,7 @@ const createWindow = async () => {
fullscreen: false,
};
- metadataService.set('window_size', windowSize);
+ appService.metadata.set('window_size', windowSize);
});
mainWindow.on('enter-full-screen', () => {
@@ -80,7 +78,7 @@ const createWindow = async () => {
fullscreen: true,
};
- metadataService.set('window_size', windowSize);
+ appService.metadata.set('window_size', windowSize);
});
mainWindow.on('leave-full-screen', () => {
@@ -90,7 +88,7 @@ const createWindow = async () => {
fullscreen: false,
};
- metadataService.set('window_size', windowSize);
+ appService.metadata.set('window_size', windowSize);
});
// and load the index.html of the app.
@@ -116,25 +114,25 @@ const createWindow = async () => {
if (!protocol.isProtocolHandled('avatar')) {
protocol.handle('avatar', (request) => {
- return avatarService.handleAvatarRequest(request);
+ return handleAvatarRequest(request);
});
}
if (!protocol.isProtocolHandled('local-file')) {
protocol.handle('local-file', (request) => {
- return fileService.handleFileRequest(request);
+ return handleFileRequest(request);
});
}
if (!protocol.isProtocolHandled('local-file-preview')) {
protocol.handle('local-file-preview', (request) => {
- return fileService.handleFilePreviewRequest(request);
+ return handleFilePreviewRequest(request);
});
}
if (!protocol.isProtocolHandled('asset')) {
protocol.handle('asset', (request) => {
- return assetService.handleAssetRequest(request);
+ return handleAssetRequest(request);
});
}
@@ -159,7 +157,7 @@ app.on('window-all-closed', () => {
app.quit();
}
- queryService.clearSubscriptions();
+ mediator.clearSubscriptions();
});
app.on('activate', () => {
@@ -173,7 +171,7 @@ app.on('activate', () => {
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
ipcMain.handle('init', async () => {
- await scheduler.init();
+ await appService.init();
});
ipcMain.handle(
@@ -182,7 +180,7 @@ ipcMain.handle(
_: unknown,
input: T
): Promise<MutationMap[T['type']]['output']> => {
- return mutationService.executeMutation(input);
+ return mediator.executeMutation(input);
}
);
@@ -192,7 +190,7 @@ ipcMain.handle(
_: unknown,
input: T
): Promise<QueryMap[T['type']]['output']> => {
- return queryService.executeQuery(input);
+ return mediator.executeQuery(input);
}
);
@@ -203,12 +201,12 @@ ipcMain.handle(
id: string,
input: T
): Promise<QueryMap[T['type']]['output']> => {
- return queryService.executeQueryAndSubscribe(id, input);
+ return mediator.executeQueryAndSubscribe(id, input);
}
);
ipcMain.handle('unsubscribe-query', (_: unknown, id: string): void => {
- queryService.unsubscribeQuery(id);
+ mediator.unsubscribeQuery(id);
});
ipcMain.handle(
@@ -217,6 +215,6 @@ ipcMain.handle(
_: unknown,
input: T
): Promise<CommandMap[T['type']]['output']> => {
- return commandService.executeCommand(input);
+ return mediator.executeCommand(input);
}
);
diff --git a/apps/desktop/src/main/commands/file-open.ts b/apps/desktop/src/main/commands/file-open.ts
index abf07772..38570cca 100644
--- a/apps/desktop/src/main/commands/file-open.ts
+++ b/apps/desktop/src/main/commands/file-open.ts
@@ -1,4 +1,7 @@
-import { fileService } from '@/main/services/file-service';
+import path from 'path';
+import { shell } from 'electron';
+
+import { getWorkspaceFilesDirectoryPath } from '@/main/utils';
import { CommandHandler } from '@/main/types';
import { FileOpenCommandInput } from '@/shared/commands/file-open';
@@ -6,6 +9,16 @@ export class FileOpenCommandHandler
implements CommandHandler<FileOpenCommandInput>
{
public async handleCommand(input: FileOpenCommandInput): Promise<void> {
- fileService.openFile(input.userId, input.fileId, input.extension);
+ const workspaceFilesDir = getWorkspaceFilesDirectoryPath(
+ input.accountId,
+ input.workspaceId
+ );
+
+ const filePath = path.join(
+ workspaceFilesDir,
+ `${input.fileId}${input.extension}`
+ );
+
+ shell.openPath(filePath);
}
}
diff --git a/apps/desktop/src/main/data/app/migrations.ts b/apps/desktop/src/main/data/app/migrations.ts
deleted file mode 100644
index 7ab912f5..00000000
--- a/apps/desktop/src/main/data/app/migrations.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { Migration } from 'kysely';
-
-const createServersTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('servers')
- .addColumn('domain', 'text', (col) => col.notNull().primaryKey())
- .addColumn('name', 'text', (col) => col.notNull())
- .addColumn('avatar', 'text', (col) => col.notNull())
- .addColumn('attributes', 'text', (col) => col.notNull())
- .addColumn('version', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('last_synced_at', 'text')
- .execute();
-
- await db
- .insertInto('servers')
- .values([
- {
- domain: 'eu.colanode.com',
- name: 'Colanode Cloud (EU)',
- avatar: 'https://colanode.com/assets/flags/eu.svg',
- attributes: '{}',
- version: '0.1.0',
- created_at: new Date().toISOString(),
- },
- {
- domain: 'us.colanode.com',
- name: 'Colanode Cloud (US)',
- avatar: 'https://colanode.com/assets/flags/us.svg',
- attributes: '{}',
- version: '0.1.0',
- created_at: new Date().toISOString(),
- },
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('servers').execute();
- },
-};
-
-const createAccountsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('accounts')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('device_id', 'text', (col) => col.notNull())
- .addColumn('server', 'text', (col) => col.notNull())
- .addColumn('name', 'text', (col) => col.notNull())
- .addColumn('email', 'text', (col) => col.notNull())
- .addColumn('avatar', 'text')
- .addColumn('token', 'text', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('accounts').execute();
- },
-};
-
-const createWorkspacesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('workspaces')
- .addColumn('user_id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('workspace_id', 'text', (col) => col.notNull())
- .addColumn('account_id', 'text', (col) =>
- col.notNull().references('accounts.id').onDelete('cascade')
- )
- .addColumn('name', 'text', (col) => col.notNull())
- .addColumn('description', 'text')
- .addColumn('avatar', 'text')
- .addColumn('role', 'text', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('workspaces').execute();
- },
-};
-
-const createDeletedTokensTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('deleted_tokens')
- .addColumn('account_id', 'text', (col) => col.notNull())
- .addColumn('token', 'text', (col) => col.notNull().primaryKey())
- .addColumn('server', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('deleted_tokens').execute();
- },
-};
-
-const createMetadataTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('metadata')
- .addColumn('key', 'text', (col) => col.notNull().primaryKey())
- .addColumn('value', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('metadata').execute();
- },
-};
-
-export const appDatabaseMigrations: Record<string, Migration> = {
- '00001_create_servers_table': createServersTable,
- '00002_create_accounts_table': createAccountsTable,
- '00003_create_workspaces_table': createWorkspacesTable,
- '00004_create_deleted_tokens_table': createDeletedTokensTable,
- '00005_create_metadata_table': createMetadataTable,
-};
diff --git a/apps/desktop/src/main/data/database-service.ts b/apps/desktop/src/main/data/database-service.ts
deleted file mode 100644
index d034349d..00000000
--- a/apps/desktop/src/main/data/database-service.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import SQLite from 'better-sqlite3';
-import { Kysely, Migration, Migrator, SqliteDialect } from 'kysely';
-import { createDebugger } from '@colanode/core';
-
-import fs from 'fs';
-
-import { appDatabaseMigrations } from '@/main/data/app/migrations';
-import { AppDatabaseSchema } from '@/main/data/app/schema';
-import { workspaceDatabaseMigrations } from '@/main/data/workspace/migrations';
-import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';
-import { appDatabasePath, getWorkspaceDirectoryPath } from '@/main/utils';
-import { eventBus } from '@/shared/lib/event-bus';
-
-class DatabaseService {
- private initPromise: Promise<void> | null = null;
- private readonly workspaceDatabases: Map<
- string,
- Kysely<WorkspaceDatabaseSchema>
- > = new Map();
-
- public readonly appDatabase: Kysely<AppDatabaseSchema>;
- private readonly debug = createDebugger('desktop:service:database');
-
- constructor() {
- this.debug('Constructing database service');
- const dialect = new SqliteDialect({
- database: this.buildSqlite(appDatabasePath),
- });
-
- this.appDatabase = new Kysely<AppDatabaseSchema>({ dialect });
-
- eventBus.subscribe((event) => {
- if (event.type === 'workspace_created') {
- this.initWorkspaceDatabase(event.workspace.userId);
- }
- });
- }
-
- public async init(): Promise<void> {
- this.debug('Initializing database service');
- if (!this.initPromise) {
- this.initPromise = this.executeInit();
- }
-
- await this.initPromise;
- }
-
- public async getWorkspaceDatabase(
- userId: string
- ): Promise<Kysely<WorkspaceDatabaseSchema>> {
- await this.waitForInit();
-
- if (this.workspaceDatabases.has(userId)) {
- return this.workspaceDatabases.get(userId)!;
- }
-
- //try and check if it's in database but hasn't been loaded yet
- const workspace = await this.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .where('user_id', '=', userId)
- .executeTakeFirst();
-
- if (!workspace) {
- throw new Error('Workspace database not found');
- }
-
- const workspaceDatabase = await this.initWorkspaceDatabase(userId);
- this.workspaceDatabases.set(userId, workspaceDatabase);
- return workspaceDatabase;
- }
-
- public async getWorkspaceDatabases(): Promise<
- Map<string, Kysely<WorkspaceDatabaseSchema>>
- > {
- await this.waitForInit();
- return this.workspaceDatabases;
- }
-
- public async removeWorkspaceDatabase(userId: string): Promise<void> {
- this.debug(`Deleting workspace database for user: ${userId}`);
- await this.waitForInit();
-
- const workspaceDatabase = this.workspaceDatabases.get(userId);
- if (workspaceDatabase) {
- try {
- workspaceDatabase.destroy();
- } catch (error) {
- this.debug(
- `Failed to destroy workspace database for user: ${userId}`,
- error
- );
- }
- }
-
- this.workspaceDatabases.delete(userId);
- }
-
- private async waitForInit(): Promise<void> {
- if (!this.initPromise) {
- this.initPromise = this.executeInit();
- }
-
- await this.initPromise;
- }
-
- private async executeInit(): Promise<void> {
- await this.migrateAppDatabase();
-
- const workspaces = await this.appDatabase
- .selectFrom('workspaces')
- .select('user_id')
- .execute();
-
- for (const workspace of workspaces) {
- const workspaceDatabase = await this.initWorkspaceDatabase(
- workspace.user_id
- );
-
- this.workspaceDatabases.set(workspace.user_id, workspaceDatabase);
- }
- }
-
- private async initWorkspaceDatabase(
- userId: string
- ): Promise<Kysely<WorkspaceDatabaseSchema>> {
- this.debug(`Initializing workspace database for user: ${userId}`);
- const workspaceDir = getWorkspaceDirectoryPath(userId);
-
- if (!fs.existsSync(workspaceDir)) {
- fs.mkdirSync(workspaceDir, {
- recursive: true,
- });
- }
-
- const dialect = new SqliteDialect({
- database: this.buildSqlite(`${workspaceDir}/workspace.db`),
- });
-
- const workspaceDatabase = new Kysely<WorkspaceDatabaseSchema>({
- dialect,
- });
-
- await this.migrateWorkspaceDatabase(workspaceDatabase);
- return workspaceDatabase;
- }
-
- private async migrateAppDatabase(): Promise<void> {
- this.debug('Migrating app database');
- const migrator = new Migrator({
- db: this.appDatabase,
- provider: {
- getMigrations(): Promise<Record<string, Migration>> {
- return Promise.resolve(appDatabaseMigrations);
- },
- },
- });
-
- await migrator.migrateToLatest();
- }
-
- private async migrateWorkspaceDatabase(
- database: Kysely<WorkspaceDatabaseSchema>
- ): Promise<void> {
- this.debug('Migrating workspace database');
- const migrator = new Migrator({
- db: database,
- provider: {
- getMigrations(): Promise<Record<string, Migration>> {
- return Promise.resolve(workspaceDatabaseMigrations);
- },
- },
- });
-
- await migrator.migrateToLatest();
- }
-
- private buildSqlite = (filename: string): SQLite.Database => {
- this.debug(`Building sqlite database: ${filename}`);
- const database = new SQLite(filename);
- database.pragma('journal_mode = WAL');
- return database;
- };
-}
-
-export const databaseService = new DatabaseService();
diff --git a/apps/desktop/src/main/data/workspace/migrations.ts b/apps/desktop/src/main/data/workspace/migrations.ts
deleted file mode 100644
index 9f32ec3c..00000000
--- a/apps/desktop/src/main/data/workspace/migrations.ts
+++ /dev/null
@@ -1,401 +0,0 @@
-import { Migration, sql } from 'kysely';
-
-const createUsersTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('users')
- .addColumn('id', 'text', (col) => col.primaryKey().notNull())
- .addColumn('email', 'text', (col) => col.notNull())
- .addColumn('name', 'text', (col) => col.notNull())
- .addColumn('avatar', 'text')
- .addColumn('custom_name', 'text')
- .addColumn('custom_avatar', 'text')
- .addColumn('role', 'text', (col) => col.notNull())
- .addColumn('storage_limit', 'integer', (col) => col.notNull())
- .addColumn('max_file_size', 'integer', (col) => col.notNull())
- .addColumn('status', 'integer', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('version', 'integer')
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('users').execute();
- },
-};
-
-const createEntriesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entries')
- .addColumn('id', 'text', (col) => col.primaryKey().notNull())
- .addColumn('type', 'text', (col) =>
- col
- .notNull()
- .generatedAlwaysAs(sql`json_extract(attributes, '$.type')`)
- .stored()
- )
- .addColumn('parent_id', 'text', (col) =>
- col
- .generatedAlwaysAs(sql`json_extract(attributes, '$.parentId')`)
- .stored()
- )
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('attributes', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('updated_by', 'text')
- .addColumn('transaction_id', 'text', (col) => col.notNull())
- .execute();
-
- await db.schema
- .createIndex('entries_parent_id_type_index')
- .on('entries')
- .columns(['parent_id', 'type'])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('entries').execute();
- },
-};
-
-const createEntryTransactionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entry_transactions')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('entry_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('operation', 'integer', (col) => col.notNull())
- .addColumn('data', 'blob')
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('server_created_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('entry_transactions').execute();
- },
-};
-
-const createEntryInteractionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entry_interactions')
- .addColumn('entry_id', 'text', (col) => col.notNull())
- .addColumn('collaborator_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('first_seen_at', 'text')
- .addColumn('last_seen_at', 'text')
- .addColumn('first_opened_at', 'text')
- .addColumn('last_opened_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('entry_interactions_pkey', [
- 'entry_id',
- 'collaborator_id',
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('entry_interactions').execute();
- },
-};
-
-const createCollaborationsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('collaborations')
- .addColumn('entry_id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('role', 'text')
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('deleted_at', 'text')
- .addColumn('version', 'integer')
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('collaborations').execute();
- },
-};
-
-const createMessagesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('messages')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('type', 'integer', (col) =>
- col
- .notNull()
- .generatedAlwaysAs(sql`json_extract(attributes, '$.type')`)
- .stored()
- )
- .addColumn('parent_id', 'text', (col) => col.notNull())
- .addColumn('entry_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('attributes', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('updated_by', 'text')
- .addColumn('deleted_at', 'text')
- .addColumn('version', 'integer')
- .execute();
-
- await db.schema
- .createIndex('messages_parent_id_index')
- .on('messages')
- .columns(['parent_id'])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('messages').execute();
- },
-};
-
-const createMessageReactionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('message_reactions')
- .addColumn('message_id', 'text', (col) => col.notNull())
- .addColumn('collaborator_id', 'text', (col) => col.notNull())
- .addColumn('reaction', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('deleted_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('message_reactions_pkey', [
- 'message_id',
- 'collaborator_id',
- 'reaction',
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('message_reactions').execute();
- },
-};
-
-const createMessageInteractionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('message_interactions')
- .addColumn('message_id', 'text', (col) => col.notNull())
- .addColumn('collaborator_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('first_seen_at', 'text')
- .addColumn('last_seen_at', 'text')
- .addColumn('first_opened_at', 'text')
- .addColumn('last_opened_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('message_interactions_pkey', [
- 'message_id',
- 'collaborator_id',
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('message_interactions').execute();
- },
-};
-
-const createFilesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('files')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('type', 'text', (col) => col.notNull())
- .addColumn('parent_id', 'text', (col) => col.notNull())
- .addColumn('entry_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('name', 'text', (col) => col.notNull())
- .addColumn('original_name', 'text', (col) => col.notNull())
- .addColumn('mime_type', 'text', (col) => col.notNull())
- .addColumn('extension', 'text', (col) => col.notNull())
- .addColumn('size', 'integer', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('updated_by', 'text')
- .addColumn('deleted_at', 'text')
- .addColumn('status', 'integer', (col) => col.notNull())
- .addColumn('version', 'integer')
- .execute();
-
- await db.schema
- .createIndex('files_parent_id_index')
- .on('files')
- .columns(['parent_id'])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('files').execute();
- },
-};
-
-const createFileStatesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('file_states')
- .addColumn('file_id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('download_status', 'integer', (col) => col.notNull())
- .addColumn('download_progress', 'integer', (col) => col.notNull())
- .addColumn('download_retries', 'integer', (col) => col.notNull())
- .addColumn('upload_status', 'integer', (col) => col.notNull())
- .addColumn('upload_progress', 'integer', (col) => col.notNull())
- .addColumn('upload_retries', 'integer', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('file_states').execute();
- },
-};
-
-const createFileInteractionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('file_interactions')
- .addColumn('file_id', 'text', (col) => col.notNull())
- .addColumn('collaborator_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('seen_at', 'text')
- .addColumn('first_opened_at', 'text')
- .addColumn('last_opened_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('file_interactions_pkey', [
- 'file_id',
- 'collaborator_id',
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('file_interactions').execute();
- },
-};
-
-const createMutationsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('mutations')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('type', 'text', (col) => col.notNull())
- .addColumn('data', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('retries', 'integer', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('mutations').execute();
- },
-};
-
-const createEntryPathsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entry_paths')
- .addColumn('ancestor_id', 'varchar(30)', (col) =>
- col.notNull().references('entries.id').onDelete('cascade')
- )
- .addColumn('descendant_id', 'varchar(30)', (col) =>
- col.notNull().references('entries.id').onDelete('cascade')
- )
- .addColumn('level', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('entry_paths_pkey', [
- 'ancestor_id',
- 'descendant_id',
- ])
- .execute();
-
- await sql`
- CREATE TRIGGER trg_insert_entry_path
- AFTER INSERT ON entries
- FOR EACH ROW
- BEGIN
- -- Insert direct path from the new entry to itself
- INSERT INTO entry_paths (ancestor_id, descendant_id, level)
- VALUES (NEW.id, NEW.id, 0);
-
- -- Insert paths from ancestors to the new entry
- INSERT INTO entry_paths (ancestor_id, descendant_id, level)
- SELECT ancestor_id, NEW.id, level + 1
- FROM entry_paths
- WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
- END;
- `.execute(db);
-
- await sql`
- CREATE TRIGGER trg_update_entry_path
- AFTER UPDATE ON entries
- FOR EACH ROW
- WHEN OLD.parent_id <> NEW.parent_id
- BEGIN
- -- Delete old paths involving the updated entry
- DELETE FROM entry_paths
- WHERE descendant_id = NEW.id AND ancestor_id <> NEW.id;
-
- -- Insert new paths from ancestors to the updated entry
- INSERT INTO entry_paths (ancestor_id, descendant_id, level)
- SELECT ancestor_id, NEW.id, level + 1
- FROM entry_paths
- WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
- END;
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_insert_entry_path;
- DROP TRIGGER IF EXISTS trg_update_entry_path;
- `.execute(db);
-
- await db.schema.dropTable('entry_paths').execute();
- },
-};
-
-const createTextsTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE VIRTUAL TABLE texts USING fts5(id UNINDEXED, name, text);
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TABLE IF EXISTS texts;
- `.execute(db);
- },
-};
-
-const createCursorsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('cursors')
- .addColumn('key', 'text', (col) => col.notNull().primaryKey())
- .addColumn('value', 'integer', (col) => col.notNull().defaultTo(0))
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('cursors').execute();
- },
-};
-
-export const workspaceDatabaseMigrations: Record<string, Migration> = {
- '00001_create_users_table': createUsersTable,
- '00002_create_entries_table': createEntriesTable,
- '00003_create_entry_interactions_table': createEntryInteractionsTable,
- '00004_create_entry_transactions_table': createEntryTransactionsTable,
- '00005_create_collaborations_table': createCollaborationsTable,
- '00006_create_messages_table': createMessagesTable,
- '00007_create_message_reactions_table': createMessageReactionsTable,
- '00008_create_message_interactions_table': createMessageInteractionsTable,
- '00009_create_files_table': createFilesTable,
- '00010_create_file_states_table': createFileStatesTable,
- '00011_create_file_interactions_table': createFileInteractionsTable,
- '00012_create_mutations_table': createMutationsTable,
- '00013_create_entry_paths_table': createEntryPathsTable,
- '00014_create_texts_table': createTextsTable,
- '00015_create_cursors_table': createCursorsTable,
-};
diff --git a/apps/desktop/src/main/databases/account/index.ts b/apps/desktop/src/main/databases/account/index.ts
new file mode 100644
index 00000000..adaca880
--- /dev/null
+++ b/apps/desktop/src/main/databases/account/index.ts
@@ -0,0 +1,2 @@
+export * from './schema';
+export * from './migrations';
diff --git a/apps/desktop/src/main/databases/account/migrations/00001-create-workspaces-table.ts b/apps/desktop/src/main/databases/account/migrations/00001-create-workspaces-table.ts
new file mode 100644
index 00000000..3dbe7f37
--- /dev/null
+++ b/apps/desktop/src/main/databases/account/migrations/00001-create-workspaces-table.ts
@@ -0,0 +1,19 @@
+import { Migration } from 'kysely';
+
+export const createWorkspacesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('workspaces')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('user_id', 'text', (col) => col.notNull())
+ .addColumn('account_id', 'text', (col) => col.notNull())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('description', 'text')
+ .addColumn('avatar', 'text')
+ .addColumn('role', 'text', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('workspaces').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/account/migrations/index.ts b/apps/desktop/src/main/databases/account/migrations/index.ts
new file mode 100644
index 00000000..7f4c4ee9
--- /dev/null
+++ b/apps/desktop/src/main/databases/account/migrations/index.ts
@@ -0,0 +1,7 @@
+import { Migration } from 'kysely';
+
+import { createWorkspacesTable } from './00001-create-workspaces-table';
+
+export const accountDatabaseMigrations: Record<string, Migration> = {
+ '00001-create-workspaces-table': createWorkspacesTable,
+};
diff --git a/apps/desktop/src/main/databases/account/schema.ts b/apps/desktop/src/main/databases/account/schema.ts
new file mode 100644
index 00000000..804250f4
--- /dev/null
+++ b/apps/desktop/src/main/databases/account/schema.ts
@@ -0,0 +1,20 @@
+import { WorkspaceRole } from '@colanode/core';
+import { ColumnType, Insertable, Selectable, Updateable } from 'kysely';
+
+interface WorkspaceTable {
+ id: ColumnType<string, string, never>;
+ user_id: ColumnType<string, string, never>;
+ account_id: ColumnType<string, string, never>;
+ name: ColumnType<string, string, string>;
+ description: ColumnType<string | null, string | null, string | null>;
+ avatar: ColumnType<string | null, string | null, string | null>;
+ role: ColumnType<WorkspaceRole, WorkspaceRole, WorkspaceRole>;
+}
+
+export type SelectWorkspace = Selectable<WorkspaceTable>;
+export type CreateWorkspace = Insertable<WorkspaceTable>;
+export type UpdateWorkspace = Updateable<WorkspaceTable>;
+
+export interface AccountDatabaseSchema {
+ workspaces: WorkspaceTable;
+}
diff --git a/apps/desktop/src/main/databases/app/index.ts b/apps/desktop/src/main/databases/app/index.ts
new file mode 100644
index 00000000..adaca880
--- /dev/null
+++ b/apps/desktop/src/main/databases/app/index.ts
@@ -0,0 +1,2 @@
+export * from './schema';
+export * from './migrations';
diff --git a/apps/desktop/src/main/databases/app/migrations/00001-create-servers-table.ts b/apps/desktop/src/main/databases/app/migrations/00001-create-servers-table.ts
new file mode 100644
index 00000000..765254aa
--- /dev/null
+++ b/apps/desktop/src/main/databases/app/migrations/00001-create-servers-table.ts
@@ -0,0 +1,41 @@
+import { Migration } from 'kysely';
+
+export const createServersTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('servers')
+ .addColumn('domain', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('avatar', 'text', (col) => col.notNull())
+ .addColumn('attributes', 'text', (col) => col.notNull())
+ .addColumn('version', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('last_synced_at', 'text')
+ .execute();
+
+ await db
+ .insertInto('servers')
+ .values([
+ {
+ domain: 'eu.colanode.com',
+ name: 'Colanode Cloud (EU)',
+ avatar: 'https://colanode.com/assets/flags/eu.svg',
+ attributes: '{}',
+ version: '0.1.0',
+ created_at: new Date().toISOString(),
+ },
+ {
+ domain: 'us.colanode.com',
+ name: 'Colanode Cloud (US)',
+ avatar: 'https://colanode.com/assets/flags/us.svg',
+ attributes: '{}',
+ version: '0.1.0',
+ created_at: new Date().toISOString(),
+ },
+ ])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('servers').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/app/migrations/00002-create-accounts-table.ts b/apps/desktop/src/main/databases/app/migrations/00002-create-accounts-table.ts
new file mode 100644
index 00000000..34d78c72
--- /dev/null
+++ b/apps/desktop/src/main/databases/app/migrations/00002-create-accounts-table.ts
@@ -0,0 +1,19 @@
+import { Migration } from 'kysely';
+
+export const createAccountsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('accounts')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('device_id', 'text', (col) => col.notNull())
+ .addColumn('server', 'text', (col) => col.notNull())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('email', 'text', (col) => col.notNull())
+ .addColumn('avatar', 'text')
+ .addColumn('token', 'text', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('accounts').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/app/migrations/00003-create-deleted-tokens-table.ts b/apps/desktop/src/main/databases/app/migrations/00003-create-deleted-tokens-table.ts
new file mode 100644
index 00000000..d4f12dcb
--- /dev/null
+++ b/apps/desktop/src/main/databases/app/migrations/00003-create-deleted-tokens-table.ts
@@ -0,0 +1,16 @@
+import { Migration } from 'kysely';
+
+export const createDeletedTokensTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('deleted_tokens')
+ .addColumn('account_id', 'text', (col) => col.notNull())
+ .addColumn('token', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('server', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('deleted_tokens').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/app/migrations/00004-create-metadata-table.ts b/apps/desktop/src/main/databases/app/migrations/00004-create-metadata-table.ts
new file mode 100644
index 00000000..e7424d2f
--- /dev/null
+++ b/apps/desktop/src/main/databases/app/migrations/00004-create-metadata-table.ts
@@ -0,0 +1,16 @@
+import { Migration } from 'kysely';
+
+export const createMetadataTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('metadata')
+ .addColumn('key', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('value', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('metadata').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/app/migrations/index.ts b/apps/desktop/src/main/databases/app/migrations/index.ts
new file mode 100644
index 00000000..d4cb314c
--- /dev/null
+++ b/apps/desktop/src/main/databases/app/migrations/index.ts
@@ -0,0 +1,13 @@
+import { Migration } from 'kysely';
+
+import { createServersTable } from './00001-create-servers-table';
+import { createAccountsTable } from './00002-create-accounts-table';
+import { createDeletedTokensTable } from './00003-create-deleted-tokens-table';
+import { createMetadataTable } from './00004-create-metadata-table';
+
+export const appDatabaseMigrations: Record<string, Migration> = {
+ '00001-create-servers-table': createServersTable,
+ '00002-create-accounts-table': createAccountsTable,
+ '00003-create-deleted-tokens-table': createDeletedTokensTable,
+ '00004-create-metadata-table': createMetadataTable,
+};
diff --git a/apps/desktop/src/main/data/app/schema.ts b/apps/desktop/src/main/databases/app/schema.ts
similarity index 73%
rename from apps/desktop/src/main/data/app/schema.ts
rename to apps/desktop/src/main/databases/app/schema.ts
index cfa8341a..c4bd73d4 100644
--- a/apps/desktop/src/main/data/app/schema.ts
+++ b/apps/desktop/src/main/databases/app/schema.ts
@@ -1,4 +1,3 @@
-import { WorkspaceRole } from '@colanode/core';
import { ColumnType, Insertable, Selectable, Updateable } from 'kysely';
interface ServerTable {
@@ -29,20 +28,6 @@ export type SelectAccount = Selectable<AccountTable>;
export type CreateAccount = Insertable<AccountTable>;
export type UpdateAccount = Updateable<AccountTable>;
-interface WorkspaceTable {
- user_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- account_id: ColumnType<string, string, never>;
- name: ColumnType<string, string, string>;
- description: ColumnType<string | null, string | null, string | null>;
- avatar: ColumnType<string | null, string | null, string | null>;
- role: ColumnType<WorkspaceRole, WorkspaceRole, WorkspaceRole>;
-}
-
-export type SelectWorkspace = Selectable<WorkspaceTable>;
-export type CreateWorkspace = Insertable<WorkspaceTable>;
-export type UpdateWorkspace = Updateable<WorkspaceTable>;
-
interface DeletedTokenTable {
token: ColumnType<string, string, never>;
account_id: ColumnType<string, string, never>;
@@ -64,7 +49,6 @@ export type UpdateMetadata = Updateable<MetadataTable>;
export interface AppDatabaseSchema {
servers: ServerTable;
accounts: AccountTable;
- workspaces: WorkspaceTable;
deleted_tokens: DeletedTokenTable;
metadata: MetadataTable;
}
diff --git a/apps/desktop/src/main/databases/workspace/index.ts b/apps/desktop/src/main/databases/workspace/index.ts
new file mode 100644
index 00000000..adaca880
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/index.ts
@@ -0,0 +1,2 @@
+export * from './schema';
+export * from './migrations';
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts
new file mode 100644
index 00000000..8bdada7b
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts
@@ -0,0 +1,25 @@
+import { Migration } from 'kysely';
+
+export const createUsersTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('users')
+ .addColumn('id', 'text', (col) => col.primaryKey().notNull())
+ .addColumn('email', 'text', (col) => col.notNull())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('avatar', 'text')
+ .addColumn('custom_name', 'text')
+ .addColumn('custom_avatar', 'text')
+ .addColumn('role', 'text', (col) => col.notNull())
+ .addColumn('storage_limit', 'integer', (col) => col.notNull())
+ .addColumn('max_file_size', 'integer', (col) => col.notNull())
+ .addColumn('status', 'integer', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('version', 'integer')
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('users').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00002-create-entries-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00002-create-entries-table.ts
new file mode 100644
index 00000000..d9dd1943
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00002-create-entries-table.ts
@@ -0,0 +1,37 @@
+import { Migration, sql } from 'kysely';
+
+export const createEntriesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('entries')
+ .addColumn('id', 'text', (col) => col.primaryKey().notNull())
+ .addColumn('type', 'text', (col) =>
+ col
+ .notNull()
+ .generatedAlwaysAs(sql`json_extract(attributes, '$.type')`)
+ .stored()
+ )
+ .addColumn('parent_id', 'text', (col) =>
+ col
+ .generatedAlwaysAs(sql`json_extract(attributes, '$.parentId')`)
+ .stored()
+ )
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('attributes', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('created_by', 'text', (col) => col.notNull())
+ .addColumn('updated_by', 'text')
+ .addColumn('transaction_id', 'text', (col) => col.notNull())
+ .execute();
+
+ await db.schema
+ .createIndex('entries_parent_id_type_index')
+ .on('entries')
+ .columns(['parent_id', 'type'])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('entries').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00003-create-entry-transactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00003-create-entry-transactions-table.ts
new file mode 100644
index 00000000..4058cbea
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00003-create-entry-transactions-table.ts
@@ -0,0 +1,21 @@
+import { Migration } from 'kysely';
+
+export const createEntryTransactionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('entry_transactions')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('entry_id', 'text', (col) => col.notNull())
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('operation', 'integer', (col) => col.notNull())
+ .addColumn('data', 'blob')
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('created_by', 'text', (col) => col.notNull())
+ .addColumn('server_created_at', 'text')
+ .addColumn('version', 'integer', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('entry_transactions').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00004-create-entry-interactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00004-create-entry-interactions-table.ts
new file mode 100644
index 00000000..0781ae5d
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00004-create-entry-interactions-table.ts
@@ -0,0 +1,24 @@
+import { Migration } from 'kysely';
+
+export const createEntryInteractionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('entry_interactions')
+ .addColumn('entry_id', 'text', (col) => col.notNull())
+ .addColumn('collaborator_id', 'text', (col) => col.notNull())
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('first_seen_at', 'text')
+ .addColumn('last_seen_at', 'text')
+ .addColumn('first_opened_at', 'text')
+ .addColumn('last_opened_at', 'text')
+ .addColumn('version', 'integer', (col) => col.notNull())
+ .addPrimaryKeyConstraint('entry_interactions_pkey', [
+ 'entry_id',
+ 'collaborator_id',
+ ])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('entry_interactions').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00005-create-collaborations-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00005-create-collaborations-table.ts
new file mode 100644
index 00000000..73d42f1d
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00005-create-collaborations-table.ts
@@ -0,0 +1,18 @@
+import { Migration } from 'kysely';
+
+export const createCollaborationsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('collaborations')
+ .addColumn('entry_id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('role', 'text')
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('deleted_at', 'text')
+ .addColumn('version', 'integer')
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('collaborations').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00006-create-messages-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00006-create-messages-table.ts
new file mode 100644
index 00000000..87798b82
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00006-create-messages-table.ts
@@ -0,0 +1,35 @@
+import { Migration, sql } from 'kysely';
+
+export const createMessagesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('messages')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('type', 'integer', (col) =>
+ col
+ .notNull()
+ .generatedAlwaysAs(sql`json_extract(attributes, '$.type')`)
+ .stored()
+ )
+ .addColumn('parent_id', 'text', (col) => col.notNull())
+ .addColumn('entry_id', 'text', (col) => col.notNull())
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('attributes', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('created_by', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('updated_by', 'text')
+ .addColumn('deleted_at', 'text')
+ .addColumn('version', 'integer')
+ .execute();
+
+ await db.schema
+ .createIndex('messages_parent_id_index')
+ .on('messages')
+ .columns(['parent_id'])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('messages').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00007-create-message-reactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00007-create-message-reactions-table.ts
new file mode 100644
index 00000000..dd9f9e7a
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00007-create-message-reactions-table.ts
@@ -0,0 +1,24 @@
+import { Migration } from 'kysely';
+
+export const createMessageReactionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('message_reactions')
+ .addColumn('message_id', 'text', (col) => col.notNull())
+ .addColumn('collaborator_id', 'text', (col) => col.notNull())
+ .addColumn('reaction', 'text', (col) => col.notNull())
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('deleted_at', 'text')
+ .addColumn('version', 'integer', (col) => col.notNull())
+ .addPrimaryKeyConstraint('message_reactions_pkey', [
+ 'message_id',
+ 'collaborator_id',
+ 'reaction',
+ ])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('message_reactions').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00008-create-message-interactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00008-create-message-interactions-table.ts
new file mode 100644
index 00000000..78f709cc
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00008-create-message-interactions-table.ts
@@ -0,0 +1,24 @@
+import { Migration } from 'kysely';
+
+export const createMessageInteractionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('message_interactions')
+ .addColumn('message_id', 'text', (col) => col.notNull())
+ .addColumn('collaborator_id', 'text', (col) => col.notNull())
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('first_seen_at', 'text')
+ .addColumn('last_seen_at', 'text')
+ .addColumn('first_opened_at', 'text')
+ .addColumn('last_opened_at', 'text')
+ .addColumn('version', 'integer', (col) => col.notNull())
+ .addPrimaryKeyConstraint('message_interactions_pkey', [
+ 'message_id',
+ 'collaborator_id',
+ ])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('message_interactions').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00009-create-files-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00009-create-files-table.ts
new file mode 100644
index 00000000..cfaa1355
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00009-create-files-table.ts
@@ -0,0 +1,35 @@
+import { Migration } from 'kysely';
+
+export const createFilesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('files')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('type', 'text', (col) => col.notNull())
+ .addColumn('parent_id', 'text', (col) => col.notNull())
+ .addColumn('entry_id', 'text', (col) => col.notNull())
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('original_name', 'text', (col) => col.notNull())
+ .addColumn('mime_type', 'text', (col) => col.notNull())
+ .addColumn('extension', 'text', (col) => col.notNull())
+ .addColumn('size', 'integer', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('created_by', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('updated_by', 'text')
+ .addColumn('deleted_at', 'text')
+ .addColumn('status', 'integer', (col) => col.notNull())
+ .addColumn('version', 'integer')
+ .execute();
+
+ await db.schema
+ .createIndex('files_parent_id_index')
+ .on('files')
+ .columns(['parent_id'])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('files').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts
new file mode 100644
index 00000000..7420c7c1
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts
@@ -0,0 +1,21 @@
+import { Migration } from 'kysely';
+
+export const createFileStatesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('file_states')
+ .addColumn('file_id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('download_status', 'integer', (col) => col.notNull())
+ .addColumn('download_progress', 'integer', (col) => col.notNull())
+ .addColumn('download_retries', 'integer', (col) => col.notNull())
+ .addColumn('upload_status', 'integer', (col) => col.notNull())
+ .addColumn('upload_progress', 'integer', (col) => col.notNull())
+ .addColumn('upload_retries', 'integer', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('file_states').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00011-create-file-interactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00011-create-file-interactions-table.ts
new file mode 100644
index 00000000..3ba5cff4
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00011-create-file-interactions-table.ts
@@ -0,0 +1,23 @@
+import { Migration } from 'kysely';
+
+export const createFileInteractionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('file_interactions')
+ .addColumn('file_id', 'text', (col) => col.notNull())
+ .addColumn('collaborator_id', 'text', (col) => col.notNull())
+ .addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('seen_at', 'text')
+ .addColumn('first_opened_at', 'text')
+ .addColumn('last_opened_at', 'text')
+ .addColumn('version', 'integer', (col) => col.notNull())
+ .addPrimaryKeyConstraint('file_interactions_pkey', [
+ 'file_id',
+ 'collaborator_id',
+ ])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('file_interactions').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00012-create-mutations-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00012-create-mutations-table.ts
new file mode 100644
index 00000000..a3914d90
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00012-create-mutations-table.ts
@@ -0,0 +1,17 @@
+import { Migration } from 'kysely';
+
+export const createMutationsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('mutations')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('type', 'text', (col) => col.notNull())
+ .addColumn('data', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('retries', 'integer', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('mutations').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00013-create-entry-paths-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00013-create-entry-paths-table.ts
new file mode 100644
index 00000000..6a9e72a1
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00013-create-entry-paths-table.ts
@@ -0,0 +1,63 @@
+import { Migration, sql } from 'kysely';
+
+export const createEntryPathsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('entry_paths')
+ .addColumn('ancestor_id', 'varchar(30)', (col) =>
+ col.notNull().references('entries.id').onDelete('cascade')
+ )
+ .addColumn('descendant_id', 'varchar(30)', (col) =>
+ col.notNull().references('entries.id').onDelete('cascade')
+ )
+ .addColumn('level', 'integer', (col) => col.notNull())
+ .addPrimaryKeyConstraint('entry_paths_pkey', [
+ 'ancestor_id',
+ 'descendant_id',
+ ])
+ .execute();
+
+ await sql`
+ CREATE TRIGGER trg_insert_entry_path
+ AFTER INSERT ON entries
+ FOR EACH ROW
+ BEGIN
+ -- Insert direct path from the new entry to itself
+ INSERT INTO entry_paths (ancestor_id, descendant_id, level)
+ VALUES (NEW.id, NEW.id, 0);
+
+ -- Insert paths from ancestors to the new entry
+ INSERT INTO entry_paths (ancestor_id, descendant_id, level)
+ SELECT ancestor_id, NEW.id, level + 1
+ FROM entry_paths
+ WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
+ END;
+ `.execute(db);
+
+ await sql`
+ CREATE TRIGGER trg_update_entry_path
+ AFTER UPDATE ON entries
+ FOR EACH ROW
+ WHEN OLD.parent_id <> NEW.parent_id
+ BEGIN
+ -- Delete old paths involving the updated entry
+ DELETE FROM entry_paths
+ WHERE descendant_id = NEW.id AND ancestor_id <> NEW.id;
+
+ -- Insert new paths from ancestors to the updated entry
+ INSERT INTO entry_paths (ancestor_id, descendant_id, level)
+ SELECT ancestor_id, NEW.id, level + 1
+ FROM entry_paths
+ WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
+ END;
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_insert_entry_path;
+ DROP TRIGGER IF EXISTS trg_update_entry_path;
+ `.execute(db);
+
+ await db.schema.dropTable('entry_paths').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00014-create-texts-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00014-create-texts-table.ts
new file mode 100644
index 00000000..ace93821
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00014-create-texts-table.ts
@@ -0,0 +1,14 @@
+import { Migration, sql } from 'kysely';
+
+export const createTextsTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE VIRTUAL TABLE texts USING fts5(id UNINDEXED, name, text);
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TABLE IF EXISTS texts;
+ `.execute(db);
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00015-create-cursors-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00015-create-cursors-table.ts
new file mode 100644
index 00000000..9f0430e4
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00015-create-cursors-table.ts
@@ -0,0 +1,16 @@
+import { Migration } from 'kysely';
+
+export const createCursorsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('cursors')
+ .addColumn('key', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('value', 'integer', (col) => col.notNull().defaultTo(0))
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('cursors').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/index.ts b/apps/desktop/src/main/databases/workspace/migrations/index.ts
new file mode 100644
index 00000000..77f56ee9
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/index.ts
@@ -0,0 +1,35 @@
+import { Migration } from 'kysely';
+
+import { createUsersTable } from './00001-create-users-table';
+import { createEntriesTable } from './00002-create-entries-table';
+import { createEntryInteractionsTable } from './00004-create-entry-interactions-table';
+import { createEntryTransactionsTable } from './00003-create-entry-transactions-table';
+import { createCollaborationsTable } from './00005-create-collaborations-table';
+import { createMessagesTable } from './00006-create-messages-table';
+import { createMessageReactionsTable } from './00007-create-message-reactions-table';
+import { createMessageInteractionsTable } from './00008-create-message-interactions-table';
+import { createFilesTable } from './00009-create-files-table';
+import { createFileStatesTable } from './00010-create-file-states-table';
+import { createFileInteractionsTable } from './00011-create-file-interactions-table';
+import { createMutationsTable } from './00012-create-mutations-table';
+import { createEntryPathsTable } from './00013-create-entry-paths-table';
+import { createTextsTable } from './00014-create-texts-table';
+import { createCursorsTable } from './00015-create-cursors-table';
+
+export const workspaceDatabaseMigrations: Record<string, Migration> = {
+ '00001-create-users-table': createUsersTable,
+ '00002-create-entries-table': createEntriesTable,
+ '00003-create-entry-transactions-table': createEntryTransactionsTable,
+ '00004-create-entry-interactions-table': createEntryInteractionsTable,
+ '00005-create-collaborations-table': createCollaborationsTable,
+ '00006-create-messages-table': createMessagesTable,
+ '00007-create-message-reactions-table': createMessageReactionsTable,
+ '00008-create-message-interactions-table': createMessageInteractionsTable,
+ '00009-create-files-table': createFilesTable,
+ '00010-create-file-states-table': createFileStatesTable,
+ '00011-create-file-interactions-table': createFileInteractionsTable,
+ '00012-create-mutations-table': createMutationsTable,
+ '00013-create-entry-paths-table': createEntryPathsTable,
+ '00014-create-texts-table': createTextsTable,
+ '00015-create-cursors-table': createCursorsTable,
+};
diff --git a/apps/desktop/src/main/data/workspace/schema.ts b/apps/desktop/src/main/databases/workspace/schema.ts
similarity index 100%
rename from apps/desktop/src/main/data/workspace/schema.ts
rename to apps/desktop/src/main/databases/workspace/schema.ts
diff --git a/apps/desktop/src/main/jobs/clean-deleted-files.ts b/apps/desktop/src/main/jobs/clean-deleted-files.ts
deleted file mode 100644
index 29b54cac..00000000
--- a/apps/desktop/src/main/jobs/clean-deleted-files.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { fileService } from '@/main/services/file-service';
-import { JobHandler } from '@/main/jobs';
-
-export type CleanDeletedFilesInput = {
- type: 'clean_deleted_files';
- userId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- clean_deleted_files: {
- input: CleanDeletedFilesInput;
- };
- }
-}
-
-export class CleanDeletedFilesJobHandler
- implements JobHandler<CleanDeletedFilesInput>
-{
- public triggerDebounce = 1000;
- public interval = 1000 * 60 * 10;
-
- public async handleJob(input: CleanDeletedFilesInput) {
- await fileService.cleanDeletedFiles(input.userId);
- }
-}
diff --git a/apps/desktop/src/main/jobs/clean-temp-files.ts b/apps/desktop/src/main/jobs/clean-temp-files.ts
deleted file mode 100644
index 3ed71fe7..00000000
--- a/apps/desktop/src/main/jobs/clean-temp-files.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { fileService } from '@/main/services/file-service';
-import { JobHandler } from '@/main/jobs';
-
-export type CleanTempFilesInput = {
- type: 'clean_temp_files';
- userId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- clean_temp_files: {
- input: CleanTempFilesInput;
- };
- }
-}
-
-export class CleanTempFilesJobHandler
- implements JobHandler<CleanTempFilesInput>
-{
- public triggerDebounce = 1000;
- public interval = 1000 * 60 * 30;
-
- public async handleJob(input: CleanTempFilesInput) {
- await fileService.cleanTempFiles(input.userId);
- }
-}
diff --git a/apps/desktop/src/main/jobs/connect-socket.ts b/apps/desktop/src/main/jobs/connect-socket.ts
deleted file mode 100644
index 7ca5a3e6..00000000
--- a/apps/desktop/src/main/jobs/connect-socket.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { createDebugger } from '@colanode/core';
-
-import { databaseService } from '@/main/data/database-service';
-import { socketService } from '@/main/services/socket-service';
-import { JobHandler } from '@/main/jobs';
-
-export type ConnectSocketInput = {
- type: 'connect_socket';
- accountId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- connect_socket: {
- input: ConnectSocketInput;
- };
- }
-}
-
-export class ConnectSocketJobHandler implements JobHandler<ConnectSocketInput> {
- public triggerDebounce = 0;
- public interval = 1000 * 30;
-
- private readonly debug = createDebugger('desktop:job:connect-socket');
-
- public async handleJob(input: ConnectSocketInput) {
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', input.accountId)
- .executeTakeFirst();
-
- if (!account) {
- this.debug(`Account ${input.accountId} not found`);
- return;
- }
-
- this.debug(`Checking connection to socket for account ${account.email}`);
- socketService.checkConnection(account);
- }
-}
diff --git a/apps/desktop/src/main/jobs/download-files.ts b/apps/desktop/src/main/jobs/download-files.ts
deleted file mode 100644
index fc778303..00000000
--- a/apps/desktop/src/main/jobs/download-files.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { fileService } from '@/main/services/file-service';
-import { JobHandler } from '@/main/jobs';
-
-export type DownloadFilesInput = {
- type: 'download_files';
- userId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- download_files: {
- input: DownloadFilesInput;
- };
- }
-}
-
-export class DownloadFilesJobHandler implements JobHandler<DownloadFilesInput> {
- public triggerDebounce = 0;
- public interval = 1000 * 60;
-
- public async handleJob(input: DownloadFilesInput) {
- await fileService.downloadFiles(input.userId);
- }
-}
diff --git a/apps/desktop/src/main/jobs/index.ts b/apps/desktop/src/main/jobs/index.ts
deleted file mode 100644
index 46c6b32b..00000000
--- a/apps/desktop/src/main/jobs/index.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// eslint-disable-next-line @typescript-eslint/no-empty-object-type
-export interface JobMap {}
-
-export type JobInput = JobMap[keyof JobMap]['input'];
-
-export interface JobHandler<T extends JobInput> {
- triggerDebounce: number;
- interval: number;
- handleJob: (input: T) => Promise<void>;
-}
diff --git a/apps/desktop/src/main/jobs/init-synchronizers.ts b/apps/desktop/src/main/jobs/init-synchronizers.ts
deleted file mode 100644
index 17b8691d..00000000
--- a/apps/desktop/src/main/jobs/init-synchronizers.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { syncService } from '@/main/services/sync-service';
-import { JobHandler } from '@/main/jobs';
-
-export type InitSynchronizersInput = {
- type: 'init_synchronizers';
- userId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- init_synchronizers: {
- input: InitSynchronizersInput;
- };
- }
-}
-
-export class InitSynchronizersJobHandler
- implements JobHandler<InitSynchronizersInput>
-{
- public triggerDebounce = 100;
- public interval = 1000 * 60;
-
- public async handleJob(input: InitSynchronizersInput) {
- syncService.initSynchronizers(input.userId);
- }
-}
diff --git a/apps/desktop/src/main/jobs/revert-invalid-mutations.ts b/apps/desktop/src/main/jobs/revert-invalid-mutations.ts
deleted file mode 100644
index 1bbb036d..00000000
--- a/apps/desktop/src/main/jobs/revert-invalid-mutations.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { createDebugger } from '@colanode/core';
-
-import { entryService } from '@/main/services/entry-service';
-import { fileService } from '@/main/services/file-service';
-import { messageService } from '@/main/services/message-service';
-import { databaseService } from '@/main/data/database-service';
-import { JobHandler } from '@/main/jobs';
-import { mapMutation } from '@/main/utils';
-
-export type RevertInvalidMutationsInput = {
- type: 'revert_invalid_mutations';
- userId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- revert_invalid_mutations: {
- input: RevertInvalidMutationsInput;
- };
- }
-}
-
-export class RevertInvalidMutationsJobHandler
- implements JobHandler<RevertInvalidMutationsInput>
-{
- public triggerDebounce = 100;
- public interval = 1000 * 60 * 5;
-
- private readonly debug = createDebugger(
- 'desktop:job:revert-invalid-mutations'
- );
-
- public async handleJob(input: RevertInvalidMutationsInput) {
- this.debug(`Reverting invalid mutations for user ${input.userId}`);
-
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
-
- const invalidMutations = await workspaceDatabase
- .selectFrom('mutations')
- .selectAll()
- .where('retries', '>=', 10)
- .execute();
-
- if (invalidMutations.length === 0) {
- this.debug(
- `No invalid mutations found for user ${input.userId}, skipping`
- );
- return;
- }
-
- for (const mutationRow of invalidMutations) {
- const mutation = mapMutation(mutationRow);
-
- if (mutation.type === 'create_file') {
- await fileService.revertFileCreation(input.userId, mutation.id);
- } else if (mutation.type === 'delete_file') {
- await fileService.revertFileDeletion(input.userId, mutation.id);
- } else if (mutation.type === 'apply_create_transaction') {
- await entryService.revertCreateTransaction(input.userId, mutation.data);
- } else if (mutation.type === 'apply_update_transaction') {
- await entryService.revertUpdateTransaction(input.userId, mutation.data);
- } else if (mutation.type === 'apply_delete_transaction') {
- await entryService.revertDeleteTransaction(input.userId, mutation.data);
- } else if (mutation.type === 'create_message') {
- await messageService.revertMessageCreation(
- input.userId,
- mutation.data.id
- );
- } else if (mutation.type === 'delete_message') {
- await messageService.revertMessageDeletion(
- input.userId,
- mutation.data.id
- );
- } else if (mutation.type === 'create_message_reaction') {
- await messageService.revertMessageReactionCreation(
- input.userId,
- mutation.data
- );
- } else if (mutation.type === 'delete_message_reaction') {
- await messageService.revertMessageReactionDeletion(
- input.userId,
- mutation.data
- );
- }
- }
-
- const mutationIds = invalidMutations.map((m) => m.id);
-
- await workspaceDatabase
- .deleteFrom('mutations')
- .where('id', 'in', mutationIds)
- .execute();
- }
-}
diff --git a/apps/desktop/src/main/jobs/sync-account.ts b/apps/desktop/src/main/jobs/sync-account.ts
deleted file mode 100644
index 029a34a8..00000000
--- a/apps/desktop/src/main/jobs/sync-account.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { accountService } from '@/main/services/account-service';
-import { JobHandler } from '@/main/jobs';
-
-export type SyncAccountInput = {
- type: 'sync_account';
- accountId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- sync_account: {
- input: SyncAccountInput;
- };
- }
-}
-
-export class SyncAccountJobHandler implements JobHandler<SyncAccountInput> {
- public triggerDebounce = 0;
- public interval = 1000 * 60;
-
- public async handleJob(input: SyncAccountInput) {
- await accountService.syncAccount(input.accountId);
- }
-}
diff --git a/apps/desktop/src/main/jobs/sync-deleted-tokens.ts b/apps/desktop/src/main/jobs/sync-deleted-tokens.ts
deleted file mode 100644
index 40c17e02..00000000
--- a/apps/desktop/src/main/jobs/sync-deleted-tokens.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { ApiErrorCode, createDebugger } from '@colanode/core';
-
-import { serverService } from '@/main/services/server-service';
-import { databaseService } from '@/main/data/database-service';
-import { JobHandler } from '@/main/jobs';
-import { httpClient } from '@/shared/lib/http-client';
-import { parseApiError } from '@/shared/lib/axios';
-
-export type SyncDeletedTokensInput = {
- type: 'sync_deleted_tokens';
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- sync_deleted_tokens: {
- input: SyncDeletedTokensInput;
- };
- }
-}
-
-export class SyncDeletedTokensJobHandler
- implements JobHandler<SyncDeletedTokensInput>
-{
- public triggerDebounce = 100;
- public interval = 1000 * 60 * 5;
-
- private readonly debug = createDebugger('desktop:job:sync-deleted-tokens');
-
- public async handleJob(_: SyncDeletedTokensInput) {
- this.debug('Syncing deleted tokens');
-
- const deletedTokens = await databaseService.appDatabase
- .selectFrom('deleted_tokens')
- .innerJoin('servers', 'deleted_tokens.server', 'servers.domain')
- .select([
- 'deleted_tokens.token',
- 'deleted_tokens.account_id',
- 'servers.domain',
- 'servers.attributes',
- ])
- .execute();
-
- if (deletedTokens.length === 0) {
- this.debug('No deleted tokens found');
- return;
- }
-
- for (const deletedToken of deletedTokens) {
- if (!serverService.isAvailable(deletedToken.domain)) {
- this.debug(
- `Server ${deletedToken.domain} is not available for logging out account ${deletedToken.account_id}`
- );
- continue;
- }
-
- try {
- const { status } = await httpClient.delete(`/v1/accounts/logout`, {
- domain: deletedToken.domain,
- token: deletedToken.token,
- });
-
- this.debug(`Deleted token logout response status code: ${status}`);
-
- if (status !== 200) {
- return;
- }
-
- await databaseService.appDatabase
- .deleteFrom('deleted_tokens')
- .where('token', '=', deletedToken.token)
- .where('account_id', '=', deletedToken.account_id)
- .execute();
-
- this.debug(
- `Logged out account ${deletedToken.account_id} from server ${deletedToken.domain}`
- );
- } catch (error) {
- const parsedError = parseApiError(error);
- if (
- parsedError.code === ApiErrorCode.TokenInvalid ||
- parsedError.code === ApiErrorCode.AccountNotFound ||
- parsedError.code === ApiErrorCode.DeviceNotFound
- ) {
- this.debug(
- `Account ${deletedToken.account_id} is already logged out, skipping...`
- );
-
- await databaseService.appDatabase
- .deleteFrom('deleted_tokens')
- .where('token', '=', deletedToken.token)
- .where('account_id', '=', deletedToken.account_id)
- .execute();
-
- continue;
- }
-
- this.debug(
- `Failed to logout account ${deletedToken.account_id} from server ${deletedToken.domain}`,
- error
- );
- }
- }
- }
-}
diff --git a/apps/desktop/src/main/jobs/sync-servers.ts b/apps/desktop/src/main/jobs/sync-servers.ts
deleted file mode 100644
index 8b6dc863..00000000
--- a/apps/desktop/src/main/jobs/sync-servers.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { serverService } from '@/main/services/server-service';
-import { JobHandler } from '@/main/jobs';
-
-export type SyncServersInput = {
- type: 'sync_servers';
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- sync_servers: {
- input: SyncServersInput;
- };
- }
-}
-
-export class SyncServersJobHandler implements JobHandler<SyncServersInput> {
- public triggerDebounce = 0;
- public interval = 1000 * 60;
-
- public async handleJob(_: SyncServersInput) {
- await serverService.syncServers();
- }
-}
diff --git a/apps/desktop/src/main/jobs/upload-files.ts b/apps/desktop/src/main/jobs/upload-files.ts
deleted file mode 100644
index 33668312..00000000
--- a/apps/desktop/src/main/jobs/upload-files.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { fileService } from '@/main/services/file-service';
-import { JobHandler } from '@/main/jobs';
-
-export type UploadFilesInput = {
- type: 'upload_files';
- userId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- upload_files: {
- input: UploadFilesInput;
- };
- }
-}
-
-export class UploadFilesJobHandler implements JobHandler<UploadFilesInput> {
- public triggerDebounce = 0;
- public interval = 1000 * 60;
-
- public async handleJob(input: UploadFilesInput) {
- await fileService.uploadFiles(input.userId);
- }
-}
diff --git a/apps/desktop/src/main/lib/assets.ts b/apps/desktop/src/main/lib/assets.ts
new file mode 100644
index 00000000..1de24c71
--- /dev/null
+++ b/apps/desktop/src/main/lib/assets.ts
@@ -0,0 +1,24 @@
+import fs from 'fs';
+import path from 'path';
+
+import { getAssetsSourcePath } from '@/main/utils';
+import { EmojiData } from '@/shared/types/emojis';
+import { IconData } from '@/shared/types/icons';
+
+export const getEmojiData = (): EmojiData => {
+ const emojisMetadataPath = path.join(
+ getAssetsSourcePath(),
+ 'emojis',
+ 'emojis.json'
+ );
+ return JSON.parse(fs.readFileSync(emojisMetadataPath, 'utf8'));
+};
+
+export const getIconData = (): IconData => {
+ const iconsMetadataPath = path.join(
+ getAssetsSourcePath(),
+ 'icons',
+ 'icons.json'
+ );
+ return JSON.parse(fs.readFileSync(iconsMetadataPath, 'utf8'));
+};
diff --git a/apps/desktop/src/main/lib/protocols.ts b/apps/desktop/src/main/lib/protocols.ts
new file mode 100644
index 00000000..146a17f0
--- /dev/null
+++ b/apps/desktop/src/main/lib/protocols.ts
@@ -0,0 +1,102 @@
+import { net } from 'electron';
+import fs from 'fs';
+import path from 'path';
+
+import {
+ getAccountAvatarsDirectoryPath,
+ getAssetsSourcePath,
+ getWorkspaceFilesDirectoryPath,
+} from '@/main/utils';
+import { appService } from '@/main/services/app-service';
+
+export const handleAssetRequest = (request: Request): Promise<Response> => {
+ const url = request.url.replace('asset://', '');
+ const assetPath = path.join(getAssetsSourcePath(), url);
+ const localFileUrl = `file://${assetPath}`;
+ return net.fetch(localFileUrl);
+};
+
+export const handleAvatarRequest = async (
+ request: Request
+): Promise<Response> => {
+ const url = request.url.replace('avatar://', '');
+ const [accountId, avatarId] = url.split('/');
+ if (!accountId || !avatarId) {
+ return new Response(null, { status: 400 });
+ }
+
+ const avatarsDir = getAccountAvatarsDirectoryPath(accountId);
+ const avatarPath = path.join(avatarsDir, `${avatarId}.jpeg`);
+ const avatarLocalUrl = `file://${avatarPath}`;
+
+ // Check if the avatar file already exists
+ if (fs.existsSync(avatarPath)) {
+ return net.fetch(avatarLocalUrl);
+ }
+
+ // Download the avatar file if it doesn't exist
+ const account = appService.getAccount(accountId);
+
+ if (!account) {
+ return new Response(null, { status: 404 });
+ }
+
+ const response = await account.client.get<NodeJS.ReadableStream>(
+ `/v1/avatars/${avatarId}`,
+ {
+ responseType: 'stream',
+ }
+ );
+
+ if (response.status !== 200 || !response.data) {
+ return new Response(null, { status: 404 });
+ }
+
+ if (!fs.existsSync(avatarsDir)) {
+ fs.mkdirSync(avatarsDir, { recursive: true });
+ }
+
+ const fileStream = fs.createWriteStream(avatarPath);
+
+ return new Promise((resolve, reject) => {
+ response.data.pipe(fileStream);
+
+ fileStream.on('finish', async () => {
+ resolve(net.fetch(avatarLocalUrl));
+ });
+
+ fileStream.on('error', (err) => {
+ reject(new Response(null, { status: 500, statusText: err.message }));
+ });
+ });
+};
+
+export const handleFilePreviewRequest = async (
+ request: Request
+): Promise<Response> => {
+ const url = request.url.replace('local-file-preview://', 'file://');
+ return net.fetch(url);
+};
+
+export const handleFileRequest = async (
+ request: Request
+): Promise<Response> => {
+ const url = request.url.replace('local-file://', '');
+ const [accountId, workspaceId, file] = url.split('/');
+ if (!accountId || !workspaceId || !file) {
+ return new Response(null, { status: 400 });
+ }
+
+ const workspaceFilesDir = getWorkspaceFilesDirectoryPath(
+ accountId,
+ workspaceId
+ );
+ const filePath = path.join(workspaceFilesDir, file);
+
+ if (fs.existsSync(filePath)) {
+ const fileUrl = `file://${filePath}`;
+ return net.fetch(fileUrl);
+ }
+
+ return new Response(null, { status: 404 });
+};
diff --git a/apps/desktop/src/main/services/query-service.ts b/apps/desktop/src/main/mediator.ts
similarity index 63%
rename from apps/desktop/src/main/services/query-service.ts
rename to apps/desktop/src/main/mediator.ts
index 65d1748d..a0c7451c 100644
--- a/apps/desktop/src/main/services/query-service.ts
+++ b/apps/desktop/src/main/mediator.ts
@@ -1,14 +1,29 @@
-import { isEqual } from 'lodash-es';
import { createDebugger } from '@colanode/core';
+import { isEqual } from 'lodash-es';
+import { mutationHandlerMap } from '@/main/mutations';
+import {
+ MutationHandler,
+ CommandHandler,
+ QueryHandler,
+ SubscribedQuery,
+} from '@/main/types';
+import {
+ MutationError,
+ MutationErrorCode,
+ MutationInput,
+ MutationResult,
+} from '@/shared/mutations';
+import { commandHandlerMap } from '@/main/commands';
+import { CommandInput, CommandMap } from '@/shared/commands';
import { queryHandlerMap } from '@/main/queries';
-import { QueryHandler, SubscribedQuery } from '@/main/types';
import { eventBus } from '@/shared/lib/event-bus';
import { QueryInput, QueryMap } from '@/shared/queries';
import { Event } from '@/shared/types/events';
-class QueryService {
- private readonly debug = createDebugger('desktop:service:query');
+class Mediator {
+ private readonly debug = createDebugger('desktop:mediator');
+
private readonly subscribedQueries: Map<string, SubscribedQuery<QueryInput>> =
new Map();
@@ -127,6 +142,60 @@ class QueryService {
this.processEventsQueue();
}
}
+
+ public async executeMutation<T extends MutationInput>(
+ input: T
+ ): Promise<MutationResult<T>> {
+ const handler = mutationHandlerMap[
+ input.type
+ ] as unknown as MutationHandler<T>;
+
+ this.debug(`Executing mutation: ${input.type}`);
+
+ try {
+ if (!handler) {
+ throw new Error(`No handler found for mutation type: ${input.type}`);
+ }
+
+ const output = await handler.handleMutation(input);
+ return { success: true, output };
+ } catch (error) {
+ this.debug(`Error executing mutation: ${input.type}`, error);
+ if (error instanceof MutationError) {
+ return {
+ success: false,
+ error: {
+ code: error.code,
+ message: error.message,
+ },
+ };
+ }
+
+ return {
+ success: false,
+ error: {
+ code: MutationErrorCode.Unknown,
+ message: 'Something went wrong trying to execute the mutation.',
+ },
+ };
+ }
+ }
+
+ public async executeCommand<T extends CommandInput>(
+ input: T
+ ): Promise<CommandMap[T['type']]['output']> {
+ this.debug(`Executing command: ${input.type}`);
+
+ const handler = commandHandlerMap[
+ input.type
+ ] as unknown as CommandHandler<T>;
+
+ if (!handler) {
+ throw new Error(`No handler found for command type: ${input.type}`);
+ }
+
+ return handler.handleCommand(input);
+ }
}
-export const queryService = new QueryService();
+export const mediator = new Mediator();
diff --git a/apps/desktop/src/main/mutations/accounts/account-logout.ts b/apps/desktop/src/main/mutations/accounts/account-logout.ts
index 3479505c..0c1684d1 100644
--- a/apps/desktop/src/main/mutations/accounts/account-logout.ts
+++ b/apps/desktop/src/main/mutations/accounts/account-logout.ts
@@ -1,5 +1,4 @@
-import { databaseService } from '@/main/data/database-service';
-import { accountService } from '@/main/services/account-service';
+import { appService } from '@/main/services/app-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
@@ -13,11 +12,7 @@ export class AccountLogoutMutationHandler
async handleMutation(
input: AccountLogoutMutationInput
): Promise<AccountLogoutMutationOutput> {
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', input.accountId)
- .executeTakeFirst();
+ const account = appService.getAccount(input.accountId);
if (!account) {
throw new MutationError(
@@ -26,7 +21,7 @@ export class AccountLogoutMutationHandler
);
}
- await accountService.logoutAccount(account);
+ await account.logout();
return {
success: true,
};
diff --git a/apps/desktop/src/main/mutations/accounts/account-update.ts b/apps/desktop/src/main/mutations/accounts/account-update.ts
index 271ae4b7..a077fc3f 100644
--- a/apps/desktop/src/main/mutations/accounts/account-update.ts
+++ b/apps/desktop/src/main/mutations/accounts/account-update.ts
@@ -1,15 +1,15 @@
import { AccountUpdateOutput } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import { eventBus } from '@/shared/lib/event-bus';
-import { httpClient } from '@/shared/lib/http-client';
import {
AccountUpdateMutationInput,
AccountUpdateMutationOutput,
} from '@/shared/mutations/accounts/account-update';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
+import { appService } from '@/main/services/app-service';
+import { mapAccount } from '@/main/utils';
export class AccountUpdateMutationHandler
implements MutationHandler<AccountUpdateMutationInput>
@@ -17,46 +17,25 @@ export class AccountUpdateMutationHandler
async handleMutation(
input: AccountUpdateMutationInput
): Promise<AccountUpdateMutationOutput> {
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', input.id)
- .executeTakeFirst();
+ const accountService = appService.getAccount(input.id);
- if (!account) {
+ if (!accountService) {
throw new MutationError(
MutationErrorCode.AccountNotFound,
'Account not found or has been logged out already. Try closing the app and opening it again.'
);
}
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', account.server)
- .executeTakeFirst();
-
- if (!server) {
- throw new MutationError(
- MutationErrorCode.ServerNotFound,
- `The server ${account.server} associated with this account was not found. Try closing the app and opening it again.`
- );
- }
-
try {
- const { data } = await httpClient.put<AccountUpdateOutput>(
+ const { data } = await accountService.client.put<AccountUpdateOutput>(
`/v1/accounts/${input.id}`,
{
name: input.name,
avatar: input.avatar,
- },
- {
- domain: server.domain,
- token: account.token,
}
);
- const updatedAccount = await databaseService.appDatabase
+ const updatedAccount = await appService.database
.updateTable('accounts')
.set({
name: data.name,
@@ -73,17 +52,12 @@ export class AccountUpdateMutationHandler
);
}
+ const account = mapAccount(updatedAccount);
+ accountService.updateAccount(account);
+
eventBus.publish({
type: 'account_updated',
- account: {
- id: updatedAccount.id,
- name: updatedAccount.name,
- email: updatedAccount.email,
- token: updatedAccount.token,
- avatar: updatedAccount.avatar,
- deviceId: updatedAccount.device_id,
- server: updatedAccount.server,
- },
+ account,
});
return {
diff --git a/apps/desktop/src/main/mutations/accounts/base.ts b/apps/desktop/src/main/mutations/accounts/base.ts
new file mode 100644
index 00000000..28d884d6
--- /dev/null
+++ b/apps/desktop/src/main/mutations/accounts/base.ts
@@ -0,0 +1,63 @@
+import { LoginSuccessOutput } from '@colanode/core';
+
+import { appService } from '@/main/services/app-service';
+import { ServerService } from '@/main/services/server-service';
+import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { mapAccount, mapWorkspace } from '@/main/utils';
+
+export abstract class AccountMutationHandlerBase {
+ protected async handleLoginSuccess(
+ login: LoginSuccessOutput,
+ server: ServerService
+ ): Promise<void> {
+ const createdAccount = await appService.database
+ .insertInto('accounts')
+ .returningAll()
+ .values({
+ id: login.account.id,
+ email: login.account.email,
+ name: login.account.name,
+ server: server.server.domain,
+ token: login.token,
+ device_id: login.deviceId,
+ avatar: login.account.avatar,
+ })
+ .executeTakeFirst();
+
+ if (!createdAccount) {
+ throw new MutationError(
+ MutationErrorCode.AccountLoginFailed,
+ 'Account login failed, please try again.'
+ );
+ }
+
+ const account = mapAccount(createdAccount);
+ const accountService = await appService.initAccount(account);
+
+ if (login.workspaces.length === 0) {
+ return;
+ }
+
+ for (const workspace of login.workspaces) {
+ const createdWorkspace = await accountService.database
+ .insertInto('workspaces')
+ .returningAll()
+ .values({
+ id: workspace.id,
+ name: workspace.name,
+ user_id: workspace.user.id,
+ account_id: account.id,
+ role: workspace.user.role,
+ avatar: workspace.avatar,
+ description: workspace.description,
+ })
+ .executeTakeFirst();
+
+ if (!createdWorkspace) {
+ continue;
+ }
+
+ await accountService.initWorkspace(mapWorkspace(createdWorkspace));
+ }
+ }
+}
diff --git a/apps/desktop/src/main/mutations/accounts/email-login.ts b/apps/desktop/src/main/mutations/accounts/email-login.ts
index 2633c2ed..82520699 100644
--- a/apps/desktop/src/main/mutations/accounts/email-login.ts
+++ b/apps/desktop/src/main/mutations/accounts/email-login.ts
@@ -1,24 +1,19 @@
import { EmailLoginInput, LoginOutput } from '@colanode/core';
+import axios from 'axios';
-import { app } from 'electron';
-
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
-import { httpClient } from '@/shared/lib/http-client';
import { EmailLoginMutationInput } from '@/shared/mutations/accounts/email-login';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
-import { accountService } from '@/main/services/account-service';
+import { appService } from '@/main/services/app-service';
+import { AccountMutationHandlerBase } from '@/main/mutations/accounts/base';
export class EmailLoginMutationHandler
+ extends AccountMutationHandlerBase
implements MutationHandler<EmailLoginMutationInput>
{
async handleMutation(input: EmailLoginMutationInput): Promise<LoginOutput> {
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', input.server)
- .executeTakeFirst();
+ const server = appService.getServer(input.server);
if (!server) {
throw new MutationError(
@@ -32,24 +27,23 @@ export class EmailLoginMutationHandler
email: input.email,
password: input.password,
platform: process.platform,
- version: app.getVersion(),
+ version: appService.version,
};
- const { data } = await httpClient.post<LoginOutput>(
- '/v1/accounts/emails/login',
- emailLoginInput,
- {
- domain: server.domain,
- }
+ const { data } = await axios.post<LoginOutput>(
+ `${server.apiBaseUrl}/v1/accounts/emails/login`,
+ emailLoginInput
);
if (data.type === 'verify') {
return data;
}
- await accountService.initAccount(data, server.domain);
+ await this.handleLoginSuccess(data, server);
+
return data;
} catch (error) {
+ console.error(error);
const apiError = parseApiError(error);
throw new MutationError(MutationErrorCode.ApiError, apiError.message);
}
diff --git a/apps/desktop/src/main/mutations/accounts/email-register.ts b/apps/desktop/src/main/mutations/accounts/email-register.ts
index 7e3f583b..9a4d29cd 100644
--- a/apps/desktop/src/main/mutations/accounts/email-register.ts
+++ b/apps/desktop/src/main/mutations/accounts/email-register.ts
@@ -1,26 +1,21 @@
import { EmailRegisterInput, LoginOutput } from '@colanode/core';
+import axios from 'axios';
-import { app } from 'electron';
-
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
-import { httpClient } from '@/shared/lib/http-client';
import { EmailRegisterMutationInput } from '@/shared/mutations/accounts/email-register';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
-import { accountService } from '@/main/services/account-service';
+import { appService } from '@/main/services/app-service';
+import { AccountMutationHandlerBase } from '@/main/mutations/accounts/base';
export class EmailRegisterMutationHandler
+ extends AccountMutationHandlerBase
implements MutationHandler<EmailRegisterMutationInput>
{
async handleMutation(
input: EmailRegisterMutationInput
): Promise<LoginOutput> {
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', input.server)
- .executeTakeFirst();
+ const server = appService.getServer(input.server);
if (!server) {
throw new MutationError(
@@ -35,22 +30,20 @@ export class EmailRegisterMutationHandler
email: input.email,
password: input.password,
platform: process.platform,
- version: app.getVersion(),
+ version: appService.version,
};
- const { data } = await httpClient.post<LoginOutput>(
- '/v1/accounts/emails/register',
- emailRegisterInput,
- {
- domain: server.domain,
- }
+ const { data } = await axios.post<LoginOutput>(
+ `${server.apiBaseUrl}/v1/accounts/emails/register`,
+ emailRegisterInput
);
if (data.type === 'verify') {
return data;
}
- await accountService.initAccount(data, server.domain);
+ await this.handleLoginSuccess(data, server);
+
return data;
} catch (error) {
const apiError = parseApiError(error);
diff --git a/apps/desktop/src/main/mutations/accounts/email-verify.ts b/apps/desktop/src/main/mutations/accounts/email-verify.ts
index 9ab1541d..2da2d0ef 100644
--- a/apps/desktop/src/main/mutations/accounts/email-verify.ts
+++ b/apps/desktop/src/main/mutations/accounts/email-verify.ts
@@ -1,24 +1,18 @@
import { EmailVerifyInput, LoginOutput } from '@colanode/core';
+import axios from 'axios';
-import { app } from 'electron';
-
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
-import { httpClient } from '@/shared/lib/http-client';
import { EmailVerifyMutationInput } from '@/shared/mutations/accounts/email-verify';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
-import { accountService } from '@/main/services/account-service';
-
+import { appService } from '@/main/services/app-service';
+import { AccountMutationHandlerBase } from '@/main/mutations/accounts/base';
export class EmailVerifyMutationHandler
+ extends AccountMutationHandlerBase
implements MutationHandler<EmailVerifyMutationInput>
{
async handleMutation(input: EmailVerifyMutationInput): Promise<LoginOutput> {
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', input.server)
- .executeTakeFirst();
+ const server = appService.getServer(input.server);
if (!server) {
throw new MutationError(
@@ -32,15 +26,12 @@ export class EmailVerifyMutationHandler
id: input.id,
otp: input.otp,
platform: process.platform,
- version: app.getVersion(),
+ version: appService.version,
};
- const { data } = await httpClient.post<LoginOutput>(
- '/v1/accounts/emails/verify',
- emailVerifyInput,
- {
- domain: server.domain,
- }
+ const { data } = await axios.post<LoginOutput>(
+ `${server.apiBaseUrl}/v1/accounts/emails/verify`,
+ emailVerifyInput
);
if (data.type === 'verify') {
@@ -50,7 +41,7 @@ export class EmailVerifyMutationHandler
);
}
- await accountService.initAccount(data, server.domain);
+ await this.handleLoginSuccess(data, server);
return data;
} catch (error) {
diff --git a/apps/desktop/src/main/mutations/avatars/avatar-upload.ts b/apps/desktop/src/main/mutations/avatars/avatar-upload.ts
index 356f3eef..1636a8cb 100644
--- a/apps/desktop/src/main/mutations/avatars/avatar-upload.ts
+++ b/apps/desktop/src/main/mutations/avatars/avatar-upload.ts
@@ -2,15 +2,14 @@ import FormData from 'form-data';
import fs from 'fs';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
-import { httpClient } from '@/shared/lib/http-client';
import {
AvatarUploadMutationInput,
AvatarUploadMutationOutput,
} from '@/shared/mutations/avatars/avatar-upload';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
+import { appService } from '@/main/services/app-service';
interface AvatarUploadResponse {
id: string;
@@ -22,14 +21,9 @@ export class AvatarUploadMutationHandler
async handleMutation(
input: AvatarUploadMutationInput
): Promise<AvatarUploadMutationOutput> {
- const credentials = await databaseService.appDatabase
- .selectFrom('accounts')
- .innerJoin('servers', 'accounts.server', 'servers.domain')
- .select(['domain', 'attributes', 'token'])
- .where('id', '=', input.accountId)
- .executeTakeFirst();
+ const account = appService.getAccount(input.accountId);
- if (!credentials) {
+ if (!account) {
throw new MutationError(
MutationErrorCode.AccountNotFound,
'Account not found or has been logged out already. Try closing the app and opening it again.'
@@ -43,12 +37,10 @@ export class AvatarUploadMutationHandler
const formData = new FormData();
formData.append('avatar', fileStream);
- const { data } = await httpClient.post<AvatarUploadResponse>(
+ const { data } = await account.client.post<AvatarUploadResponse>(
'/v1/avatars',
formData,
{
- domain: credentials.domain,
- token: credentials.token,
headers: formData.getHeaders(),
}
);
diff --git a/apps/desktop/src/main/mutations/channels/channel-create.ts b/apps/desktop/src/main/mutations/channels/channel-create.ts
index 0ea54bef..e6f05eee 100644
--- a/apps/desktop/src/main/mutations/channels/channel-create.ts
+++ b/apps/desktop/src/main/mutations/channels/channel-create.ts
@@ -1,25 +1,23 @@
import { ChannelAttributes, generateId, IdType } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
ChannelCreateMutationInput,
ChannelCreateMutationOutput,
} from '@/shared/mutations/channels/channel-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class ChannelCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ChannelCreateMutationInput>
{
async handleMutation(
input: ChannelCreateMutationInput
): Promise<ChannelCreateMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const space = await workspaceDatabase
+ const space = await workspace.database
.selectFrom('entries')
.selectAll()
.where('id', '=', input.spaceId)
@@ -40,7 +38,7 @@ export class ChannelCreateMutationHandler
parentId: input.spaceId,
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id,
attributes,
parentId: input.spaceId,
diff --git a/apps/desktop/src/main/mutations/channels/channel-delete.ts b/apps/desktop/src/main/mutations/channels/channel-delete.ts
index 1b4c51cf..786c6afd 100644
--- a/apps/desktop/src/main/mutations/channels/channel-delete.ts
+++ b/apps/desktop/src/main/mutations/channels/channel-delete.ts
@@ -1,17 +1,19 @@
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
ChannelDeleteMutationInput,
ChannelDeleteMutationOutput,
} from '@/shared/mutations/channels/channel-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class ChannelDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ChannelDeleteMutationInput>
{
async handleMutation(
input: ChannelDeleteMutationInput
): Promise<ChannelDeleteMutationOutput> {
- await entryService.deleteEntry(input.channelId, input.userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ await workspace.entries.deleteEntry(input.channelId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/channels/channel-update.ts b/apps/desktop/src/main/mutations/channels/channel-update.ts
index 11b51fbe..dea15e81 100644
--- a/apps/desktop/src/main/mutations/channels/channel-update.ts
+++ b/apps/desktop/src/main/mutations/channels/channel-update.ts
@@ -1,22 +1,24 @@
import { ChannelAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
ChannelUpdateMutationInput,
ChannelUpdateMutationOutput,
} from '@/shared/mutations/channels/channel-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class ChannelUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ChannelUpdateMutationInput>
{
async handleMutation(
input: ChannelUpdateMutationInput
): Promise<ChannelUpdateMutationOutput> {
- const result = await entryService.updateEntry<ChannelAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<ChannelAttributes>(
input.channelId,
- input.userId,
(attributes) => {
attributes.name = input.name;
attributes.avatar = input.avatar;
diff --git a/apps/desktop/src/main/mutations/chats/chat-create.ts b/apps/desktop/src/main/mutations/chats/chat-create.ts
index f979c458..d13d5e43 100644
--- a/apps/desktop/src/main/mutations/chats/chat-create.ts
+++ b/apps/desktop/src/main/mutations/chats/chat-create.ts
@@ -1,37 +1,35 @@
import { ChatAttributes, generateId, IdType } from '@colanode/core';
import { sql } from 'kysely';
-import { databaseService } from '@/main/data/database-service';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
ChatCreateMutationInput,
ChatCreateMutationOutput,
} from '@/shared/mutations/chats/chat-create';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
interface ChatRow {
id: string;
}
export class ChatCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ChatCreateMutationInput>
{
public async handleMutation(
input: ChatCreateMutationInput
): Promise<ChatCreateMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const query = sql<ChatRow>`
SELECT id
FROM entries
WHERE type = 'chat'
AND json_extract(attributes, '$.collaborators.${sql.raw(input.userId)}') is not null
- AND json_extract(attributes, '$.collaborators.${sql.raw(input.otherUserId)}') is not null
- `.compile(workspaceDatabase);
+ AND json_extract(attributes, '$.collaborators.${sql.raw(workspace.userId)}') is not null
+ `.compile(workspace.database);
- const existingChats = await workspaceDatabase.executeQuery(query);
+ const existingChats = await workspace.database.executeQuery(query);
const chat = existingChats.rows?.[0];
if (chat) {
return {
@@ -44,11 +42,11 @@ export class ChatCreateMutationHandler
type: 'chat',
collaborators: {
[input.userId]: 'admin',
- [input.otherUserId]: 'admin',
+ [workspace.userId]: 'admin',
},
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id,
attributes,
parentId: null,
diff --git a/apps/desktop/src/main/mutations/databases/database-create.ts b/apps/desktop/src/main/mutations/databases/database-create.ts
index 7ba5ef53..51867d51 100644
--- a/apps/desktop/src/main/mutations/databases/database-create.ts
+++ b/apps/desktop/src/main/mutations/databases/database-create.ts
@@ -5,19 +5,22 @@ import {
IdType,
} from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
DatabaseCreateMutationInput,
DatabaseCreateMutationOutput,
} from '@/shared/mutations/databases/database-create';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class DatabaseCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<DatabaseCreateMutationInput>
{
async handleMutation(
input: DatabaseCreateMutationInput
): Promise<DatabaseCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
const databaseId = generateId(IdType.Database);
const viewId = generateId(IdType.View);
const fieldId = generateId(IdType.Field);
@@ -45,7 +48,7 @@ export class DatabaseCreateMutationHandler
},
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id: databaseId,
attributes,
parentId: input.spaceId,
diff --git a/apps/desktop/src/main/mutations/databases/database-delete.ts b/apps/desktop/src/main/mutations/databases/database-delete.ts
index 855a8cf1..aef3f48d 100644
--- a/apps/desktop/src/main/mutations/databases/database-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/database-delete.ts
@@ -1,17 +1,19 @@
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
DatabaseDeleteMutationInput,
DatabaseDeleteMutationOutput,
} from '@/shared/mutations/databases/database-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class DatabaseDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<DatabaseDeleteMutationInput>
{
async handleMutation(
input: DatabaseDeleteMutationInput
): Promise<DatabaseDeleteMutationOutput> {
- await entryService.deleteEntry(input.databaseId, input.userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ await workspace.entries.deleteEntry(input.databaseId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/databases/database-update.ts b/apps/desktop/src/main/mutations/databases/database-update.ts
index 33521485..55f2d1f3 100644
--- a/apps/desktop/src/main/mutations/databases/database-update.ts
+++ b/apps/desktop/src/main/mutations/databases/database-update.ts
@@ -1,25 +1,25 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
DatabaseUpdateMutationInput,
DatabaseUpdateMutationOutput,
} from '@/shared/mutations/databases/database-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class DatabaseUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<DatabaseUpdateMutationInput>
{
async handleMutation(
input: DatabaseUpdateMutationInput
): Promise<DatabaseUpdateMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
attributes.name = input.name;
- attributes.avatar = input.avatar;
return attributes;
}
diff --git a/apps/desktop/src/main/mutations/databases/field-create.ts b/apps/desktop/src/main/mutations/databases/field-create.ts
index e0caf8c3..f34f91e1 100644
--- a/apps/desktop/src/main/mutations/databases/field-create.ts
+++ b/apps/desktop/src/main/mutations/databases/field-create.ts
@@ -7,22 +7,24 @@ import {
IdType,
} from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
FieldCreateMutationInput,
FieldCreateMutationOutput,
} from '@/shared/mutations/databases/field-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
-import { databaseService } from '@/main/data/database-service';
import { fetchEntry } from '@/main/utils';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FieldCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FieldCreateMutationInput>
{
async handleMutation(
input: FieldCreateMutationInput
): Promise<FieldCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
if (input.fieldType === 'relation') {
if (!input.relationDatabaseId) {
throw new MutationError(
@@ -31,12 +33,8 @@ export class FieldCreateMutationHandler
);
}
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
-
const relationDatabase = await fetchEntry(
- workspaceDatabase,
+ workspace.database,
input.relationDatabaseId
);
@@ -49,9 +47,8 @@ export class FieldCreateMutationHandler
}
const fieldId = generateId(IdType.Field);
- const result = await entryService.updateEntry(
+ const result = await workspace.entries.updateEntry(
input.databaseId,
- input.userId,
(attributes) => {
if (attributes.type !== 'database') {
throw new Error('Invalid node type');
diff --git a/apps/desktop/src/main/mutations/databases/field-delete.ts b/apps/desktop/src/main/mutations/databases/field-delete.ts
index d198855a..74c2e0c7 100644
--- a/apps/desktop/src/main/mutations/databases/field-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/field-delete.ts
@@ -1,30 +1,25 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
FieldDeleteMutationInput,
FieldDeleteMutationOutput,
} from '@/shared/mutations/databases/field-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FieldDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FieldDeleteMutationInput>
{
async handleMutation(
input: FieldDeleteMutationInput
): Promise<FieldDeleteMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
- if (!attributes.fields[input.fieldId]) {
- throw new MutationError(
- MutationErrorCode.FieldNotFound,
- 'The field you are trying to delete does not exist.'
- );
- }
-
delete attributes.fields[input.fieldId];
return attributes;
diff --git a/apps/desktop/src/main/mutations/databases/field-name-update.ts b/apps/desktop/src/main/mutations/databases/field-name-update.ts
index 434cf67f..05fd6fb7 100644
--- a/apps/desktop/src/main/mutations/databases/field-name-update.ts
+++ b/apps/desktop/src/main/mutations/databases/field-name-update.ts
@@ -1,22 +1,24 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
FieldNameUpdateMutationInput,
FieldNameUpdateMutationOutput,
} from '@/shared/mutations/databases/field-name-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FieldNameUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FieldNameUpdateMutationInput>
{
async handleMutation(
input: FieldNameUpdateMutationInput
): Promise<FieldNameUpdateMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
const field = attributes.fields[input.fieldId];
if (!field) {
diff --git a/apps/desktop/src/main/mutations/databases/select-option-create.ts b/apps/desktop/src/main/mutations/databases/select-option-create.ts
index f829eb62..f4622f7a 100644
--- a/apps/desktop/src/main/mutations/databases/select-option-create.ts
+++ b/apps/desktop/src/main/mutations/databases/select-option-create.ts
@@ -6,24 +6,26 @@ import {
IdType,
} from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
SelectOptionCreateMutationInput,
SelectOptionCreateMutationOutput,
} from '@/shared/mutations/databases/select-option-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class SelectOptionCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<SelectOptionCreateMutationInput>
{
async handleMutation(
input: SelectOptionCreateMutationInput
): Promise<SelectOptionCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
const id = generateId(IdType.SelectOption);
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
const field = attributes.fields[input.fieldId];
if (!field) {
diff --git a/apps/desktop/src/main/mutations/databases/select-option-delete.ts b/apps/desktop/src/main/mutations/databases/select-option-delete.ts
index 898523ee..6181a28d 100644
--- a/apps/desktop/src/main/mutations/databases/select-option-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/select-option-delete.ts
@@ -1,22 +1,24 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
SelectOptionDeleteMutationInput,
SelectOptionDeleteMutationOutput,
} from '@/shared/mutations/databases/select-option-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class SelectOptionDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<SelectOptionDeleteMutationInput>
{
async handleMutation(
input: SelectOptionDeleteMutationInput
): Promise<SelectOptionDeleteMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
const field = attributes.fields[input.fieldId];
if (!field) {
diff --git a/apps/desktop/src/main/mutations/databases/select-option-update.ts b/apps/desktop/src/main/mutations/databases/select-option-update.ts
index 9de23725..a2908cb2 100644
--- a/apps/desktop/src/main/mutations/databases/select-option-update.ts
+++ b/apps/desktop/src/main/mutations/databases/select-option-update.ts
@@ -1,22 +1,24 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
SelectOptionUpdateMutationInput,
SelectOptionUpdateMutationOutput,
} from '@/shared/mutations/databases/select-option-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class SelectOptionUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<SelectOptionUpdateMutationInput>
{
async handleMutation(
input: SelectOptionUpdateMutationInput
): Promise<SelectOptionUpdateMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
const field = attributes.fields[input.fieldId];
if (!field) {
diff --git a/apps/desktop/src/main/mutations/databases/view-create.ts b/apps/desktop/src/main/mutations/databases/view-create.ts
index 94136047..9aed80a6 100644
--- a/apps/desktop/src/main/mutations/databases/view-create.ts
+++ b/apps/desktop/src/main/mutations/databases/view-create.ts
@@ -6,24 +6,26 @@ import {
IdType,
} from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
ViewCreateMutationInput,
ViewCreateMutationOutput,
} from '@/shared/mutations/databases/view-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class ViewCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ViewCreateMutationInput>
{
async handleMutation(
input: ViewCreateMutationInput
): Promise<ViewCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
const id = generateId(IdType.View);
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
const maxIndex = Object.values(attributes.views)
.map((view) => view.index)
diff --git a/apps/desktop/src/main/mutations/databases/view-delete.ts b/apps/desktop/src/main/mutations/databases/view-delete.ts
index 8de4595d..4084a61d 100644
--- a/apps/desktop/src/main/mutations/databases/view-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/view-delete.ts
@@ -1,22 +1,24 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
ViewDeleteMutationInput,
ViewDeleteMutationOutput,
} from '@/shared/mutations/databases/view-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class ViewDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ViewDeleteMutationInput>
{
async handleMutation(
input: ViewDeleteMutationInput
): Promise<ViewDeleteMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
if (!attributes.views[input.viewId]) {
throw new MutationError(
diff --git a/apps/desktop/src/main/mutations/databases/view-name-update.ts b/apps/desktop/src/main/mutations/databases/view-name-update.ts
index e7c41bbb..6a4076be 100644
--- a/apps/desktop/src/main/mutations/databases/view-name-update.ts
+++ b/apps/desktop/src/main/mutations/databases/view-name-update.ts
@@ -1,22 +1,24 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
ViewNameUpdateMutationInput,
ViewNameUpdateMutationOutput,
} from '@/shared/mutations/databases/view-name-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class ViewNameUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ViewNameUpdateMutationInput>
{
async handleMutation(
input: ViewNameUpdateMutationInput
): Promise<ViewNameUpdateMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
const view = attributes.views[input.viewId];
if (!view) {
diff --git a/apps/desktop/src/main/mutations/databases/view-update.ts b/apps/desktop/src/main/mutations/databases/view-update.ts
index c56840df..37b7a0d5 100644
--- a/apps/desktop/src/main/mutations/databases/view-update.ts
+++ b/apps/desktop/src/main/mutations/databases/view-update.ts
@@ -1,22 +1,24 @@
import { DatabaseAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
ViewUpdateMutationInput,
ViewUpdateMutationOutput,
} from '@/shared/mutations/databases/view-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class ViewUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<ViewUpdateMutationInput>
{
async handleMutation(
input: ViewUpdateMutationInput
): Promise<ViewUpdateMutationOutput> {
- const result = await entryService.updateEntry<DatabaseAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<DatabaseAttributes>(
input.databaseId,
- input.userId,
(attributes) => {
if (!attributes.views[input.view.id]) {
throw new MutationError(
diff --git a/apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts b/apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts
index d712d941..f8b3e95c 100644
--- a/apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts
+++ b/apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts
@@ -1,22 +1,24 @@
import { set } from 'lodash-es';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
EntryCollaboratorCreateMutationInput,
EntryCollaboratorCreateMutationOutput,
} from '@/shared/mutations/entries/entry-collaborator-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class EntryCollaboratorCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<EntryCollaboratorCreateMutationInput>
{
async handleMutation(
input: EntryCollaboratorCreateMutationInput
): Promise<EntryCollaboratorCreateMutationOutput> {
- const result = await entryService.updateEntry(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry(
input.entryId,
- input.userId,
(attributes) => {
for (const collaboratorId of input.collaboratorIds) {
set(attributes, `collaborators.${collaboratorId}`, input.role);
diff --git a/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts b/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts
index 1f4ffa35..c40a110b 100644
--- a/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts
+++ b/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts
@@ -1,22 +1,24 @@
import { unset } from 'lodash-es';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
EntryCollaboratorDeleteMutationInput,
EntryCollaboratorDeleteMutationOutput,
} from '@/shared/mutations/entries/entry-collaborator-delete';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class EntryCollaboratorDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<EntryCollaboratorDeleteMutationInput>
{
async handleMutation(
input: EntryCollaboratorDeleteMutationInput
): Promise<EntryCollaboratorDeleteMutationOutput> {
- const result = await entryService.updateEntry(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry(
input.entryId,
- input.userId,
(attributes) => {
unset(attributes, `collaborators.${input.collaboratorId}`);
return attributes;
diff --git a/apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts b/apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts
index 1e3e29b5..0897ceca 100644
--- a/apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts
+++ b/apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts
@@ -1,22 +1,24 @@
import { set } from 'lodash-es';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
EntryCollaboratorUpdateMutationInput,
EntryCollaboratorUpdateMutationOutput,
} from '@/shared/mutations/entries/entry-collaborator-update';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class EntryCollaboratorUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<EntryCollaboratorUpdateMutationInput>
{
async handleMutation(
input: EntryCollaboratorUpdateMutationInput
): Promise<EntryCollaboratorUpdateMutationOutput> {
- const result = await entryService.updateEntry(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry(
input.entryId,
- input.userId,
(attributes) => {
set(attributes, `collaborators.${input.collaboratorId}`, input.role);
return attributes;
diff --git a/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts b/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts
index cf7204de..190b0673 100644
--- a/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts
+++ b/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts
@@ -1,29 +1,24 @@
import { MarkEntryOpenedMutation, generateId, IdType } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
EntryMarkOpenedMutationInput,
EntryMarkOpenedMutationOutput,
} from '@/shared/mutations/entries/entry-mark-opened';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapEntryInteraction } from '@/main/utils';
+import { fetchEntry, mapEntryInteraction } from '@/main/utils';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class EntryMarkOpenedMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<EntryMarkOpenedMutationInput>
{
async handleMutation(
input: EntryMarkOpenedMutationInput
): Promise<EntryMarkOpenedMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const entry = await workspaceDatabase
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', input.entryId)
- .executeTakeFirst();
+ const entry = await fetchEntry(workspace.database, input.entryId);
if (!entry) {
return {
@@ -31,11 +26,11 @@ export class EntryMarkOpenedMutationHandler
};
}
- const existingInteraction = await workspaceDatabase
+ const existingInteraction = await workspace.database
.selectFrom('entry_interactions')
.selectAll()
.where('entry_id', '=', input.entryId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.executeTakeFirst();
if (existingInteraction) {
@@ -55,7 +50,7 @@ export class EntryMarkOpenedMutationHandler
? existingInteraction.first_opened_at
: lastOpenedAt;
- const { createdInteraction, createdMutation } = await workspaceDatabase
+ const { createdInteraction, createdMutation } = await workspace.database
.transaction()
.execute(async (trx) => {
const createdInteraction = await trx
@@ -63,7 +58,7 @@ export class EntryMarkOpenedMutationHandler
.returningAll()
.values({
entry_id: input.entryId,
- collaborator_id: input.userId,
+ collaborator_id: workspace.userId,
last_opened_at: lastOpenedAt,
first_opened_at: firstOpenedAt,
version: 0n,
@@ -87,7 +82,7 @@ export class EntryMarkOpenedMutationHandler
type: 'mark_entry_opened',
data: {
entryId: input.entryId,
- collaboratorId: input.userId,
+ collaboratorId: workspace.userId,
openedAt: new Date().toISOString(),
},
};
@@ -114,14 +109,12 @@ export class EntryMarkOpenedMutationHandler
throw new Error('Failed to create entry interaction');
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'entry_interaction_updated',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
entryInteraction: mapEntryInteraction(createdInteraction),
});
diff --git a/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts b/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts
index a9dba475..ed7fd1c8 100644
--- a/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts
+++ b/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts
@@ -1,29 +1,24 @@
import { MarkEntrySeenMutation, generateId, IdType } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
EntryMarkSeenMutationInput,
EntryMarkSeenMutationOutput,
} from '@/shared/mutations/entries/entry-mark-seen';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapEntryInteraction } from '@/main/utils';
+import { fetchEntry, mapEntryInteraction } from '@/main/utils';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class EntryMarkSeenMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<EntryMarkSeenMutationInput>
{
async handleMutation(
input: EntryMarkSeenMutationInput
): Promise<EntryMarkSeenMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const entry = await workspaceDatabase
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', input.entryId)
- .executeTakeFirst();
+ const entry = await fetchEntry(workspace.database, input.entryId);
if (!entry) {
return {
@@ -31,11 +26,11 @@ export class EntryMarkSeenMutationHandler
};
}
- const existingInteraction = await workspaceDatabase
+ const existingInteraction = await workspace.database
.selectFrom('entry_interactions')
.selectAll()
.where('entry_id', '=', input.entryId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.executeTakeFirst();
if (existingInteraction) {
@@ -55,7 +50,7 @@ export class EntryMarkSeenMutationHandler
? existingInteraction.first_seen_at
: lastSeenAt;
- const { createdInteraction, createdMutation } = await workspaceDatabase
+ const { createdInteraction, createdMutation } = await workspace.database
.transaction()
.execute(async (trx) => {
const createdInteraction = await trx
@@ -63,7 +58,7 @@ export class EntryMarkSeenMutationHandler
.returningAll()
.values({
entry_id: input.entryId,
- collaborator_id: input.userId,
+ collaborator_id: workspace.userId,
last_seen_at: lastSeenAt,
first_seen_at: firstSeenAt,
version: 0n,
@@ -87,7 +82,7 @@ export class EntryMarkSeenMutationHandler
type: 'mark_entry_seen',
data: {
entryId: input.entryId,
- collaboratorId: input.userId,
+ collaboratorId: workspace.userId,
seenAt: new Date().toISOString(),
},
};
@@ -114,14 +109,12 @@ export class EntryMarkSeenMutationHandler
throw new Error('Failed to create entry interaction');
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'entry_interaction_updated',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
entryInteraction: mapEntryInteraction(createdInteraction),
});
diff --git a/apps/desktop/src/main/mutations/files/file-create.ts b/apps/desktop/src/main/mutations/files/file-create.ts
index 54a98a39..dcf4aed3 100644
--- a/apps/desktop/src/main/mutations/files/file-create.ts
+++ b/apps/desktop/src/main/mutations/files/file-create.ts
@@ -6,32 +6,33 @@ import {
IdType,
} from '@colanode/core';
-import { fileService } from '@/main/services/file-service';
import { MutationHandler } from '@/main/types';
import {
FileCreateMutationInput,
FileCreateMutationOutput,
} from '@/shared/mutations/files/file-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
-import { databaseService } from '@/main/data/database-service';
import { eventBus } from '@/shared/lib/event-bus';
import {
fetchEntry,
fetchUser,
fetchUserStorageUsed,
+ getFileMetadata,
mapEntry,
mapFile,
} from '@/main/utils';
import { formatBytes } from '@/shared/lib/files';
import { DownloadStatus, UploadStatus } from '@/shared/types/files';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FileCreateMutationInput>
{
async handleMutation(
input: FileCreateMutationInput
): Promise<FileCreateMutationOutput> {
- const metadata = fileService.getFileMetadata(input.filePath);
+ const metadata = getFileMetadata(input.filePath);
if (!metadata) {
throw new MutationError(
MutationErrorCode.FileInvalid,
@@ -39,11 +40,10 @@ export class FileCreateMutationHandler
);
}
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const user = await fetchUser(workspace.database, workspace.userId);
- const user = await fetchUser(workspaceDatabase, input.userId);
if (!user) {
throw new MutationError(
MutationErrorCode.UserNotFound,
@@ -60,8 +60,8 @@ export class FileCreateMutationHandler
}
const storageUsed = await fetchUserStorageUsed(
- workspaceDatabase,
- input.userId
+ workspace.database,
+ workspace.userId
);
if (storageUsed + BigInt(metadata.size) > user.storage_limit) {
@@ -76,7 +76,7 @@ export class FileCreateMutationHandler
);
}
- const entry = await fetchEntry(workspaceDatabase, input.entryId);
+ const entry = await fetchEntry(workspace.database, input.entryId);
if (!entry) {
throw new MutationError(
MutationErrorCode.EntryNotFound,
@@ -84,7 +84,7 @@ export class FileCreateMutationHandler
);
}
- const root = await fetchEntry(workspaceDatabase, input.rootId);
+ const root = await fetchEntry(workspace.database, input.rootId);
if (!root) {
throw new MutationError(
MutationErrorCode.RootNotFound,
@@ -96,8 +96,8 @@ export class FileCreateMutationHandler
if (
!canCreateFile({
user: {
- userId: input.userId,
- role: user.role,
+ userId: workspace.userId,
+ role: workspace.role,
},
root: mapEntry(root),
entry: mapEntry(entry),
@@ -113,11 +113,10 @@ export class FileCreateMutationHandler
);
}
- fileService.copyFileToWorkspace(
+ workspace.files.copyFileToWorkspace(
input.filePath,
fileId,
- metadata.extension,
- input.userId
+ metadata.extension
);
const mutationData: CreateFileMutationData = {
@@ -134,7 +133,7 @@ export class FileCreateMutationHandler
createdAt: new Date().toISOString(),
};
- const createdFile = await workspaceDatabase
+ const createdFile = await workspace.database
.transaction()
.execute(async (tx) => {
const createdFile = await tx
@@ -152,7 +151,7 @@ export class FileCreateMutationHandler
size: metadata.size,
extension: metadata.extension,
created_at: new Date().toISOString(),
- created_by: input.userId,
+ created_by: workspace.userId,
status: FileStatus.Pending,
version: 0n,
})
@@ -196,18 +195,17 @@ export class FileCreateMutationHandler
eventBus.publish({
type: 'file_created',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
file: mapFile(createdFile),
});
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'file_state_created',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fileState: {
fileId: fileId,
downloadProgress: 100,
diff --git a/apps/desktop/src/main/mutations/files/file-delete.ts b/apps/desktop/src/main/mutations/files/file-delete.ts
index 5ed57f93..8d5d3df9 100644
--- a/apps/desktop/src/main/mutations/files/file-delete.ts
+++ b/apps/desktop/src/main/mutations/files/file-delete.ts
@@ -5,27 +5,26 @@ import {
IdType,
} from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
FileDeleteMutationInput,
FileDeleteMutationOutput,
} from '@/shared/mutations/files/file-delete';
import { eventBus } from '@/shared/lib/event-bus';
-import { fetchEntry, fetchUser, mapEntry, mapFile } from '@/main/utils';
+import { fetchEntry, mapEntry, mapFile } from '@/main/utils';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FileDeleteMutationInput>
{
async handleMutation(
input: FileDeleteMutationInput
): Promise<FileDeleteMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const file = await workspaceDatabase
+ const file = await workspace.database
.selectFrom('files')
.selectAll()
.where('id', '=', input.fileId)
@@ -38,15 +37,7 @@ export class FileDeleteMutationHandler
);
}
- const user = await fetchUser(workspaceDatabase, input.userId);
- if (!user) {
- throw new MutationError(
- MutationErrorCode.UserNotFound,
- 'There was an error while fetching the user. Please make sure you are logged in.'
- );
- }
-
- const entry = await fetchEntry(workspaceDatabase, file.root_id);
+ const entry = await fetchEntry(workspace.database, file.root_id);
if (!entry) {
throw new MutationError(
MutationErrorCode.EntryNotFound,
@@ -54,7 +45,7 @@ export class FileDeleteMutationHandler
);
}
- const root = await fetchEntry(workspaceDatabase, entry.root_id);
+ const root = await fetchEntry(workspace.database, entry.root_id);
if (!root) {
throw new MutationError(
MutationErrorCode.RootNotFound,
@@ -65,8 +56,8 @@ export class FileDeleteMutationHandler
if (
!canDeleteFile({
user: {
- userId: input.userId,
- role: user.role,
+ userId: workspace.userId,
+ role: workspace.role,
},
root: mapEntry(root),
entry: mapEntry(entry),
@@ -90,7 +81,7 @@ export class FileDeleteMutationHandler
deletedAt,
};
- await workspaceDatabase.transaction().execute(async (tx) => {
+ await workspace.database.transaction().execute(async (tx) => {
await tx
.updateTable('files')
.set({
@@ -113,14 +104,12 @@ export class FileDeleteMutationHandler
eventBus.publish({
type: 'file_deleted',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
file: mapFile(file),
});
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/files/file-download.ts b/apps/desktop/src/main/mutations/files/file-download.ts
index 5f486c26..5511d71b 100644
--- a/apps/desktop/src/main/mutations/files/file-download.ts
+++ b/apps/desktop/src/main/mutations/files/file-download.ts
@@ -1,6 +1,5 @@
import { FileStatus } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import { mapFileState } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
@@ -10,18 +9,18 @@ import {
FileDownloadMutationOutput,
} from '@/shared/mutations/files/file-download';
import { DownloadStatus, UploadStatus } from '@/shared/types/files';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileDownloadMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FileDownloadMutationInput>
{
async handleMutation(
input: FileDownloadMutationInput
): Promise<FileDownloadMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const file = await workspaceDatabase
+ const file = await workspace.database
.selectFrom('files')
.selectAll()
.where('id', '=', input.fileId)
@@ -41,7 +40,7 @@ export class FileDownloadMutationHandler
);
}
- const existingFileState = await workspaceDatabase
+ const existingFileState = await workspace.database
.selectFrom('file_states')
.selectAll()
.where('file_id', '=', input.fileId)
@@ -56,7 +55,7 @@ export class FileDownloadMutationHandler
};
}
- const fileState = await workspaceDatabase
+ const fileState = await workspace.database
.insertInto('file_states')
.returningAll()
.values({
@@ -85,7 +84,8 @@ export class FileDownloadMutationHandler
eventBus.publish({
type: 'file_state_created',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fileState: mapFileState(fileState),
});
diff --git a/apps/desktop/src/main/mutations/files/file-mark-opened.ts b/apps/desktop/src/main/mutations/files/file-mark-opened.ts
index 2245afa9..f3f29e8d 100644
--- a/apps/desktop/src/main/mutations/files/file-mark-opened.ts
+++ b/apps/desktop/src/main/mutations/files/file-mark-opened.ts
@@ -1,6 +1,5 @@
import { MarkFileOpenedMutation, generateId, IdType } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
FileMarkOpenedMutationInput,
@@ -8,18 +7,18 @@ import {
} from '@/shared/mutations/files/file-mark-opened';
import { eventBus } from '@/shared/lib/event-bus';
import { mapFileInteraction } from '@/main/utils';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileMarkOpenedMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FileMarkOpenedMutationInput>
{
async handleMutation(
input: FileMarkOpenedMutationInput
): Promise<FileMarkOpenedMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const file = await workspaceDatabase
+ const file = await workspace.database
.selectFrom('files')
.selectAll()
.where('id', '=', input.fileId)
@@ -31,11 +30,11 @@ export class FileMarkOpenedMutationHandler
};
}
- const existingInteraction = await workspaceDatabase
+ const existingInteraction = await workspace.database
.selectFrom('file_interactions')
.selectAll()
.where('file_id', '=', input.fileId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.executeTakeFirst();
if (existingInteraction) {
@@ -55,7 +54,7 @@ export class FileMarkOpenedMutationHandler
? existingInteraction.first_opened_at
: lastOpenedAt;
- const { createdInteraction, createdMutation } = await workspaceDatabase
+ const { createdInteraction, createdMutation } = await workspace.database
.transaction()
.execute(async (trx) => {
const createdInteraction = await trx
@@ -63,7 +62,7 @@ export class FileMarkOpenedMutationHandler
.returningAll()
.values({
file_id: input.fileId,
- collaborator_id: input.userId,
+ collaborator_id: workspace.userId,
last_opened_at: lastOpenedAt,
first_opened_at: firstOpenedAt,
version: 0n,
@@ -87,7 +86,7 @@ export class FileMarkOpenedMutationHandler
type: 'mark_file_opened',
data: {
fileId: input.fileId,
- collaboratorId: input.userId,
+ collaboratorId: workspace.userId,
openedAt: new Date().toISOString(),
},
};
@@ -114,14 +113,12 @@ export class FileMarkOpenedMutationHandler
throw new Error('Failed to create file interaction');
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'file_interaction_updated',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fileInteraction: mapFileInteraction(createdInteraction),
});
diff --git a/apps/desktop/src/main/mutations/files/file-mark-seen.ts b/apps/desktop/src/main/mutations/files/file-mark-seen.ts
index 2205f03a..55277a7d 100644
--- a/apps/desktop/src/main/mutations/files/file-mark-seen.ts
+++ b/apps/desktop/src/main/mutations/files/file-mark-seen.ts
@@ -1,6 +1,5 @@
import { MarkFileSeenMutation, generateId, IdType } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
FileMarkSeenMutationInput,
@@ -8,18 +7,18 @@ import {
} from '@/shared/mutations/files/file-mark-seen';
import { eventBus } from '@/shared/lib/event-bus';
import { mapFileInteraction } from '@/main/utils';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileMarkSeenMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FileMarkSeenMutationInput>
{
async handleMutation(
input: FileMarkSeenMutationInput
): Promise<FileMarkSeenMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const file = await workspaceDatabase
+ const file = await workspace.database
.selectFrom('files')
.selectAll()
.where('id', '=', input.fileId)
@@ -31,11 +30,11 @@ export class FileMarkSeenMutationHandler
};
}
- const existingInteraction = await workspaceDatabase
+ const existingInteraction = await workspace.database
.selectFrom('file_interactions')
.selectAll()
.where('file_id', '=', input.fileId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.executeTakeFirst();
if (existingInteraction) {
@@ -55,7 +54,7 @@ export class FileMarkSeenMutationHandler
? existingInteraction.first_seen_at
: lastSeenAt;
- const { createdInteraction, createdMutation } = await workspaceDatabase
+ const { createdInteraction, createdMutation } = await workspace.database
.transaction()
.execute(async (trx) => {
const createdInteraction = await trx
@@ -63,7 +62,7 @@ export class FileMarkSeenMutationHandler
.returningAll()
.values({
file_id: input.fileId,
- collaborator_id: input.userId,
+ collaborator_id: workspace.userId,
last_seen_at: lastSeenAt,
first_seen_at: firstSeenAt,
version: 0n,
@@ -87,7 +86,7 @@ export class FileMarkSeenMutationHandler
type: 'mark_file_seen',
data: {
fileId: input.fileId,
- collaboratorId: input.userId,
+ collaboratorId: workspace.userId,
seenAt: new Date().toISOString(),
},
};
@@ -114,14 +113,12 @@ export class FileMarkSeenMutationHandler
throw new Error('Failed to create file interaction');
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'file_interaction_updated',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fileInteraction: mapFileInteraction(createdInteraction),
});
diff --git a/apps/desktop/src/main/mutations/files/file-save-temp.ts b/apps/desktop/src/main/mutations/files/file-save-temp.ts
index 2aaaaba7..dcd8817b 100644
--- a/apps/desktop/src/main/mutations/files/file-save-temp.ts
+++ b/apps/desktop/src/main/mutations/files/file-save-temp.ts
@@ -7,14 +7,19 @@ import {
FileSaveTempMutationOutput,
} from '@/shared/mutations/files/file-save-temp';
import { getWorkspaceTempFilesDirectoryPath } from '@/main/utils';
-
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileSaveTempMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FileSaveTempMutationInput>
{
async handleMutation(
input: FileSaveTempMutationInput
): Promise<FileSaveTempMutationOutput> {
- const directoryPath = getWorkspaceTempFilesDirectoryPath(input.userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ const directoryPath = getWorkspaceTempFilesDirectoryPath(
+ workspace.accountId,
+ workspace.id
+ );
const fileName = this.generateUniqueName(directoryPath, input.name);
const filePath = path.join(directoryPath, fileName);
diff --git a/apps/desktop/src/main/mutations/folders/folder-create.ts b/apps/desktop/src/main/mutations/folders/folder-create.ts
index 38a37d6e..44d719c4 100644
--- a/apps/desktop/src/main/mutations/folders/folder-create.ts
+++ b/apps/desktop/src/main/mutations/folders/folder-create.ts
@@ -1,18 +1,21 @@
import { FolderAttributes, generateId, IdType } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
FolderCreateMutationInput,
FolderCreateMutationOutput,
} from '@/shared/mutations/folders/folder-create';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FolderCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FolderCreateMutationInput>
{
async handleMutation(
input: FolderCreateMutationInput
): Promise<FolderCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
const id = generateId(IdType.Folder);
const attributes: FolderAttributes = {
type: 'folder',
@@ -21,7 +24,7 @@ export class FolderCreateMutationHandler
avatar: input.avatar,
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id,
attributes,
parentId: input.parentId,
diff --git a/apps/desktop/src/main/mutations/folders/folder-delete.ts b/apps/desktop/src/main/mutations/folders/folder-delete.ts
index 830629f9..bce3b759 100644
--- a/apps/desktop/src/main/mutations/folders/folder-delete.ts
+++ b/apps/desktop/src/main/mutations/folders/folder-delete.ts
@@ -1,17 +1,20 @@
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
FolderDeleteMutationInput,
FolderDeleteMutationOutput,
} from '@/shared/mutations/folders/folder-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FolderDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FolderDeleteMutationInput>
{
async handleMutation(
input: FolderDeleteMutationInput
): Promise<FolderDeleteMutationOutput> {
- await entryService.deleteEntry(input.folderId, input.userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ await workspace.entries.deleteEntry(input.folderId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/folders/folder-update.ts b/apps/desktop/src/main/mutations/folders/folder-update.ts
index a9f0555e..bab49a49 100644
--- a/apps/desktop/src/main/mutations/folders/folder-update.ts
+++ b/apps/desktop/src/main/mutations/folders/folder-update.ts
@@ -1,22 +1,24 @@
import { FolderAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
FolderUpdateMutationInput,
FolderUpdateMutationOutput,
} from '@/shared/mutations/folders/folder-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FolderUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<FolderUpdateMutationInput>
{
async handleMutation(
input: FolderUpdateMutationInput
): Promise<FolderUpdateMutationOutput> {
- const result = await entryService.updateEntry<FolderAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<FolderAttributes>(
input.folderId,
- input.userId,
(attributes) => {
attributes.name = input.name;
attributes.avatar = input.avatar;
diff --git a/apps/desktop/src/main/mutations/messages/message-create.ts b/apps/desktop/src/main/mutations/messages/message-create.ts
index f3d554f5..7ebc9c39 100644
--- a/apps/desktop/src/main/mutations/messages/message-create.ts
+++ b/apps/desktop/src/main/mutations/messages/message-create.ts
@@ -11,7 +11,6 @@ import {
MessageType,
} from '@colanode/core';
-import { fileService } from '@/main/services/file-service';
import { MutationHandler } from '@/main/types';
import { mapContentsToBlocks } from '@/shared/lib/editor';
import {
@@ -23,13 +22,13 @@ import {
CreateFile,
CreateFileState,
CreateMutation,
-} from '@/main/data/workspace/schema';
-import { databaseService } from '@/main/data/database-service';
+} from '@/main/databases/workspace';
import { eventBus } from '@/shared/lib/event-bus';
import {
fetchEntry,
fetchUser,
fetchUserStorageUsed,
+ getFileMetadata,
mapEntry,
mapFile,
mapFileState,
@@ -37,18 +36,18 @@ import {
} from '@/main/utils';
import { formatBytes } from '@/shared/lib/files';
import { DownloadStatus, UploadStatus } from '@/shared/types/files';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class MessageCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<MessageCreateMutationInput>
{
async handleMutation(
input: MessageCreateMutationInput
): Promise<MessageCreateMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const user = await fetchUser(workspaceDatabase, input.userId);
+ const user = await fetchUser(workspace.database, workspace.userId);
if (!user) {
throw new MutationError(
MutationErrorCode.UserNotFound,
@@ -56,7 +55,7 @@ export class MessageCreateMutationHandler
);
}
- const entry = await fetchEntry(workspaceDatabase, input.conversationId);
+ const entry = await fetchEntry(workspace.database, input.conversationId);
if (!entry) {
throw new MutationError(
MutationErrorCode.EntryNotFound,
@@ -64,7 +63,7 @@ export class MessageCreateMutationHandler
);
}
- const root = await fetchEntry(workspaceDatabase, input.rootId);
+ const root = await fetchEntry(workspace.database, input.rootId);
if (!root) {
throw new MutationError(
MutationErrorCode.RootNotFound,
@@ -75,7 +74,7 @@ export class MessageCreateMutationHandler
if (
!canCreateMessage({
user: {
- userId: input.userId,
+ userId: workspace.userId,
role: user.role,
},
root: mapEntry(root),
@@ -101,7 +100,7 @@ export class MessageCreateMutationHandler
for (const block of blocks) {
if (block.type === EditorNodeTypes.FilePlaceholder) {
const path = block.attrs?.path;
- const metadata = fileService.getFileMetadata(path);
+ const metadata = getFileMetadata(path);
if (!metadata) {
throw new MutationError(
MutationErrorCode.FileInvalid,
@@ -122,12 +121,7 @@ export class MessageCreateMutationHandler
block.type = 'file';
block.attrs = null;
- fileService.copyFileToWorkspace(
- path,
- fileId,
- metadata.extension,
- input.userId
- );
+ workspace.files.copyFileToWorkspace(path, fileId, metadata.extension);
files.push({
id: fileId,
@@ -142,7 +136,7 @@ export class MessageCreateMutationHandler
extension: metadata.extension,
size: metadata.size,
created_at: createdAt,
- created_by: input.userId,
+ created_by: workspace.userId,
version: 0n,
});
@@ -183,8 +177,8 @@ export class MessageCreateMutationHandler
if (files.length > 0) {
const storageUsed = await fetchUserStorageUsed(
- workspaceDatabase,
- input.userId
+ workspace.database,
+ workspace.userId
);
const fileSizeSum = BigInt(
@@ -193,7 +187,7 @@ export class MessageCreateMutationHandler
if (storageUsed + fileSizeSum > user.storage_limit) {
for (const file of files) {
- fileService.deleteFile(input.userId, file.id, file.extension);
+ workspace.files.deleteFile(file.id, file.extension);
}
throw new MutationError(
@@ -223,7 +217,7 @@ export class MessageCreateMutationHandler
};
const { createdMessage, createdFiles, createdFileStates } =
- await workspaceDatabase.transaction().execute(async (tx) => {
+ await workspace.database.transaction().execute(async (tx) => {
const createdMessage = await tx
.insertInto('messages')
.returningAll()
@@ -234,7 +228,7 @@ export class MessageCreateMutationHandler
root_id: input.rootId,
attributes: JSON.stringify(messageAttributes),
created_at: createdAt,
- created_by: input.userId,
+ created_by: workspace.userId,
version: 0n,
})
.executeTakeFirst();
@@ -301,7 +295,8 @@ export class MessageCreateMutationHandler
if (createdMessage) {
eventBus.publish({
type: 'message_created',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
message: mapMessage(createdMessage),
});
}
@@ -310,7 +305,8 @@ export class MessageCreateMutationHandler
for (const file of createdFiles) {
eventBus.publish({
type: 'file_created',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
file: mapFile(file),
});
}
@@ -320,16 +316,14 @@ export class MessageCreateMutationHandler
for (const fileState of createdFileStates) {
eventBus.publish({
type: 'file_state_created',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fileState: mapFileState(fileState),
});
}
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
return {
id: messageId,
diff --git a/apps/desktop/src/main/mutations/messages/message-delete.ts b/apps/desktop/src/main/mutations/messages/message-delete.ts
index c84c2a34..f9f16130 100644
--- a/apps/desktop/src/main/mutations/messages/message-delete.ts
+++ b/apps/desktop/src/main/mutations/messages/message-delete.ts
@@ -5,27 +5,25 @@ import {
IdType,
} from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
MessageDeleteMutationInput,
MessageDeleteMutationOutput,
} from '@/shared/mutations/messages/message-delete';
import { eventBus } from '@/shared/lib/event-bus';
-import { fetchEntry, fetchUser, mapEntry, mapMessage } from '@/main/utils';
+import { fetchEntry, mapEntry, mapMessage } from '@/main/utils';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
-
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class MessageDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<MessageDeleteMutationInput>
{
async handleMutation(
input: MessageDeleteMutationInput
): Promise<MessageDeleteMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const message = await workspaceDatabase
+ const message = await workspace.database
.selectFrom('messages')
.selectAll()
.where('id', '=', input.messageId)
@@ -37,15 +35,7 @@ export class MessageDeleteMutationHandler
};
}
- const user = await fetchUser(workspaceDatabase, input.userId);
- if (!user) {
- throw new MutationError(
- MutationErrorCode.UserNotFound,
- 'There was an error while fetching the user. Please make sure you are logged in.'
- );
- }
-
- const entry = await fetchEntry(workspaceDatabase, message.entry_id);
+ const entry = await fetchEntry(workspace.database, message.entry_id);
if (!entry) {
throw new MutationError(
MutationErrorCode.EntryNotFound,
@@ -53,7 +43,7 @@ export class MessageDeleteMutationHandler
);
}
- const root = await fetchEntry(workspaceDatabase, message.root_id);
+ const root = await fetchEntry(workspace.database, message.root_id);
if (!root) {
throw new MutationError(
MutationErrorCode.RootNotFound,
@@ -64,8 +54,8 @@ export class MessageDeleteMutationHandler
if (
!canDeleteMessage({
user: {
- userId: input.userId,
- role: user.role,
+ userId: workspace.userId,
+ role: workspace.role,
},
root: mapEntry(root),
entry: mapEntry(entry),
@@ -88,7 +78,7 @@ export class MessageDeleteMutationHandler
deletedAt,
};
- await workspaceDatabase.transaction().execute(async (tx) => {
+ await workspace.database.transaction().execute(async (tx) => {
await tx
.updateTable('messages')
.set({
@@ -111,14 +101,12 @@ export class MessageDeleteMutationHandler
eventBus.publish({
type: 'message_deleted',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
message: mapMessage(message),
});
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/messages/message-mark-seen.ts b/apps/desktop/src/main/mutations/messages/message-mark-seen.ts
index 58d3369a..c5589952 100644
--- a/apps/desktop/src/main/mutations/messages/message-mark-seen.ts
+++ b/apps/desktop/src/main/mutations/messages/message-mark-seen.ts
@@ -1,6 +1,5 @@
import { MarkMessageSeenMutation, generateId, IdType } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
MessageMarkSeenMutationInput,
@@ -8,18 +7,18 @@ import {
} from '@/shared/mutations/messages/message-mark-seen';
import { eventBus } from '@/shared/lib/event-bus';
import { mapMessageInteraction } from '@/main/utils';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class MessageMarkSeenMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<MessageMarkSeenMutationInput>
{
async handleMutation(
input: MessageMarkSeenMutationInput
): Promise<MessageMarkSeenMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const message = await workspaceDatabase
+ const message = await workspace.database
.selectFrom('messages')
.selectAll()
.where('id', '=', input.messageId)
@@ -31,11 +30,11 @@ export class MessageMarkSeenMutationHandler
};
}
- const existingInteraction = await workspaceDatabase
+ const existingInteraction = await workspace.database
.selectFrom('message_interactions')
.selectAll()
.where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.executeTakeFirst();
if (existingInteraction) {
@@ -55,7 +54,7 @@ export class MessageMarkSeenMutationHandler
? existingInteraction.first_seen_at
: lastSeenAt;
- const { createdInteraction, createdMutation } = await workspaceDatabase
+ const { createdInteraction, createdMutation } = await workspace.database
.transaction()
.execute(async (trx) => {
const createdInteraction = await trx
@@ -63,7 +62,7 @@ export class MessageMarkSeenMutationHandler
.returningAll()
.values({
message_id: input.messageId,
- collaborator_id: input.userId,
+ collaborator_id: workspace.userId,
first_seen_at: firstSeenAt,
last_seen_at: lastSeenAt,
version: 0n,
@@ -87,7 +86,7 @@ export class MessageMarkSeenMutationHandler
type: 'mark_message_seen',
data: {
messageId: input.messageId,
- collaboratorId: input.userId,
+ collaboratorId: workspace.userId,
seenAt: new Date().toISOString(),
},
};
@@ -114,14 +113,12 @@ export class MessageMarkSeenMutationHandler
throw new Error('Failed to create message interaction');
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'message_interaction_updated',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
messageInteraction: mapMessageInteraction(createdInteraction),
});
diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts b/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
index c412bfa9..bad741af 100644
--- a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
+++ b/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
@@ -5,32 +5,26 @@ import {
IdType,
} from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
MessageReactionCreateMutationInput,
MessageReactionCreateMutationOutput,
} from '@/shared/mutations/messages/message-reaction-create';
import { eventBus } from '@/shared/lib/event-bus';
-import {
- fetchEntry,
- fetchUser,
- mapEntry,
- mapMessageReaction,
-} from '@/main/utils';
+import { fetchEntry, mapEntry, mapMessageReaction } from '@/main/utils';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class MessageReactionCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<MessageReactionCreateMutationInput>
{
async handleMutation(
input: MessageReactionCreateMutationInput
): Promise<MessageReactionCreateMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const message = await workspaceDatabase
+ const message = await workspace.database
.selectFrom('messages')
.selectAll()
.where('id', '=', input.messageId)
@@ -43,11 +37,11 @@ export class MessageReactionCreateMutationHandler
);
}
- const existingMessageReaction = await workspaceDatabase
+ const existingMessageReaction = await workspace.database
.selectFrom('message_reactions')
.selectAll()
.where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.where('reaction', '=', input.reaction)
.executeTakeFirst();
@@ -57,15 +51,7 @@ export class MessageReactionCreateMutationHandler
};
}
- const user = await fetchUser(workspaceDatabase, input.userId);
- if (!user) {
- throw new MutationError(
- MutationErrorCode.UserNotFound,
- 'There was an error while fetching the user. Please make sure you are logged in.'
- );
- }
-
- const root = await fetchEntry(workspaceDatabase, input.rootId);
+ const root = await fetchEntry(workspace.database, input.rootId);
if (!root) {
throw new MutationError(
MutationErrorCode.RootNotFound,
@@ -76,8 +62,8 @@ export class MessageReactionCreateMutationHandler
if (
!canCreateMessageReaction({
user: {
- userId: input.userId,
- role: user.role,
+ userId: workspace.userId,
+ role: workspace.role,
},
root: mapEntry(root),
message: {
@@ -92,7 +78,7 @@ export class MessageReactionCreateMutationHandler
);
}
- const { createdMessageReaction, createdMutation } = await workspaceDatabase
+ const { createdMessageReaction, createdMutation } = await workspace.database
.transaction()
.execute(async (trx) => {
const createdMessageReaction = await trx
@@ -100,7 +86,7 @@ export class MessageReactionCreateMutationHandler
.returningAll()
.values({
message_id: input.messageId,
- collaborator_id: input.userId,
+ collaborator_id: workspace.userId,
reaction: input.reaction,
root_id: input.rootId,
version: 0n,
@@ -153,14 +139,12 @@ export class MessageReactionCreateMutationHandler
throw new Error('Failed to create message reaction');
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'message_reaction_created',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
messageReaction: mapMessageReaction(createdMessageReaction),
});
diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts b/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
index 4646238e..af51b56e 100644
--- a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
+++ b/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
@@ -4,7 +4,6 @@ import {
IdType,
} from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
MessageReactionDeleteMutationInput,
@@ -12,22 +11,22 @@ import {
} from '@/shared/mutations/messages/message-reaction-delete';
import { mapMessageReaction } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class MessageReactionDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<MessageReactionDeleteMutationInput>
{
async handleMutation(
input: MessageReactionDeleteMutationInput
): Promise<MessageReactionDeleteMutationOutput> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const existingMessageReaction = await workspaceDatabase
+ const existingMessageReaction = await workspace.database
.selectFrom('message_reactions')
.selectAll()
.where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.where('reaction', '=', input.reaction)
.executeTakeFirst();
@@ -37,7 +36,7 @@ export class MessageReactionDeleteMutationHandler
};
}
- const { deletedMessageReaction, createdMutation } = await workspaceDatabase
+ const { deletedMessageReaction, createdMutation } = await workspace.database
.transaction()
.execute(async (trx) => {
const deletedMessageReaction = await trx
@@ -47,7 +46,7 @@ export class MessageReactionDeleteMutationHandler
deleted_at: new Date().toISOString(),
})
.where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', input.userId)
+ .where('collaborator_id', '=', workspace.userId)
.where('reaction', '=', input.reaction)
.executeTakeFirst();
@@ -89,14 +88,12 @@ export class MessageReactionDeleteMutationHandler
throw new Error('Failed to delete message reaction');
}
- eventBus.publish({
- type: 'mutation_created',
- userId: input.userId,
- });
+ workspace.mutations.triggerSync();
eventBus.publish({
type: 'message_reaction_deleted',
- userId: input.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
messageReaction: mapMessageReaction(deletedMessageReaction),
});
diff --git a/apps/desktop/src/main/mutations/pages/page-content-update.ts b/apps/desktop/src/main/mutations/pages/page-content-update.ts
index 3dd1a2d6..8770e537 100644
--- a/apps/desktop/src/main/mutations/pages/page-content-update.ts
+++ b/apps/desktop/src/main/mutations/pages/page-content-update.ts
@@ -1,7 +1,6 @@
import { PageAttributes } from '@colanode/core';
import { isEqual } from 'lodash-es';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { mapContentsToBlocks } from '@/shared/lib/editor';
import {
@@ -9,16 +8,19 @@ import {
PageContentUpdateMutationOutput,
} from '@/shared/mutations/pages/page-content-update';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class PageContentUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<PageContentUpdateMutationInput>
{
async handleMutation(
input: PageContentUpdateMutationInput
): Promise<PageContentUpdateMutationOutput> {
- const result = await entryService.updateEntry<PageAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<PageAttributes>(
input.pageId,
- input.userId,
(attributes) => {
const indexMap = new Map<string, string>();
if (attributes.content) {
diff --git a/apps/desktop/src/main/mutations/pages/page-create.ts b/apps/desktop/src/main/mutations/pages/page-create.ts
index a907cccc..a880e7f5 100644
--- a/apps/desktop/src/main/mutations/pages/page-create.ts
+++ b/apps/desktop/src/main/mutations/pages/page-create.ts
@@ -1,18 +1,21 @@
import { generateId, IdType, PageAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
PageCreateMutationInput,
PageCreateMutationOutput,
} from '@/shared/mutations/pages/page-create';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class PageCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<PageCreateMutationInput>
{
async handleMutation(
input: PageCreateMutationInput
): Promise<PageCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
const id = generateId(IdType.Page);
const attributes: PageAttributes = {
type: 'page',
@@ -21,7 +24,7 @@ export class PageCreateMutationHandler
name: input.name,
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id,
attributes,
parentId: input.parentId,
diff --git a/apps/desktop/src/main/mutations/pages/page-delete.ts b/apps/desktop/src/main/mutations/pages/page-delete.ts
index ffc6ae36..d14538a2 100644
--- a/apps/desktop/src/main/mutations/pages/page-delete.ts
+++ b/apps/desktop/src/main/mutations/pages/page-delete.ts
@@ -1,17 +1,20 @@
-import { entryService } from '@/main/services/entry-service';
-import { MutationHandler } from '@/main/types';
import {
PageDeleteMutationInput,
PageDeleteMutationOutput,
} from '@/shared/mutations/pages/page-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
+import { MutationHandler } from '@/main/types';
export class PageDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<PageDeleteMutationInput>
{
async handleMutation(
input: PageDeleteMutationInput
): Promise<PageDeleteMutationOutput> {
- await entryService.deleteEntry(input.pageId, input.userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ await workspace.entries.deleteEntry(input.pageId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/pages/page-update.ts b/apps/desktop/src/main/mutations/pages/page-update.ts
index 0bfae973..a7148bc6 100644
--- a/apps/desktop/src/main/mutations/pages/page-update.ts
+++ b/apps/desktop/src/main/mutations/pages/page-update.ts
@@ -1,22 +1,24 @@
import { PageAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
PageUpdateMutationInput,
PageUpdateMutationOutput,
} from '@/shared/mutations/pages/page-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class PageUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<PageUpdateMutationInput>
{
async handleMutation(
input: PageUpdateMutationInput
): Promise<PageUpdateMutationOutput> {
- const result = await entryService.updateEntry<PageAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<PageAttributes>(
input.pageId,
- input.userId,
(attributes) => {
attributes.name = input.name;
attributes.avatar = input.avatar;
diff --git a/apps/desktop/src/main/mutations/records/record-avatar-update.ts b/apps/desktop/src/main/mutations/records/record-avatar-update.ts
index 98ed4daa..ff3f5bda 100644
--- a/apps/desktop/src/main/mutations/records/record-avatar-update.ts
+++ b/apps/desktop/src/main/mutations/records/record-avatar-update.ts
@@ -1,22 +1,24 @@
import { RecordAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
RecordAvatarUpdateMutationInput,
RecordAvatarUpdateMutationOutput,
} from '@/shared/mutations/records/record-avatar-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class RecordAvatarUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<RecordAvatarUpdateMutationInput>
{
async handleMutation(
input: RecordAvatarUpdateMutationInput
): Promise<RecordAvatarUpdateMutationOutput> {
- const result = await entryService.updateEntry<RecordAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<RecordAttributes>(
input.recordId,
- input.userId,
(attributes) => {
attributes.avatar = input.avatar;
return attributes;
diff --git a/apps/desktop/src/main/mutations/records/record-content-update.ts b/apps/desktop/src/main/mutations/records/record-content-update.ts
index 0e0a851b..a8f7a84b 100644
--- a/apps/desktop/src/main/mutations/records/record-content-update.ts
+++ b/apps/desktop/src/main/mutations/records/record-content-update.ts
@@ -1,7 +1,6 @@
import { RecordAttributes } from '@colanode/core';
import { isEqual } from 'lodash-es';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { mapContentsToBlocks } from '@/shared/lib/editor';
import {
@@ -9,16 +8,19 @@ import {
RecordContentUpdateMutationOutput,
} from '@/shared/mutations/records/record-content-update';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class RecordContentUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<RecordContentUpdateMutationInput>
{
async handleMutation(
input: RecordContentUpdateMutationInput
): Promise<RecordContentUpdateMutationOutput> {
- const result = await entryService.updateEntry<RecordAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<RecordAttributes>(
input.recordId,
- input.userId,
(attributes) => {
const indexMap = new Map<string, string>();
if (attributes.content) {
diff --git a/apps/desktop/src/main/mutations/records/record-create.ts b/apps/desktop/src/main/mutations/records/record-create.ts
index 8fa4b6b0..1cf613fc 100644
--- a/apps/desktop/src/main/mutations/records/record-create.ts
+++ b/apps/desktop/src/main/mutations/records/record-create.ts
@@ -1,18 +1,21 @@
import { generateId, IdType, RecordAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
RecordCreateMutationInput,
RecordCreateMutationOutput,
} from '@/shared/mutations/records/record-create';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class RecordCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<RecordCreateMutationInput>
{
async handleMutation(
input: RecordCreateMutationInput
): Promise<RecordCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
const id = generateId(IdType.Record);
const attributes: RecordAttributes = {
type: 'record',
@@ -22,7 +25,7 @@ export class RecordCreateMutationHandler
fields: input.fields ?? {},
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id,
attributes,
parentId: input.databaseId,
diff --git a/apps/desktop/src/main/mutations/records/record-delete.ts b/apps/desktop/src/main/mutations/records/record-delete.ts
index cca0f38e..65c81161 100644
--- a/apps/desktop/src/main/mutations/records/record-delete.ts
+++ b/apps/desktop/src/main/mutations/records/record-delete.ts
@@ -1,17 +1,20 @@
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
RecordDeleteMutationInput,
RecordDeleteMutationOutput,
} from '@/shared/mutations/records/record-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class RecordDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<RecordDeleteMutationInput>
{
async handleMutation(
input: RecordDeleteMutationInput
): Promise<RecordDeleteMutationOutput> {
- await entryService.deleteEntry(input.recordId, input.userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ await workspace.entries.deleteEntry(input.recordId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/records/record-field-value-delete.ts b/apps/desktop/src/main/mutations/records/record-field-value-delete.ts
index 2f6eaf51..5f50c19d 100644
--- a/apps/desktop/src/main/mutations/records/record-field-value-delete.ts
+++ b/apps/desktop/src/main/mutations/records/record-field-value-delete.ts
@@ -1,22 +1,24 @@
import { RecordAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
RecordFieldValueDeleteMutationInput,
RecordFieldValueDeleteMutationOutput,
} from '@/shared/mutations/records/record-field-value-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class RecordFieldValueDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<RecordFieldValueDeleteMutationInput>
{
async handleMutation(
input: RecordFieldValueDeleteMutationInput
): Promise<RecordFieldValueDeleteMutationOutput> {
- const result = await entryService.updateEntry<RecordAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<RecordAttributes>(
input.recordId,
- input.userId,
(attributes) => {
delete attributes.fields[input.fieldId];
return attributes;
diff --git a/apps/desktop/src/main/mutations/records/record-field-value-set.ts b/apps/desktop/src/main/mutations/records/record-field-value-set.ts
index 563a3cc0..e36fc8b6 100644
--- a/apps/desktop/src/main/mutations/records/record-field-value-set.ts
+++ b/apps/desktop/src/main/mutations/records/record-field-value-set.ts
@@ -1,22 +1,24 @@
import { RecordAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
RecordFieldValueSetMutationInput,
RecordFieldValueSetMutationOutput,
} from '@/shared/mutations/records/record-field-value-set';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class RecordFieldValueSetMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<RecordFieldValueSetMutationInput>
{
async handleMutation(
input: RecordFieldValueSetMutationInput
): Promise<RecordFieldValueSetMutationOutput> {
- const result = await entryService.updateEntry<RecordAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<RecordAttributes>(
input.recordId,
- input.userId,
(attributes) => {
attributes.fields[input.fieldId] = input.value;
return attributes;
diff --git a/apps/desktop/src/main/mutations/records/record-name-update.ts b/apps/desktop/src/main/mutations/records/record-name-update.ts
index 1cc0c428..b8869b2d 100644
--- a/apps/desktop/src/main/mutations/records/record-name-update.ts
+++ b/apps/desktop/src/main/mutations/records/record-name-update.ts
@@ -1,22 +1,24 @@
import { RecordAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
RecordNameUpdateMutationInput,
RecordNameUpdateMutationOutput,
} from '@/shared/mutations/records/record-name-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class RecordNameUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<RecordNameUpdateMutationInput>
{
async handleMutation(
input: RecordNameUpdateMutationInput
): Promise<RecordNameUpdateMutationOutput> {
- const result = await entryService.updateEntry<RecordAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<RecordAttributes>(
input.recordId,
- input.userId,
(attributes) => {
attributes.name = input.name;
return attributes;
diff --git a/apps/desktop/src/main/mutations/servers/server-create.ts b/apps/desktop/src/main/mutations/servers/server-create.ts
index efd633d7..effe41c5 100644
--- a/apps/desktop/src/main/mutations/servers/server-create.ts
+++ b/apps/desktop/src/main/mutations/servers/server-create.ts
@@ -1,5 +1,4 @@
-import { databaseService } from '@/main/data/database-service';
-import { serverService } from '@/main/services/server-service';
+import { appService } from '@/main/services/app-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
@@ -14,20 +13,7 @@ export class ServerCreateMutationHandler
input: ServerCreateMutationInput
): Promise<ServerCreateMutationOutput> {
const domain = parseDomain(input.domain);
- const existingServer = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', domain)
- .executeTakeFirst();
-
- if (existingServer) {
- throw new MutationError(
- MutationErrorCode.ServerAlreadyExists,
- 'A server with this domain already exists.'
- );
- }
-
- const server = await serverService.createServer(domain);
+ const server = await appService.createServer(domain);
if (server === null) {
throw new MutationError(
MutationErrorCode.ServerInitFailed,
@@ -36,7 +22,7 @@ export class ServerCreateMutationHandler
}
return {
- server,
+ server: server.server,
};
}
}
diff --git a/apps/desktop/src/main/mutations/spaces/space-create.ts b/apps/desktop/src/main/mutations/spaces/space-create.ts
index fcc98189..61a43847 100644
--- a/apps/desktop/src/main/mutations/spaces/space-create.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-create.ts
@@ -6,26 +6,22 @@ import {
SpaceAttributes,
} from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
SpaceCreateMutationInput,
SpaceCreateMutationOutput,
} from '@/shared/mutations/spaces/space-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class SpaceCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<SpaceCreateMutationInput>
{
async handleMutation(
input: SpaceCreateMutationInput
): Promise<SpaceCreateMutationOutput> {
- const workspace = await databaseService.appDatabase
- .selectFrom('workspaces')
- .where('user_id', '=', input.userId)
- .selectAll()
- .executeTakeFirst();
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
if (!workspace) {
throw new MutationError(
@@ -47,12 +43,12 @@ export class SpaceCreateMutationHandler
name: input.name,
visibility: 'private',
collaborators: {
- [input.userId]: 'admin',
+ [workspace.userId]: 'admin',
},
description: input.description,
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id: spaceId,
attributes: spaceAttributes,
parentId: null,
@@ -65,7 +61,7 @@ export class SpaceCreateMutationHandler
parentId: spaceId,
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id: pageId,
attributes: pageAttributes,
parentId: spaceId,
@@ -78,7 +74,7 @@ export class SpaceCreateMutationHandler
parentId: spaceId,
};
- await entryService.createEntry(input.userId, {
+ await workspace.entries.createEntry({
id: channelId,
attributes: channelAttributes,
parentId: spaceId,
diff --git a/apps/desktop/src/main/mutations/spaces/space-delete.ts b/apps/desktop/src/main/mutations/spaces/space-delete.ts
index fe473948..b6b08e58 100644
--- a/apps/desktop/src/main/mutations/spaces/space-delete.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-delete.ts
@@ -1,17 +1,19 @@
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import {
SpaceDeleteMutationInput,
SpaceDeleteMutationOutput,
} from '@/shared/mutations/spaces/space-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class SpaceDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<SpaceDeleteMutationInput>
{
async handleMutation(
input: SpaceDeleteMutationInput
): Promise<SpaceDeleteMutationOutput> {
- await entryService.deleteEntry(input.spaceId, input.userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ await workspace.entries.deleteEntry(input.spaceId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/spaces/space-update.ts b/apps/desktop/src/main/mutations/spaces/space-update.ts
index ed62bf07..71de36ad 100644
--- a/apps/desktop/src/main/mutations/spaces/space-update.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-update.ts
@@ -1,22 +1,24 @@
import { SpaceAttributes } from '@colanode/core';
-import { entryService } from '@/main/services/entry-service';
import { MutationHandler } from '@/main/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
SpaceUpdateMutationInput,
SpaceUpdateMutationOutput,
} from '@/shared/mutations/spaces/space-update';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class SpaceUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<SpaceUpdateMutationInput>
{
async handleMutation(
input: SpaceUpdateMutationInput
): Promise<SpaceUpdateMutationOutput> {
- const result = await entryService.updateEntry<SpaceAttributes>(
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const result = await workspace.entries.updateEntry<SpaceAttributes>(
input.id,
- input.userId,
(attributes) => {
attributes.name = input.name;
attributes.description = input.description;
diff --git a/apps/desktop/src/main/mutations/users/user-role-update.ts b/apps/desktop/src/main/mutations/users/user-role-update.ts
index 5d2febd0..acceee07 100644
--- a/apps/desktop/src/main/mutations/users/user-role-update.ts
+++ b/apps/desktop/src/main/mutations/users/user-role-update.ts
@@ -1,69 +1,28 @@
import { UserRoleUpdateOutput } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
-import { httpClient } from '@/shared/lib/http-client';
import {
UserRoleUpdateMutationInput,
UserRoleUpdateMutationOutput,
} from '@/shared/mutations/workspaces/workspace-user-role-update';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class UserRoleUpdateMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<UserRoleUpdateMutationInput>
{
async handleMutation(
input: UserRoleUpdateMutationInput
): Promise<UserRoleUpdateMutationOutput> {
- const workspace = await databaseService.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .where('user_id', '=', input.userId)
- .executeTakeFirst();
-
- if (!workspace) {
- throw new MutationError(
- MutationErrorCode.WorkspaceNotFound,
- 'Workspace was not found or has been deleted.'
- );
- }
-
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', workspace.account_id)
- .executeTakeFirst();
-
- if (!account) {
- throw new MutationError(
- MutationErrorCode.AccountNotFound,
- 'The account associated with this workspace was not found or has been logged out.'
- );
- }
-
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', account.server)
- .executeTakeFirst();
-
- if (!server) {
- throw new MutationError(
- MutationErrorCode.ServerNotFound,
- 'The server associated with this account was not found.'
- );
- }
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
try {
- await httpClient.put<UserRoleUpdateOutput>(
- `/v1/workspaces/${workspace.workspace_id}/users/${input.userToUpdateId}`,
+ await workspace.account.client.put<UserRoleUpdateOutput>(
+ `/v1/workspaces/${workspace.id}/users/${input.userId}`,
{
role: input.role,
- },
- {
- domain: server.domain,
- token: account.token,
}
);
diff --git a/apps/desktop/src/main/mutations/users/users-invite.ts b/apps/desktop/src/main/mutations/users/users-invite.ts
index 11e2c004..93f4ce0f 100644
--- a/apps/desktop/src/main/mutations/users/users-invite.ts
+++ b/apps/desktop/src/main/mutations/users/users-invite.ts
@@ -1,70 +1,29 @@
import { UsersInviteOutput } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
-import { httpClient } from '@/shared/lib/http-client';
import {
UsersInviteMutationInput,
UsersInviteMutationOutput,
} from '@/shared/mutations/workspaces/workspace-users-invite';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class UsersInviteMutationHandler
+ extends WorkspaceMutationHandlerBase
implements MutationHandler<UsersInviteMutationInput>
{
async handleMutation(
input: UsersInviteMutationInput
): Promise<UsersInviteMutationOutput> {
- const workspace = await databaseService.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .where('user_id', '=', input.userId)
- .executeTakeFirst();
-
- if (!workspace) {
- throw new MutationError(
- MutationErrorCode.WorkspaceNotFound,
- 'Workspace was not found or has been deleted.'
- );
- }
-
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', workspace.account_id)
- .executeTakeFirst();
-
- if (!account) {
- throw new MutationError(
- MutationErrorCode.AccountNotFound,
- 'The account associated with this workspace was not found or has been logged out.'
- );
- }
-
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', account.server)
- .executeTakeFirst();
-
- if (!server) {
- throw new MutationError(
- MutationErrorCode.ServerNotFound,
- 'The server associated with this account was not found.'
- );
- }
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
try {
- await httpClient.post<UsersInviteOutput>(
- `/v1/workspaces/${workspace.workspace_id}/users`,
+ await workspace.account.client.post<UsersInviteOutput>(
+ `/v1/workspaces/${workspace.id}/users`,
{
emails: input.emails,
role: input.role,
- },
- {
- domain: server.domain,
- token: account.token,
}
);
diff --git a/apps/desktop/src/main/mutations/workspace-mutation-handler-base.ts b/apps/desktop/src/main/mutations/workspace-mutation-handler-base.ts
new file mode 100644
index 00000000..ecd1847a
--- /dev/null
+++ b/apps/desktop/src/main/mutations/workspace-mutation-handler-base.ts
@@ -0,0 +1,28 @@
+import { appService } from '@/main/services/app-service';
+import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+
+export abstract class WorkspaceMutationHandlerBase {
+ protected getWorkspace(
+ accountId: string,
+ workspaceId: string
+ ): WorkspaceService {
+ const account = appService.getAccount(accountId);
+ if (!account) {
+ throw new MutationError(
+ MutationErrorCode.AccountNotFound,
+ 'Account not found or has been logged out already. Try closing the app and opening it again.'
+ );
+ }
+
+ const workspace = account.getWorkspace(workspaceId);
+ if (!workspace) {
+ throw new MutationError(
+ MutationErrorCode.WorkspaceNotFound,
+ 'Workspace not found or has been deleted.'
+ );
+ }
+
+ return workspace;
+ }
+}
diff --git a/apps/desktop/src/main/mutations/workspaces/workspace-create.ts b/apps/desktop/src/main/mutations/workspaces/workspace-create.ts
index 3d867be1..8632ea0e 100644
--- a/apps/desktop/src/main/mutations/workspaces/workspace-create.ts
+++ b/apps/desktop/src/main/mutations/workspaces/workspace-create.ts
@@ -1,15 +1,15 @@
import { WorkspaceOutput } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import { eventBus } from '@/shared/lib/event-bus';
-import { httpClient } from '@/shared/lib/http-client';
import {
WorkspaceCreateMutationInput,
WorkspaceCreateMutationOutput,
} from '@/shared/mutations/workspaces/workspace-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { parseApiError } from '@/shared/lib/axios';
+import { appService } from '@/main/services/app-service';
+import { mapWorkspace } from '@/main/utils';
export class WorkspaceCreateMutationHandler
implements MutationHandler<WorkspaceCreateMutationInput>
@@ -17,11 +17,7 @@ export class WorkspaceCreateMutationHandler
async handleMutation(
input: WorkspaceCreateMutationInput
): Promise<WorkspaceCreateMutationOutput> {
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', input.accountId)
- .executeTakeFirst();
+ const account = appService.getAccount(input.accountId);
if (!account) {
throw new MutationError(
@@ -30,38 +26,21 @@ export class WorkspaceCreateMutationHandler
);
}
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', account.server)
- .executeTakeFirst();
-
- if (!server) {
- throw new MutationError(
- MutationErrorCode.ServerNotFound,
- 'The server associated with this account was not found.'
- );
- }
-
try {
- const { data } = await httpClient.post<WorkspaceOutput>(
+ const { data } = await account.client.post<WorkspaceOutput>(
`/v1/workspaces`,
{
name: input.name,
description: input.description,
avatar: input.avatar,
- },
- {
- domain: server.domain,
- token: account.token,
}
);
- const createdWorkspace = await databaseService.appDatabase
+ const createdWorkspace = await account.database
.insertInto('workspaces')
.returningAll()
.values({
- workspace_id: data.id ?? data.id,
+ id: data.id,
account_id: data.user.accountId,
name: data.name,
description: data.description,
@@ -79,21 +58,16 @@ export class WorkspaceCreateMutationHandler
);
}
+ const workspace = mapWorkspace(createdWorkspace);
+ await account.initWorkspace(workspace);
+
eventBus.publish({
type: 'workspace_created',
- workspace: {
- id: createdWorkspace.workspace_id,
- userId: createdWorkspace.user_id,
- name: createdWorkspace.name,
- accountId: createdWorkspace.account_id,
- role: createdWorkspace.role,
- avatar: createdWorkspace.avatar,
- description: createdWorkspace.description,
- },
+ workspace: workspace,
});
return {
- id: createdWorkspace.workspace_id,
+ id: createdWorkspace.id,
userId: createdWorkspace.user_id,
};
} catch (error) {
diff --git a/apps/desktop/src/main/mutations/workspaces/workspace-update.ts b/apps/desktop/src/main/mutations/workspaces/workspace-update.ts
index 7a028544..577a128d 100644
--- a/apps/desktop/src/main/mutations/workspaces/workspace-update.ts
+++ b/apps/desktop/src/main/mutations/workspaces/workspace-update.ts
@@ -1,8 +1,8 @@
-import { databaseService } from '@/main/data/database-service';
+import { appService } from '@/main/services/app-service';
import { MutationHandler } from '@/main/types';
+import { mapWorkspace } from '@/main/utils';
import { parseApiError } from '@/shared/lib/axios';
import { eventBus } from '@/shared/lib/event-bus';
-import { httpClient } from '@/shared/lib/http-client';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
WorkspaceUpdateMutationInput,
@@ -16,47 +16,34 @@ export class WorkspaceUpdateMutationHandler
async handleMutation(
input: WorkspaceUpdateMutationInput
): Promise<WorkspaceUpdateMutationOutput> {
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', input.accountId)
- .executeTakeFirst();
+ const accountService = appService.getAccount(input.accountId);
- if (!account) {
+ if (!accountService) {
throw new MutationError(
MutationErrorCode.AccountNotFound,
'Account not found or has been logged out.'
);
}
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', account.server)
- .executeTakeFirst();
-
- if (!server) {
+ const workspaceService = accountService.getWorkspace(input.id);
+ if (!workspaceService) {
throw new MutationError(
- MutationErrorCode.ServerNotFound,
- 'The server associated with this account was not found.'
+ MutationErrorCode.WorkspaceNotFound,
+ 'Workspace not found.'
);
}
try {
- const { data } = await httpClient.put<Workspace>(
+ const { data } = await accountService.client.put<Workspace>(
`/v1/workspaces/${input.id}`,
{
name: input.name,
description: input.description,
avatar: input.avatar,
- },
- {
- domain: server.domain,
- token: account.token,
}
);
- const updatedWorkspace = await databaseService.appDatabase
+ const updatedWorkspace = await accountService.database
.updateTable('workspaces')
.returningAll()
.set({
@@ -65,12 +52,7 @@ export class WorkspaceUpdateMutationHandler
avatar: data.avatar,
role: data.role,
})
- .where((eb) =>
- eb.and([
- eb('account_id', '=', input.accountId),
- eb('workspace_id', '=', input.id),
- ])
- )
+ .where((eb) => eb.and([eb('id', '=', input.id)]))
.executeTakeFirst();
if (!updatedWorkspace) {
@@ -80,15 +62,12 @@ export class WorkspaceUpdateMutationHandler
);
}
+ const workspace = mapWorkspace(updatedWorkspace);
+ workspaceService.updateWorkspace(workspace);
+
eventBus.publish({
type: 'workspace_updated',
- workspace: {
- id: updatedWorkspace.workspace_id,
- userId: updatedWorkspace.user_id,
- name: updatedWorkspace.name,
- accountId: updatedWorkspace.account_id,
- role: updatedWorkspace.role,
- },
+ workspace: workspace,
});
return {
diff --git a/apps/desktop/src/main/queries/accounts/account-get.ts b/apps/desktop/src/main/queries/accounts/account-get.ts
index 962da539..48ab6919 100644
--- a/apps/desktop/src/main/queries/accounts/account-get.ts
+++ b/apps/desktop/src/main/queries/accounts/account-get.ts
@@ -1,5 +1,5 @@
-import { SelectAccount } from '@/main/data/app/schema';
-import { databaseService } from '@/main/data/database-service';
+import { SelectAccount } from '@/main/databases/app';
+import { appService } from '@/main/services/app-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapAccount } from '@/main/utils';
import { AccountGetQueryInput } from '@/shared/queries/accounts/account-get';
@@ -60,7 +60,7 @@ export class AccountGetQueryHandler
}
private fetchAccount(accountId: string): Promise<SelectAccount | undefined> {
- return databaseService.appDatabase
+ return appService.database
.selectFrom('accounts')
.selectAll()
.where('id', '=', accountId)
diff --git a/apps/desktop/src/main/queries/accounts/accounts-list.ts b/apps/desktop/src/main/queries/accounts/accounts-list.ts
index 38572580..f9a4dccf 100644
--- a/apps/desktop/src/main/queries/accounts/accounts-list.ts
+++ b/apps/desktop/src/main/queries/accounts/accounts-list.ts
@@ -1,5 +1,5 @@
-import { SelectAccount } from '@/main/data/app/schema';
-import { databaseService } from '@/main/data/database-service';
+import { SelectAccount } from '@/main/databases/app';
+import { appService } from '@/main/services/app-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapAccount } from '@/main/utils';
import { AccountListQueryInput } from '@/shared/queries/accounts/account-list';
@@ -58,9 +58,6 @@ export class AccountListQueryHandler
}
private fetchAccounts(): Promise<SelectAccount[]> {
- return databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .execute();
+ return appService.database.selectFrom('accounts').selectAll().execute();
}
}
diff --git a/apps/desktop/src/main/queries/chats/chat-list.ts b/apps/desktop/src/main/queries/chats/chat-list.ts
index e174b222..d43e2f2a 100644
--- a/apps/desktop/src/main/queries/chats/chat-list.ts
+++ b/apps/desktop/src/main/queries/chats/chat-list.ts
@@ -1,13 +1,16 @@
import { ChatEntry } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
+import { SelectEntry } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapEntry } from '@/main/utils';
import { ChatListQueryInput } from '@/shared/queries/chats/chat-list';
import { Event } from '@/shared/types/events';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-export class ChatListQueryHandler implements QueryHandler<ChatListQueryInput> {
+export class ChatListQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<ChatListQueryInput>
+{
public async handleQuery(input: ChatListQueryInput): Promise<ChatEntry[]> {
const rows = await this.fetchChildren(input);
return rows.map(mapEntry) as ChatEntry[];
@@ -20,7 +23,8 @@ export class ChatListQueryHandler implements QueryHandler<ChatListQueryInput> {
): Promise<ChangeCheckResult<ChatListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -30,7 +34,8 @@ export class ChatListQueryHandler implements QueryHandler<ChatListQueryInput> {
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'chat'
) {
const newChildren = [...output, event.entry];
@@ -42,7 +47,8 @@ export class ChatListQueryHandler implements QueryHandler<ChatListQueryInput> {
if (
event.type === 'entry_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'chat'
) {
const entry = output.find((entry) => entry.id === event.entry.id);
@@ -60,7 +66,8 @@ export class ChatListQueryHandler implements QueryHandler<ChatListQueryInput> {
if (
event.type === 'entry_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'chat'
) {
const entry = output.find((entry) => entry.id === event.entry.id);
@@ -83,11 +90,9 @@ export class ChatListQueryHandler implements QueryHandler<ChatListQueryInput> {
private async fetchChildren(
input: ChatListQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const rows = await workspaceDatabase
+ const rows = await workspace.database
.selectFrom('entries')
.selectAll()
.where('parent_id', 'is', null)
diff --git a/apps/desktop/src/main/queries/databases/database-list.ts b/apps/desktop/src/main/queries/databases/database-list.ts
index facba53d..04841383 100644
--- a/apps/desktop/src/main/queries/databases/database-list.ts
+++ b/apps/desktop/src/main/queries/databases/database-list.ts
@@ -1,13 +1,14 @@
import { compareString, DatabaseEntry } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
+import { SelectEntry } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapEntry } from '@/main/utils';
import { DatabaseListQueryInput } from '@/shared/queries/databases/database-list';
import { Event } from '@/shared/types/events';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
export class DatabaseListQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<DatabaseListQueryInput>
{
public async handleQuery(
@@ -24,7 +25,8 @@ export class DatabaseListQueryHandler
): Promise<ChangeCheckResult<DatabaseListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -34,7 +36,8 @@ export class DatabaseListQueryHandler
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'database'
) {
const newResult = await this.handleQuery(input);
@@ -47,7 +50,8 @@ export class DatabaseListQueryHandler
if (
event.type === 'entry_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'database'
) {
const database = output.find(
@@ -70,7 +74,8 @@ export class DatabaseListQueryHandler
if (
event.type === 'entry_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'database'
) {
const database = output.find(
@@ -94,11 +99,9 @@ export class DatabaseListQueryHandler
private async fetchDatabases(
input: DatabaseListQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const databases = await workspaceDatabase
+ const databases = await workspace.database
.selectFrom('entries')
.where('type', '=', 'database')
.selectAll()
diff --git a/apps/desktop/src/main/queries/emojis/emojis-get.ts b/apps/desktop/src/main/queries/emojis/emojis-get.ts
index 68e9fe82..76a02988 100644
--- a/apps/desktop/src/main/queries/emojis/emojis-get.ts
+++ b/apps/desktop/src/main/queries/emojis/emojis-get.ts
@@ -1,4 +1,4 @@
-import { assetService } from '@/main/services/asset-service';
+import { getEmojiData } from '@/main/lib/assets';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { EmojisGetQueryInput } from '@/shared/queries/emojis/emojis-get';
import { EmojiData } from '@/shared/types/emojis';
@@ -8,7 +8,7 @@ export class EmojisGetQueryHandler
implements QueryHandler<EmojisGetQueryInput>
{
public async handleQuery(_: EmojisGetQueryInput): Promise<EmojiData> {
- const data = assetService.getEmojiData();
+ const data = getEmojiData();
return data;
}
diff --git a/apps/desktop/src/main/queries/entries/entry-children-get.ts b/apps/desktop/src/main/queries/entries/entry-children-get.ts
index 796fc4a1..c60d21c4 100644
--- a/apps/desktop/src/main/queries/entries/entry-children-get.ts
+++ b/apps/desktop/src/main/queries/entries/entry-children-get.ts
@@ -1,13 +1,14 @@
import { Entry } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
+import { SelectEntry } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapEntry } from '@/main/utils';
-import { EntryChildrenGetQueryInput } from '@/shared/queries/entries/entry-children-get';
import { Event } from '@/shared/types/events';
+import { EntryChildrenGetQueryInput } from '@/shared/queries/entries/entry-children-get';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
export class EntryChildrenGetQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<EntryChildrenGetQueryInput>
{
public async handleQuery(
@@ -24,7 +25,8 @@ export class EntryChildrenGetQueryHandler
): Promise<ChangeCheckResult<EntryChildrenGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -34,7 +36,8 @@ export class EntryChildrenGetQueryHandler
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.parentId === input.entryId &&
(input.types === undefined || input.types.includes(event.entry.type))
) {
@@ -47,7 +50,8 @@ export class EntryChildrenGetQueryHandler
if (
event.type === 'entry_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.parentId === input.entryId &&
(input.types === undefined || input.types.includes(event.entry.type))
) {
@@ -66,7 +70,8 @@ export class EntryChildrenGetQueryHandler
if (
event.type === 'entry_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.parentId === input.entryId &&
(input.types === undefined || input.types.includes(event.entry.type))
) {
@@ -90,11 +95,9 @@ export class EntryChildrenGetQueryHandler
private async fetchChildren(
input: EntryChildrenGetQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const rows = await workspaceDatabase
+ const rows = await workspace.database
.selectFrom('entries')
.selectAll()
.where('parent_id', '=', input.entryId)
diff --git a/apps/desktop/src/main/queries/entries/entry-get.ts b/apps/desktop/src/main/queries/entries/entry-get.ts
index 57fbd653..91199584 100644
--- a/apps/desktop/src/main/queries/entries/entry-get.ts
+++ b/apps/desktop/src/main/queries/entries/entry-get.ts
@@ -1,13 +1,16 @@
import { Entry } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
+import { SelectEntry } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapEntry } from '@/main/utils';
import { EntryGetQueryInput } from '@/shared/queries/entries/entry-get';
import { Event } from '@/shared/types/events';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-export class EntryGetQueryHandler implements QueryHandler<EntryGetQueryInput> {
+export class EntryGetQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<EntryGetQueryInput>
+{
public async handleQuery(input: EntryGetQueryInput): Promise<Entry | null> {
const row = await this.fetchEntry(input);
return row ? mapEntry(row) : null;
@@ -20,7 +23,8 @@ export class EntryGetQueryHandler implements QueryHandler<EntryGetQueryInput> {
): Promise<ChangeCheckResult<EntryGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -30,7 +34,8 @@ export class EntryGetQueryHandler implements QueryHandler<EntryGetQueryInput> {
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.id === input.entryId
) {
return {
@@ -41,7 +46,8 @@ export class EntryGetQueryHandler implements QueryHandler<EntryGetQueryInput> {
if (
event.type === 'entry_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.id === input.entryId
) {
return {
@@ -52,7 +58,8 @@ export class EntryGetQueryHandler implements QueryHandler<EntryGetQueryInput> {
if (
event.type === 'entry_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.id === input.entryId
) {
return {
@@ -69,11 +76,9 @@ export class EntryGetQueryHandler implements QueryHandler<EntryGetQueryInput> {
private async fetchEntry(
input: EntryGetQueryInput
): Promise<SelectEntry | undefined> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const row = await workspaceDatabase
+ const row = await workspace.database
.selectFrom('entries')
.selectAll()
.where('id', '=', input.entryId)
diff --git a/apps/desktop/src/main/queries/entries/entry-tree-get.ts b/apps/desktop/src/main/queries/entries/entry-tree-get.ts
index 7104dc7a..fa4a8144 100644
--- a/apps/desktop/src/main/queries/entries/entry-tree-get.ts
+++ b/apps/desktop/src/main/queries/entries/entry-tree-get.ts
@@ -1,13 +1,14 @@
import { Entry } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
+import { SelectEntry } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { fetchEntryAncestors, mapEntry } from '@/main/utils';
import { EntryTreeGetQueryInput } from '@/shared/queries/entries/entry-tree-get';
import { Event } from '@/shared/types/events';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
export class EntryTreeGetQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<EntryTreeGetQueryInput>
{
public async handleQuery(input: EntryTreeGetQueryInput): Promise<Entry[]> {
@@ -22,7 +23,8 @@ export class EntryTreeGetQueryHandler
): Promise<ChangeCheckResult<EntryTreeGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -32,7 +34,8 @@ export class EntryTreeGetQueryHandler
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.id === input.entryId
) {
const newResult = await this.handleQuery(input);
@@ -42,7 +45,11 @@ export class EntryTreeGetQueryHandler
};
}
- if (event.type === 'entry_updated' && event.userId === input.userId) {
+ if (
+ event.type === 'entry_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const entry = output.find((entry) => entry.id === event.entry.id);
if (entry) {
const newEntries = output.map((entry) => {
@@ -59,7 +66,11 @@ export class EntryTreeGetQueryHandler
}
}
- if (event.type === 'entry_deleted' && event.userId === input.userId) {
+ if (
+ event.type === 'entry_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const entry = output.find((entry) => entry.id === event.entry.id);
if (entry) {
const newResult = await this.handleQuery(input);
@@ -78,11 +89,9 @@ export class EntryTreeGetQueryHandler
private async fetchEntries(
input: EntryTreeGetQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const rows = await fetchEntryAncestors(workspaceDatabase, input.entryId);
+ const rows = await fetchEntryAncestors(workspace.database, input.entryId);
if (rows.length === 0) {
return [];
}
diff --git a/apps/desktop/src/main/queries/files/file-get.ts b/apps/desktop/src/main/queries/files/file-get.ts
index 9bba92bb..79de1743 100644
--- a/apps/desktop/src/main/queries/files/file-get.ts
+++ b/apps/desktop/src/main/queries/files/file-get.ts
@@ -1,4 +1,3 @@
-import { databaseService } from '@/main/data/database-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapFile } from '@/main/utils';
import { FileGetQueryInput } from '@/shared/queries/files/file-get';
@@ -8,8 +7,12 @@ import {
FileWithState,
UploadStatus,
} from '@/shared/types/files';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
+export class FileGetQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<FileGetQueryInput>
+{
public async handleQuery(
input: FileGetQueryInput
): Promise<FileWithState | null> {
@@ -23,7 +26,8 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
): Promise<ChangeCheckResult<FileGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -33,7 +37,8 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
if (
event.type === 'file_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.file.id === input.id
) {
const output = await this.handleQuery(input);
@@ -45,7 +50,8 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
if (
event.type === 'file_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.file.id === input.id
) {
return {
@@ -62,7 +68,8 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
if (
event.type === 'file_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.file.id === input.id
) {
return {
@@ -73,7 +80,8 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
if (
event.type === 'file_state_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.fileState.fileId === input.id
) {
if (output === null) {
@@ -95,7 +103,8 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
if (
event.type === 'file_state_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.fileState.fileId === input.id
) {
if (output === null) {
@@ -123,11 +132,9 @@ export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
private async fetchFile(
input: FileGetQueryInput
): Promise<FileWithState | null> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const file = await workspaceDatabase
+ const file = await workspace.database
.selectFrom('files as f')
.leftJoin('file_states as fs', 'f.id', 'fs.file_id')
.select([
diff --git a/apps/desktop/src/main/queries/files/file-list.ts b/apps/desktop/src/main/queries/files/file-list.ts
index d4b54491..01d49f42 100644
--- a/apps/desktop/src/main/queries/files/file-list.ts
+++ b/apps/desktop/src/main/queries/files/file-list.ts
@@ -1,4 +1,3 @@
-import { databaseService } from '@/main/data/database-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapFile } from '@/main/utils';
import { FileListQueryInput } from '@/shared/queries/files/file-list';
@@ -8,8 +7,12 @@ import {
FileWithState,
UploadStatus,
} from '@/shared/types/files';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
+export class FileListQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<FileListQueryInput>
+{
public async handleQuery(
input: FileListQueryInput
): Promise<FileWithState[]> {
@@ -23,7 +26,8 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
): Promise<ChangeCheckResult<FileListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -33,7 +37,8 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
if (
event.type === 'file_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.file.parentId === input.parentId
) {
const output = await this.handleQuery(input);
@@ -45,7 +50,8 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
if (
event.type === 'file_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.file.parentId === input.parentId
) {
const file = output.find((file) => file.id === event.file.id);
@@ -73,7 +79,8 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
if (
event.type === 'file_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.file.parentId === input.parentId
) {
const file = output.find((file) => file.id === event.file.id);
@@ -86,7 +93,11 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
}
}
- if (event.type === 'file_state_created' && event.userId === input.userId) {
+ if (
+ event.type === 'file_state_created' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const file = output.find((file) => file.id === event.fileState.fileId);
if (file) {
const newResult = output.map((file) => {
@@ -106,7 +117,11 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
}
}
- if (event.type === 'file_state_updated' && event.userId === input.userId) {
+ if (
+ event.type === 'file_state_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const file = output.find((file) => file.id === event.fileState.fileId);
if (file) {
const newResult = output.map((file) => {
@@ -134,12 +149,10 @@ export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
private async fetchFiles(
input: FileListQueryInput
): Promise<FileWithState[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const offset = (input.page - 1) * input.count;
- const files = await workspaceDatabase
+ const files = await workspace.database
.selectFrom('files as f')
.leftJoin('file_states as fs', 'f.id', 'fs.file_id')
.select([
diff --git a/apps/desktop/src/main/queries/files/file-metadata-get.ts b/apps/desktop/src/main/queries/files/file-metadata-get.ts
index bba3d400..32e7ac54 100644
--- a/apps/desktop/src/main/queries/files/file-metadata-get.ts
+++ b/apps/desktop/src/main/queries/files/file-metadata-get.ts
@@ -1,5 +1,5 @@
-import { fileService } from '@/main/services/file-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
+import { getFileMetadata } from '@/main/utils';
import { FileMetadataGetQueryInput } from '@/shared/queries/files/file-metadata-get';
import { Event } from '@/shared/types/events';
import { FileMetadata } from '@/shared/types/files';
@@ -10,7 +10,7 @@ export class FileMetadataGetQueryHandler
public async handleQuery(
input: FileMetadataGetQueryInput
): Promise<FileMetadata | null> {
- const data = fileService.getFileMetadata(input.path);
+ const data = getFileMetadata(input.path);
return data;
}
diff --git a/apps/desktop/src/main/queries/icons/icons-get.ts b/apps/desktop/src/main/queries/icons/icons-get.ts
index 8d2351a2..baadb051 100644
--- a/apps/desktop/src/main/queries/icons/icons-get.ts
+++ b/apps/desktop/src/main/queries/icons/icons-get.ts
@@ -1,4 +1,4 @@
-import { assetService } from '@/main/services/asset-service';
+import { getIconData } from '@/main/lib/assets';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { IconsGetQueryInput } from '@/shared/queries/icons/icons-get';
import { Event } from '@/shared/types/events';
@@ -6,7 +6,7 @@ import { IconData } from '@/shared/types/icons';
export class IconsGetQueryHandler implements QueryHandler<IconsGetQueryInput> {
public async handleQuery(_: IconsGetQueryInput): Promise<IconData> {
- const data = assetService.getIconData();
+ const data = getIconData();
return data;
}
diff --git a/apps/desktop/src/main/queries/interactions/radar-data-get.ts b/apps/desktop/src/main/queries/interactions/radar-data-get.ts
index 5cedcc29..1a63a8f2 100644
--- a/apps/desktop/src/main/queries/interactions/radar-data-get.ts
+++ b/apps/desktop/src/main/queries/interactions/radar-data-get.ts
@@ -1,6 +1,9 @@
-import { radarService } from '@/main/services/radar-service';
+import { appService } from '@/main/services/app-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
-import { RadarDataGetQueryInput } from '@/shared/queries/interactions/radar-data-get';
+import {
+ RadarDataGetQueryInput,
+ RadarDataGetQueryOutput,
+} from '@/shared/queries/interactions/radar-data-get';
import { Event } from '@/shared/types/events';
import { WorkspaceRadarData } from '@/shared/types/radars';
@@ -9,18 +12,18 @@ export class RadarDataGetQueryHandler
{
public async handleQuery(
_: RadarDataGetQueryInput
- ): Promise<Record<string, WorkspaceRadarData>> {
- const data = radarService.getData();
+ ): Promise<RadarDataGetQueryOutput> {
+ const data = this.getRadarData();
return data;
}
public async checkForChanges(
event: Event,
_: RadarDataGetQueryInput,
- ___: Record<string, WorkspaceRadarData>
+ ___: RadarDataGetQueryOutput
): Promise<ChangeCheckResult<RadarDataGetQueryInput>> {
if (event.type === 'radar_data_updated') {
- const data = radarService.getData();
+ const data = this.getRadarData();
return {
hasChanges: true,
result: data,
@@ -31,4 +34,26 @@ export class RadarDataGetQueryHandler
hasChanges: false,
};
}
+
+ private getRadarData(): RadarDataGetQueryOutput {
+ const result: RadarDataGetQueryOutput = {};
+ const accounts = appService.getAccounts();
+ if (accounts.length === 0) {
+ return result;
+ }
+
+ for (const account of accounts) {
+ const accountResult: Record<string, WorkspaceRadarData> = {};
+ const workspaces = account.getWorkspaces();
+
+ for (const workspace of workspaces) {
+ const radarData = workspace.radar.getData();
+ accountResult[workspace.id] = radarData;
+ }
+
+ result[account.id] = accountResult;
+ }
+
+ return result;
+ }
}
diff --git a/apps/desktop/src/main/queries/messages/message-get.ts b/apps/desktop/src/main/queries/messages/message-get.ts
index 04fe0696..39c850b7 100644
--- a/apps/desktop/src/main/queries/messages/message-get.ts
+++ b/apps/desktop/src/main/queries/messages/message-get.ts
@@ -1,5 +1,5 @@
-import { databaseService } from '@/main/data/database-service';
-import { SelectMessage } from '@/main/data/workspace/schema';
+import { SelectMessage } from '@/main/databases/workspace';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapMessage } from '@/main/utils';
import { MessageGetQueryInput } from '@/shared/queries/messages/message-get';
@@ -7,6 +7,7 @@ import { Event } from '@/shared/types/events';
import { MessageNode } from '@/shared/types/messages';
export class MessageGetQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<MessageGetQueryInput>
{
public async handleQuery(
@@ -23,7 +24,8 @@ export class MessageGetQueryHandler
): Promise<ChangeCheckResult<MessageGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -33,7 +35,8 @@ export class MessageGetQueryHandler
if (
event.type === 'message_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.message.id === input.messageId
) {
return {
@@ -44,7 +47,8 @@ export class MessageGetQueryHandler
if (
event.type === 'message_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.message.id === input.messageId
) {
return {
@@ -55,7 +59,8 @@ export class MessageGetQueryHandler
if (
event.type === 'message_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.message.id === input.messageId
) {
return {
@@ -72,11 +77,9 @@ export class MessageGetQueryHandler
private async fetchMessage(
input: MessageGetQueryInput
): Promise<SelectMessage | undefined> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const row = await workspaceDatabase
+ const row = await workspace.database
.selectFrom('messages')
.selectAll()
.where('id', '=', input.messageId)
diff --git a/apps/desktop/src/main/queries/messages/message-list.ts b/apps/desktop/src/main/queries/messages/message-list.ts
index 716ee08a..bab3991f 100644
--- a/apps/desktop/src/main/queries/messages/message-list.ts
+++ b/apps/desktop/src/main/queries/messages/message-list.ts
@@ -1,14 +1,15 @@
import { compareString } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { SelectMessage } from '@/main/data/workspace/schema';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapMessage } from '@/main/utils';
import { MessageListQueryInput } from '@/shared/queries/messages/message-list';
import { Event } from '@/shared/types/events';
import { MessageNode } from '@/shared/types/messages';
+import { SelectMessage } from '@/main/databases/workspace';
export class MessageListQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<MessageListQueryInput>
{
public async handleQuery(
@@ -25,7 +26,8 @@ export class MessageListQueryHandler
): Promise<ChangeCheckResult<MessageListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -35,7 +37,8 @@ export class MessageListQueryHandler
if (
event.type === 'message_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.message.parentId === input.conversationId
) {
const newResult = await this.handleQuery(input);
@@ -48,7 +51,8 @@ export class MessageListQueryHandler
if (
event.type === 'message_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.message.parentId === input.conversationId
) {
const message = output.find((message) => message.id === event.message.id);
@@ -69,7 +73,8 @@ export class MessageListQueryHandler
if (
event.type === 'message_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.message.parentId === input.conversationId
) {
const message = output.find((message) => message.id === event.message.id);
@@ -91,12 +96,10 @@ export class MessageListQueryHandler
private async fetchMesssages(
input: MessageListQueryInput
): Promise<SelectMessage[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const offset = (input.page - 1) * input.count;
- const messages = await workspaceDatabase
+ const messages = await workspace.database
.selectFrom('messages')
.selectAll()
.where('parent_id', '=', input.conversationId)
diff --git a/apps/desktop/src/main/queries/messages/message-reactions-get.ts b/apps/desktop/src/main/queries/messages/message-reactions-get.ts
index b0854c89..7abb1d5c 100644
--- a/apps/desktop/src/main/queries/messages/message-reactions-get.ts
+++ b/apps/desktop/src/main/queries/messages/message-reactions-get.ts
@@ -1,10 +1,10 @@
import { sql } from 'kysely';
-import { databaseService } from '@/main/data/database-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { MessageReactionsGetQueryInput } from '@/shared/queries/messages/message-reactions-get';
import { Event } from '@/shared/types/events';
import { MessageReactionsCount } from '@/shared/types/messages';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
interface MessageReactionsCountRow {
reaction: string;
@@ -13,6 +13,7 @@ interface MessageReactionsCountRow {
}
export class MessageReactionsGetQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<MessageReactionsGetQueryInput>
{
public async handleQuery(
@@ -28,7 +29,8 @@ export class MessageReactionsGetQueryHandler
): Promise<ChangeCheckResult<MessageReactionsGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -38,7 +40,8 @@ export class MessageReactionsGetQueryHandler
if (
event.type === 'message_reaction_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.messageReaction.messageId === input.messageId
) {
const newResult = await this.handleQuery(input);
@@ -51,7 +54,8 @@ export class MessageReactionsGetQueryHandler
if (
event.type === 'message_reaction_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.messageReaction.messageId === input.messageId
) {
const newResult = await this.handleQuery(input);
@@ -70,22 +74,20 @@ export class MessageReactionsGetQueryHandler
private async fetchMessageReactions(
input: MessageReactionsGetQueryInput
): Promise<MessageReactionsCount[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const result = await sql<MessageReactionsCountRow>`
SELECT
reaction,
COUNT(reaction) as count,
MAX(CASE
- WHEN collaborator_id = ${input.userId} THEN 1
+ WHEN collaborator_id = ${workspace.userId} THEN 1
ELSE 0
END) as reacted
FROM message_reactions
WHERE message_id = ${input.messageId} AND deleted_at IS NULL
GROUP BY reaction
- `.execute(workspaceDatabase);
+ `.execute(workspace.database);
if (result.rows.length === 0) {
return [];
diff --git a/apps/desktop/src/main/queries/records/record-list.ts b/apps/desktop/src/main/queries/records/record-list.ts
index 73a6424a..84da38cd 100644
--- a/apps/desktop/src/main/queries/records/record-list.ts
+++ b/apps/desktop/src/main/queries/records/record-list.ts
@@ -19,14 +19,15 @@ import {
} from '@colanode/core';
import { sql } from 'kysely';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapEntry } from '@/main/utils';
import { RecordListQueryInput } from '@/shared/queries/records/record-list';
import { Event } from '@/shared/types/events';
+import { SelectEntry } from '@/main/databases/workspace';
export class RecordListQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<RecordListQueryInput>
{
public async handleQuery(
@@ -43,7 +44,8 @@ export class RecordListQueryHandler
): Promise<ChangeCheckResult<RecordListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -53,7 +55,8 @@ export class RecordListQueryHandler
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'record'
) {
const newResult = await this.handleQuery(input);
@@ -63,7 +66,11 @@ export class RecordListQueryHandler
};
}
- if (event.type === 'entry_updated' && event.userId === input.userId) {
+ if (
+ event.type === 'entry_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
if (
event.entry.type === 'record' &&
event.entry.attributes.databaseId === input.databaseId
@@ -104,7 +111,11 @@ export class RecordListQueryHandler
}
}
- if (event.type === 'entry_deleted' && event.userId === input.userId) {
+ if (
+ event.type === 'entry_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
if (
event.entry.type === 'record' &&
event.entry.attributes.databaseId === input.databaseId
@@ -135,16 +146,13 @@ export class RecordListQueryHandler
private async fetchRecords(
input: RecordListQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
-
- const database = await this.fetchDatabase(input.userId, input.databaseId);
+ const database = await this.fetchDatabase(input);
const filterQuery = this.buildFiltersQuery(
input.filters,
database.attributes.fields
);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const orderByQuery = `ORDER BY ${input.sorts.length > 0 ? this.buildSortOrdersQuery(input.sorts, database.attributes.fields) : 'e."id" ASC'}`;
const offset = (input.page - 1) * input.count;
const query = sql<SelectEntry>`
@@ -154,9 +162,9 @@ export class RecordListQueryHandler
${sql.raw(orderByQuery)}
LIMIT ${sql.lit(input.count)}
OFFSET ${sql.lit(offset)}
- `.compile(workspaceDatabase);
+ `.compile(workspace.database);
- const result = await workspaceDatabase.executeQuery(query);
+ const result = await workspace.database.executeQuery(query);
return result.rows;
}
@@ -176,15 +184,13 @@ export class RecordListQueryHandler
};
private async fetchDatabase(
- userId: string,
- databaseId: string
+ input: RecordListQueryInput
): Promise<DatabaseEntry> {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const row = await workspaceDatabase
+ const row = await workspace.database
.selectFrom('entries')
- .where('id', '=', databaseId)
+ .where('id', '=', input.databaseId)
.selectAll()
.executeTakeFirst();
@@ -260,7 +266,7 @@ export class RecordListQueryHandler
}
};
- buildBooleanFilterQuery = (
+ private buildBooleanFilterQuery = (
filter: ViewFieldFilterAttributes,
field: BooleanFieldAttributes
): string | null => {
diff --git a/apps/desktop/src/main/queries/records/record-search.ts b/apps/desktop/src/main/queries/records/record-search.ts
index 5d79831b..1e876673 100644
--- a/apps/desktop/src/main/queries/records/record-search.ts
+++ b/apps/desktop/src/main/queries/records/record-search.ts
@@ -1,14 +1,15 @@
import { RecordEntry } from '@colanode/core';
import { sql } from 'kysely';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapEntry } from '@/main/utils';
import { RecordSearchQueryInput } from '@/shared/queries/records/record-search';
import { Event } from '@/shared/types/events';
+import { SelectEntry } from '@/main/databases/workspace';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
export class RecordSearchQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<RecordSearchQueryInput>
{
public async handleQuery(
@@ -29,7 +30,8 @@ export class RecordSearchQueryHandler
): Promise<ChangeCheckResult<RecordSearchQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -39,7 +41,8 @@ export class RecordSearchQueryHandler
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'record' &&
event.entry.attributes.databaseId === input.databaseId
) {
@@ -52,7 +55,8 @@ export class RecordSearchQueryHandler
if (
event.type === 'entry_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'record' &&
event.entry.attributes.databaseId === input.databaseId
) {
@@ -65,7 +69,8 @@ export class RecordSearchQueryHandler
if (
event.type === 'entry_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'record' &&
event.entry.attributes.databaseId === input.databaseId
) {
@@ -84,9 +89,7 @@ export class RecordSearchQueryHandler
private async searchRecords(
input: RecordSearchQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const exclude = input.exclude ?? [];
const query = sql<SelectEntry>`
@@ -104,21 +107,19 @@ export class RecordSearchQueryHandler
)})`
: sql``
}
- `.compile(workspaceDatabase);
+ `.compile(workspace.database);
- const result = await workspaceDatabase.executeQuery(query);
+ const result = await workspace.database.executeQuery(query);
return result.rows;
}
private async fetchRecords(
input: RecordSearchQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const exclude = input.exclude ?? [];
- return workspaceDatabase
+ return workspace.database
.selectFrom('entries')
.where('type', '=', 'record')
.where('parent_id', '=', input.databaseId)
diff --git a/apps/desktop/src/main/queries/servers/server-list.ts b/apps/desktop/src/main/queries/servers/server-list.ts
index 1904454a..8b1231a3 100644
--- a/apps/desktop/src/main/queries/servers/server-list.ts
+++ b/apps/desktop/src/main/queries/servers/server-list.ts
@@ -1,5 +1,5 @@
-import { SelectServer } from '@/main/data/app/schema';
-import { databaseService } from '@/main/data/database-service';
+import { SelectServer } from '@/main/databases/app';
+import { appService } from '@/main/services/app-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { ServerListQueryInput } from '@/shared/queries/servers/server-list';
import { Event } from '@/shared/types/events';
@@ -40,10 +40,7 @@ export class ServerListQueryHandler
}
private fetchServers(): Promise<SelectServer[]> {
- return databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .execute();
+ return appService.database.selectFrom('servers').selectAll().execute();
}
private mapServers = (rows: SelectServer[]): Server[] => {
diff --git a/apps/desktop/src/main/queries/spaces/space-list.ts b/apps/desktop/src/main/queries/spaces/space-list.ts
index 118d0b16..6c4ff491 100644
--- a/apps/desktop/src/main/queries/spaces/space-list.ts
+++ b/apps/desktop/src/main/queries/spaces/space-list.ts
@@ -1,13 +1,14 @@
import { SpaceEntry } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntry } from '@/main/data/workspace/schema';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapEntry } from '@/main/utils';
import { SpaceListQueryInput } from '@/shared/queries/spaces/space-list';
import { Event } from '@/shared/types/events';
+import { SelectEntry } from '@/main/databases/workspace';
export class SpaceListQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<SpaceListQueryInput>
{
public async handleQuery(input: SpaceListQueryInput): Promise<SpaceEntry[]> {
@@ -22,7 +23,8 @@ export class SpaceListQueryHandler
): Promise<ChangeCheckResult<SpaceListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -32,7 +34,8 @@ export class SpaceListQueryHandler
if (
event.type === 'entry_created' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'space'
) {
const newChildren = [...output, event.entry];
@@ -44,7 +47,8 @@ export class SpaceListQueryHandler
if (
event.type === 'entry_updated' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'space'
) {
const entry = output.find((entry) => entry.id === event.entry.id);
@@ -62,7 +66,8 @@ export class SpaceListQueryHandler
if (
event.type === 'entry_deleted' &&
- event.userId === input.userId &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
event.entry.type === 'space'
) {
const entry = output.find((entry) => entry.id === event.entry.id);
@@ -85,11 +90,9 @@ export class SpaceListQueryHandler
private async fetchChildren(
input: SpaceListQueryInput
): Promise<SelectEntry[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const rows = await workspaceDatabase
+ const rows = await workspace.database
.selectFrom('entries')
.selectAll()
.where('parent_id', 'is', null)
diff --git a/apps/desktop/src/main/queries/users/user-get.ts b/apps/desktop/src/main/queries/users/user-get.ts
index 0dd4478b..21184c69 100644
--- a/apps/desktop/src/main/queries/users/user-get.ts
+++ b/apps/desktop/src/main/queries/users/user-get.ts
@@ -1,12 +1,15 @@
-import { databaseService } from '@/main/data/database-service';
-import { SelectUser } from '@/main/data/workspace/schema';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapUser } from '@/main/utils';
import { UserGetQueryInput } from '@/shared/queries/users/user-get';
import { Event } from '@/shared/types/events';
import { User } from '@/shared/types/users';
+import { SelectUser } from '@/main/databases/workspace';
-export class UserGetQueryHandler implements QueryHandler<UserGetQueryInput> {
+export class UserGetQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<UserGetQueryInput>
+{
public async handleQuery(input: UserGetQueryInput): Promise<User | null> {
const row = await this.fetchUser(input);
return row ? mapUser(row) : null;
@@ -19,7 +22,8 @@ export class UserGetQueryHandler implements QueryHandler<UserGetQueryInput> {
): Promise<ChangeCheckResult<UserGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -29,8 +33,9 @@ export class UserGetQueryHandler implements QueryHandler<UserGetQueryInput> {
if (
event.type === 'user_created' &&
- event.userId === input.userId &&
- event.user.id === input.id
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.user.id === input.userId
) {
return {
hasChanges: true,
@@ -40,8 +45,9 @@ export class UserGetQueryHandler implements QueryHandler<UserGetQueryInput> {
if (
event.type === 'user_updated' &&
- event.userId === input.userId &&
- event.user.id === input.id
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.user.id === input.userId
) {
return {
hasChanges: true,
@@ -51,8 +57,9 @@ export class UserGetQueryHandler implements QueryHandler<UserGetQueryInput> {
if (
event.type === 'user_deleted' &&
- event.userId === input.userId &&
- event.user.id === input.id
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.user.id === input.userId
) {
return {
hasChanges: true,
@@ -68,14 +75,12 @@ export class UserGetQueryHandler implements QueryHandler<UserGetQueryInput> {
private async fetchUser(
input: UserGetQueryInput
): Promise<SelectUser | undefined> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const row = await workspaceDatabase
+ const row = await workspace.database
.selectFrom('users')
.selectAll()
- .where('id', '=', input.id)
+ .where('id', '=', input.userId)
.executeTakeFirst();
return row;
diff --git a/apps/desktop/src/main/queries/users/user-list.ts b/apps/desktop/src/main/queries/users/user-list.ts
index 741bb620..04a2616e 100644
--- a/apps/desktop/src/main/queries/users/user-list.ts
+++ b/apps/desktop/src/main/queries/users/user-list.ts
@@ -1,12 +1,15 @@
-import { databaseService } from '@/main/data/database-service';
-import { SelectUser } from '@/main/data/workspace/schema';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { SelectUser } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapUser } from '@/main/utils';
import { UserListQueryInput } from '@/shared/queries/users/user-list';
import { Event } from '@/shared/types/events';
import { User } from '@/shared/types/users';
-export class UserListQueryHandler implements QueryHandler<UserListQueryInput> {
+export class UserListQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<UserListQueryInput>
+{
public async handleQuery(input: UserListQueryInput): Promise<User[]> {
const rows = await this.fetchUsers(input);
return this.buildWorkspaceUserNodes(rows);
@@ -19,7 +22,8 @@ export class UserListQueryHandler implements QueryHandler<UserListQueryInput> {
): Promise<ChangeCheckResult<UserListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -27,7 +31,11 @@ export class UserListQueryHandler implements QueryHandler<UserListQueryInput> {
};
}
- if (event.type === 'user_created' && event.userId === input.userId) {
+ if (
+ event.type === 'user_created' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -35,8 +43,12 @@ export class UserListQueryHandler implements QueryHandler<UserListQueryInput> {
};
}
- if (event.type === 'user_updated' && event.userId === input.userId) {
- const user = output.find((user) => user.id === event.userId);
+ if (
+ event.type === 'user_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
+ const user = output.find((user) => user.id === event.user.id);
if (user) {
const newUsers = output.map((user) => {
if (user.id === event.user.id) {
@@ -52,7 +64,11 @@ export class UserListQueryHandler implements QueryHandler<UserListQueryInput> {
}
}
- if (event.type === 'user_deleted' && event.userId === input.userId) {
+ if (
+ event.type === 'user_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -66,12 +82,10 @@ export class UserListQueryHandler implements QueryHandler<UserListQueryInput> {
}
private async fetchUsers(input: UserListQueryInput): Promise<SelectUser[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const offset = (input.page - 1) * input.count;
- const rows = await workspaceDatabase
+ const rows = await workspace.database
.selectFrom('users')
.selectAll()
.orderBy('created_at asc')
diff --git a/apps/desktop/src/main/queries/users/user-search.ts b/apps/desktop/src/main/queries/users/user-search.ts
index 6e596919..c4e89f2b 100644
--- a/apps/desktop/src/main/queries/users/user-search.ts
+++ b/apps/desktop/src/main/queries/users/user-search.ts
@@ -1,7 +1,7 @@
import { sql } from 'kysely';
-import { databaseService } from '@/main/data/database-service';
-import { SelectUser } from '@/main/data/workspace/schema';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { SelectUser } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapUser } from '@/main/utils';
import { UserSearchQueryInput } from '@/shared/queries/users/user-search';
@@ -9,6 +9,7 @@ import { Event } from '@/shared/types/events';
import { User } from '@/shared/types/users';
export class UserSearchQueryHandler
+ extends WorkspaceQueryHandlerBase
implements QueryHandler<UserSearchQueryInput>
{
public async handleQuery(input: UserSearchQueryInput): Promise<User[]> {
@@ -27,7 +28,8 @@ export class UserSearchQueryHandler
): Promise<ChangeCheckResult<UserSearchQueryInput>> {
if (
event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
) {
return {
hasChanges: true,
@@ -35,7 +37,11 @@ export class UserSearchQueryHandler
};
}
- if (event.type === 'user_created' && event.userId === input.userId) {
+ if (
+ event.type === 'user_created' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -43,7 +49,11 @@ export class UserSearchQueryHandler
};
}
- if (event.type === 'user_updated' && event.userId === input.userId) {
+ if (
+ event.type === 'user_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -51,7 +61,11 @@ export class UserSearchQueryHandler
};
}
- if (event.type === 'user_deleted' && event.userId === input.userId) {
+ if (
+ event.type === 'user_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId
+ ) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -67,16 +81,14 @@ export class UserSearchQueryHandler
private async searchUsers(
input: UserSearchQueryInput
): Promise<SelectUser[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const exclude = input.exclude ?? [];
const query = sql<SelectUser>`
SELECT u.*
FROM users u
JOIN texts t ON u.id = t.id
- WHERE u.id != ${input.userId}
+ WHERE u.id != ${workspace.userId}
AND t.name MATCH ${input.searchQuery + '*'}
${
exclude.length > 0
@@ -86,21 +98,19 @@ export class UserSearchQueryHandler
)})`
: sql``
}
- `.compile(workspaceDatabase);
+ `.compile(workspace.database);
- const result = await workspaceDatabase.executeQuery(query);
+ const result = await workspace.database.executeQuery(query);
return result.rows;
}
private async fetchUsers(input: UserSearchQueryInput): Promise<SelectUser[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const exclude = input.exclude ?? [];
- return workspaceDatabase
+ return workspace.database
.selectFrom('users')
- .where('id', '!=', input.userId)
+ .where('id', '!=', workspace.userId)
.where('id', 'not in', exclude)
.selectAll()
.execute();
diff --git a/apps/desktop/src/main/queries/workspace-query-handler-base.ts b/apps/desktop/src/main/queries/workspace-query-handler-base.ts
new file mode 100644
index 00000000..b0f38a96
--- /dev/null
+++ b/apps/desktop/src/main/queries/workspace-query-handler-base.ts
@@ -0,0 +1,28 @@
+import { appService } from '@/main/services/app-service';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { QueryError, QueryErrorCode } from '@/shared/queries';
+
+export abstract class WorkspaceQueryHandlerBase {
+ protected getWorkspace(
+ accountId: string,
+ workspaceId: string
+ ): WorkspaceService {
+ const account = appService.getAccount(accountId);
+ if (!account) {
+ throw new QueryError(
+ QueryErrorCode.AccountNotFound,
+ 'Account not found or has been logged out already. Try closing the app and opening it again.'
+ );
+ }
+
+ const workspace = account.getWorkspace(workspaceId);
+ if (!workspace) {
+ throw new QueryError(
+ QueryErrorCode.WorkspaceNotFound,
+ 'Workspace not found or has been deleted.'
+ );
+ }
+
+ return workspace;
+ }
+}
diff --git a/apps/desktop/src/main/queries/workspaces/workspace-get.ts b/apps/desktop/src/main/queries/workspaces/workspace-get.ts
index 25e46683..90ffb8d8 100644
--- a/apps/desktop/src/main/queries/workspaces/workspace-get.ts
+++ b/apps/desktop/src/main/queries/workspaces/workspace-get.ts
@@ -1,10 +1,10 @@
-import { SelectWorkspace } from '@/main/data/app/schema';
-import { databaseService } from '@/main/data/database-service';
+import { SelectWorkspace } from '@/main/databases/account';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapWorkspace } from '@/main/utils';
import { WorkspaceGetQueryInput } from '@/shared/queries/workspaces/workspace-get';
import { Event } from '@/shared/types/events';
import { Workspace } from '@/shared/types/workspaces';
+import { appService } from '@/main/services/app-service';
export class WorkspaceGetQueryHandler
implements QueryHandler<WorkspaceGetQueryInput>
@@ -63,15 +63,21 @@ export class WorkspaceGetQueryHandler
};
}
- private fetchWorkspace(
+ private async fetchWorkspace(
accountId: string,
workspaceId: string
): Promise<SelectWorkspace | undefined> {
- return databaseService.appDatabase
+ const account = appService.getAccount(accountId);
+ if (!account) {
+ return undefined;
+ }
+
+ const workspace = await account.database
.selectFrom('workspaces')
.selectAll()
- .where('account_id', '=', accountId)
- .where('workspace_id', '=', workspaceId)
+ .where('id', '=', workspaceId)
.executeTakeFirst();
+
+ return workspace;
}
}
diff --git a/apps/desktop/src/main/queries/workspaces/workspace-list.ts b/apps/desktop/src/main/queries/workspaces/workspace-list.ts
index 77e87c4b..c5f39ee6 100644
--- a/apps/desktop/src/main/queries/workspaces/workspace-list.ts
+++ b/apps/desktop/src/main/queries/workspaces/workspace-list.ts
@@ -1,5 +1,5 @@
-import { SelectWorkspace } from '@/main/data/app/schema';
-import { databaseService } from '@/main/data/database-service';
+import { SelectWorkspace } from '@/main/databases/account';
+import { appService } from '@/main/services/app-service';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
import { mapWorkspace } from '@/main/utils';
import { WorkspaceListQueryInput } from '@/shared/queries/workspaces/workspace-list';
@@ -68,11 +68,17 @@ export class WorkspaceListQueryHandler
};
}
- private fetchWorkspaces(accountId: string): Promise<SelectWorkspace[]> {
- return databaseService.appDatabase
+ private async fetchWorkspaces(accountId: string): Promise<SelectWorkspace[]> {
+ const account = appService.getAccount(accountId);
+ if (!account) {
+ return [];
+ }
+
+ const workspaces = await account.database
.selectFrom('workspaces')
.selectAll()
- .where('account_id', '=', accountId)
.execute();
+
+ return workspaces;
}
}
diff --git a/apps/desktop/src/main/scheduler.ts b/apps/desktop/src/main/scheduler.ts
deleted file mode 100644
index fa8f4389..00000000
--- a/apps/desktop/src/main/scheduler.ts
+++ /dev/null
@@ -1,415 +0,0 @@
-import { sha256 } from 'js-sha256';
-import { createDebugger } from '@colanode/core';
-
-import { socketService } from '@/main/services/socket-service';
-import { radarService } from '@/main/services/radar-service';
-import { databaseService } from '@/main/data/database-service';
-import { JobHandler, JobInput, JobMap } from '@/main/jobs';
-import { SyncServersJobHandler } from '@/main/jobs/sync-servers';
-import { SyncAccountJobHandler } from '@/main/jobs/sync-account';
-import { InitSynchronizersJobHandler } from '@/main/jobs/init-synchronizers';
-import { RevertInvalidMutationsJobHandler } from '@/main/jobs/revert-invalid-mutations';
-import { SyncPendingMutationsJobHandler } from '@/main/jobs/sync-pending-mutations';
-import { SyncDeletedTokensJobHandler } from '@/main/jobs/sync-deleted-tokens';
-import { ConnectSocketJobHandler } from '@/main/jobs/connect-socket';
-import { UploadFilesJobHandler } from '@/main/jobs/upload-files';
-import { DownloadFilesJobHandler } from '@/main/jobs/download-files';
-import { CleanDeletedFilesJobHandler } from '@/main/jobs/clean-deleted-files';
-import { CleanTempFilesJobHandler } from '@/main/jobs/clean-temp-files';
-import { eventBus } from '@/shared/lib/event-bus';
-import { Event } from '@/shared/types/events';
-
-type JobHandlerMap = {
- [K in keyof JobMap]: JobHandler<JobMap[K]['input']>;
-};
-
-export const jobHandlerMap: JobHandlerMap = {
- sync_servers: new SyncServersJobHandler(),
- sync_account: new SyncAccountJobHandler(),
- init_synchronizers: new InitSynchronizersJobHandler(),
- revert_invalid_mutations: new RevertInvalidMutationsJobHandler(),
- sync_pending_mutations: new SyncPendingMutationsJobHandler(),
- sync_deleted_tokens: new SyncDeletedTokensJobHandler(),
- connect_socket: new ConnectSocketJobHandler(),
- upload_files: new UploadFilesJobHandler(),
- download_files: new DownloadFilesJobHandler(),
- clean_deleted_files: new CleanDeletedFilesJobHandler(),
- clean_temp_files: new CleanTempFilesJobHandler(),
-};
-
-type JobState = {
- id: string;
- input: JobMap[keyof JobMap]['input'];
- running: boolean;
- triggered: boolean;
- handler: JobHandler<JobMap[keyof JobMap]['input']>;
- timeout: NodeJS.Timeout | null;
-};
-
-class Scheduler {
- private readonly debug = createDebugger('desktop:scheduler');
- private initPromise: Promise<void> | null = null;
- private initialized = false;
-
- private states: Map<string, JobState> = new Map();
-
- constructor() {
- eventBus.subscribe((event) => {
- this.handleEvent(event);
- });
- }
-
- public init() {
- if (!this.initPromise) {
- this.initPromise = this.executeInit();
- }
-
- return this.initPromise;
- }
-
- private async executeInit() {
- this.debug('Initializing scheduler');
- await databaseService.init();
- await this.scheduleJobs();
- radarService.init();
-
- this.initialized = true;
- this.debug('Scheduler initialized');
- }
-
- public schedule(input: JobInput) {
- const id = sha256(JSON.stringify(input));
-
- if (this.states.has(id)) {
- this.trigger(input);
- return;
- }
-
- const handler = jobHandlerMap[input.type] as JobHandler<
- JobMap[keyof JobMap]['input']
- >;
-
- if (!handler) {
- this.debug(`No handler found for job type: ${input.type}`);
- return;
- }
-
- const state: JobState = {
- id,
- input,
- running: false,
- triggered: false,
- handler,
- timeout: null,
- };
-
- state.timeout = setTimeout(() => {
- this.executeJob(state);
- }, 0);
-
- this.states.set(id, state);
- }
-
- public trigger(input: JobInput) {
- const id = sha256(JSON.stringify(input));
- const state = this.states.get(id);
- if (!state) {
- return;
- }
-
- if (state.running) {
- state.triggered = true;
- return;
- }
-
- if (state.timeout) {
- clearTimeout(state.timeout);
- }
-
- state.timeout = setTimeout(() => {
- this.executeJob(state);
- }, state.handler.triggerDebounce);
- }
-
- private async executeJob(state: JobState) {
- if (!this.states.has(state.id)) {
- this.deleteJob(state);
- return;
- }
-
- if (state.running) {
- return;
- }
-
- state.running = true;
- state.triggered = false;
-
- if (state.timeout) {
- clearTimeout(state.timeout);
- }
-
- try {
- await state.handler.handleJob(state.input);
- } catch (error) {
- this.debug(error, `Error executing job: ${state.input.type}`);
- } finally {
- state.running = false;
-
- if (state.timeout) {
- clearTimeout(state.timeout);
- }
-
- if (state.triggered) {
- state.timeout = setTimeout(() => {
- this.executeJob(state);
- }, state.handler.triggerDebounce);
- } else if (state.handler.interval > 0) {
- state.timeout = setTimeout(() => {
- this.executeJob(state);
- }, state.handler.interval);
- }
- }
- }
-
- private async deleteJob(state: JobState) {
- if (state.timeout) {
- clearTimeout(state.timeout);
- }
-
- this.states.delete(state.id);
- }
-
- private async scheduleJobs() {
- this.schedule({ type: 'sync_servers' });
- this.schedule({ type: 'sync_deleted_tokens' });
- }
-
- private async scheduleServerAccountsJobs(domain: string) {
- const accounts = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('server', '=', domain)
- .execute();
-
- for (const account of accounts) {
- this.scheduleAccountJobs(account.id);
- }
- }
-
- private scheduleAccountJobs(accountId: string) {
- this.schedule({ type: 'sync_account', accountId });
- this.schedule({ type: 'connect_socket', accountId });
- }
-
- private deleteAccountJobs(accountId: string) {
- const jobIds = Array.from(this.states.keys());
-
- for (const jobId of jobIds) {
- const state = this.states.get(jobId);
- if (!state) {
- continue;
- }
-
- if (
- state.input.type === 'sync_account' &&
- state.input.accountId === accountId
- ) {
- this.deleteJob(state);
- } else if (
- state.input.type === 'connect_socket' &&
- state.input.accountId === accountId
- ) {
- this.deleteJob(state);
- }
- }
- }
-
- private async scheduleAccountWorkspacesJobs(accountId: string) {
- const workspaces = await databaseService.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .where('account_id', '=', accountId)
- .execute();
-
- for (const workspace of workspaces) {
- this.scheduleWorkspaceJobs(accountId, workspace.user_id);
- }
- }
-
- private scheduleWorkspaceJobs(accountId: string, userId: string) {
- this.debug(
- `Scheduling workspace jobs for account: ${accountId}, user: ${userId}`
- );
-
- const isSocketConnected = socketService.isConnected(accountId);
- if (!isSocketConnected) {
- this.debug(
- `Socket is not connected for account: ${accountId}, skipping scheduling`
- );
- return;
- }
-
- this.schedule({
- type: 'sync_pending_mutations',
- userId,
- });
-
- this.schedule({
- type: 'revert_invalid_mutations',
- userId,
- });
-
- this.schedule({
- type: 'init_synchronizers',
- userId,
- });
-
- this.schedule({
- type: 'upload_files',
- userId,
- });
-
- this.schedule({
- type: 'download_files',
- userId,
- });
-
- this.schedule({
- type: 'clean_deleted_files',
- userId,
- });
-
- this.schedule({
- type: 'clean_temp_files',
- userId,
- });
- }
-
- private deleteWorkspaceJobs(userId: string) {
- const jobIds = Array.from(this.states.keys());
-
- for (const jobId of jobIds) {
- const state = this.states.get(jobId);
- if (!state) {
- continue;
- }
-
- if (this.isWorkspaceJob(state, userId)) {
- this.deleteJob(state);
- }
- }
- }
-
- private isWorkspaceJob(state: JobState, userId: string) {
- if (
- state.input.type === 'init_synchronizers' &&
- state.input.userId === userId
- ) {
- return true;
- }
-
- if (
- state.input.type === 'sync_pending_mutations' &&
- state.input.userId === userId
- ) {
- return true;
- }
-
- if (
- state.input.type === 'revert_invalid_mutations' &&
- state.input.userId === userId
- ) {
- return true;
- }
-
- if (state.input.type === 'upload_files' && state.input.userId === userId) {
- return true;
- }
-
- if (
- state.input.type === 'download_files' &&
- state.input.userId === userId
- ) {
- return true;
- }
-
- if (
- state.input.type === 'clean_deleted_files' &&
- state.input.userId === userId
- ) {
- return true;
- }
-
- if (
- state.input.type === 'clean_temp_files' &&
- state.input.userId === userId
- ) {
- return true;
- }
-
- return false;
- }
-
- private handleEvent(event: Event) {
- if (!this.initialized) {
- return;
- }
-
- if (event.type === 'server_availability_changed' && event.isAvailable) {
- this.scheduleServerAccountsJobs(event.server.domain);
- } else if (event.type === 'server_created') {
- this.scheduleServerAccountsJobs(event.server.domain);
- } else if (event.type === 'account_created') {
- this.scheduleAccountJobs(event.account.id);
- } else if (event.type === 'account_deleted') {
- this.trigger({
- type: 'sync_deleted_tokens',
- });
- this.deleteAccountJobs(event.account.id);
- } else if (event.type === 'workspace_created') {
- this.scheduleWorkspaceJobs(
- event.workspace.accountId,
- event.workspace.userId
- );
- } else if (event.type === 'workspace_deleted') {
- this.deleteWorkspaceJobs(event.workspace.userId);
- } else if (event.type === 'socket_connection_opened') {
- this.scheduleAccountWorkspacesJobs(event.accountId);
- } else if (event.type === 'mutation_created') {
- this.trigger({
- type: 'sync_pending_mutations',
- userId: event.userId,
- });
- } else if (event.type === 'file_state_created') {
- this.trigger({
- type: 'upload_files',
- userId: event.userId,
- });
- this.trigger({
- type: 'download_files',
- userId: event.userId,
- });
- } else if (event.type === 'file_updated') {
- this.trigger({
- type: 'upload_files',
- userId: event.userId,
- });
- this.trigger({
- type: 'download_files',
- userId: event.userId,
- });
- } else if (event.type === 'file_deleted') {
- this.trigger({
- type: 'clean_deleted_files',
- userId: event.userId,
- });
- } else if (event.type === 'collaboration_created') {
- this.trigger({
- type: 'init_synchronizers',
- userId: event.userId,
- });
- }
- }
-}
-
-export const scheduler = new Scheduler();
diff --git a/apps/desktop/src/main/services/account-service.ts b/apps/desktop/src/main/services/account-service.ts
deleted file mode 100644
index 8ddbb6ca..00000000
--- a/apps/desktop/src/main/services/account-service.ts
+++ /dev/null
@@ -1,393 +0,0 @@
-import {
- AccountSyncOutput,
- ApiErrorCode,
- ApiErrorOutput,
- LoginSuccessOutput,
- createDebugger,
-} from '@colanode/core';
-
-import { app } from 'electron';
-import fs from 'fs';
-
-import { SelectAccount } from '@/main/data/app/schema';
-import { databaseService } from '@/main/data/database-service';
-import { serverService } from '@/main/services/server-service';
-import {
- getAccountAvatarsDirectoryPath,
- getWorkspaceDirectoryPath,
- mapAccount,
- mapWorkspace,
-} from '@/main/utils';
-import { eventBus } from '@/shared/lib/event-bus';
-import { httpClient } from '@/shared/lib/http-client';
-import { socketService } from '@/main/services/socket-service';
-import { MutationError, MutationErrorCode } from '@/shared/mutations';
-import { parseApiError } from '@/shared/lib/axios';
-
-class AccountService {
- private readonly debug = createDebugger('desktop:service:account');
-
- public async initAccount(output: LoginSuccessOutput, server: string) {
- const { createdAccount, createdWorkspaces } =
- await databaseService.appDatabase.transaction().execute(async (trx) => {
- const createdAccount = await trx
- .insertInto('accounts')
- .returningAll()
- .values({
- id: output.account.id,
- name: output.account.name,
- avatar: output.account.avatar,
- device_id: output.deviceId,
- email: output.account.email,
- token: output.token,
- server,
- })
- .executeTakeFirst();
-
- if (!createdAccount) {
- throw new MutationError(
- MutationErrorCode.AccountLoginFailed,
- 'Failed to login with email and password! Please try again.'
- );
- }
-
- if (output.workspaces.length === 0) {
- return { createdAccount, createdWorkspaces: [] };
- }
-
- const createdWorkspaces = await trx
- .insertInto('workspaces')
- .returningAll()
- .values(
- output.workspaces.map((workspace) => ({
- workspace_id: workspace.id,
- name: workspace.name,
- account_id: output.account.id,
- avatar: workspace.avatar,
- role: workspace.user.role,
- description: workspace.description,
- user_id: workspace.user.id,
- }))
- )
- .execute();
-
- return { createdAccount, createdWorkspaces };
- });
-
- if (!createdAccount) {
- throw new MutationError(
- MutationErrorCode.AccountLoginFailed,
- 'Failed to login with email and password! Please try again.'
- );
- }
-
- const account = mapAccount(createdAccount);
- eventBus.publish({
- type: 'account_created',
- account,
- });
-
- if (createdWorkspaces.length > 0) {
- for (const workspace of createdWorkspaces) {
- eventBus.publish({
- type: 'workspace_created',
- workspace: mapWorkspace(workspace),
- });
- }
- }
- }
-
- public async syncAccount(accountId: string) {
- this.debug(`Syncing account ${accountId}`);
-
- const account = await databaseService.appDatabase
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', accountId)
- .executeTakeFirst();
-
- if (!account) {
- this.debug(`Account ${accountId} not found`);
- return;
- }
-
- const server = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .where('domain', '=', account.server)
- .executeTakeFirst();
-
- if (!server) {
- this.debug(
- `Server ${account.server} not found for syncing account ${account.email}`
- );
- return;
- }
-
- if (!serverService.isAvailable(server.domain)) {
- this.debug(
- `Server ${server.domain} is not available for syncing account ${account.email}`
- );
- return;
- }
-
- try {
- const { data, status } = await httpClient.post<AccountSyncOutput>(
- '/v1/accounts/sync',
- {
- platform: process.platform,
- version: app.getVersion(),
- },
- {
- domain: server.domain,
- token: account.token,
- }
- );
-
- this.debug(`Account sync response status code: ${status}`);
-
- if (status >= 400 && status < 500) {
- this.debug(`Account ${account.email} is not valid, logging out...`);
- await this.logoutAccount(account);
- return;
- }
-
- if (status !== 200) {
- return;
- }
-
- const currentWorkspaces = await databaseService.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .where('account_id', '=', account.id)
- .execute();
-
- if (
- data.account.name !== account.name ||
- data.account.avatar !== account.avatar
- ) {
- const updatedAccount = await databaseService.appDatabase
- .updateTable('accounts')
- .returningAll()
- .set({
- name: data.account.name,
- avatar: data.account.avatar,
- })
- .where('id', '=', account.id)
- .executeTakeFirst();
-
- if (!updatedAccount) {
- this.debug(`Failed to update account ${account.email} after sync`);
- return;
- } else {
- this.debug(`Updated account ${account.email} after sync`);
- }
-
- eventBus.publish({
- type: 'account_updated',
- account: mapAccount(updatedAccount),
- });
- }
-
- for (const workspace of data.workspaces) {
- const currentWorkspace = currentWorkspaces.find(
- (w) => w.workspace_id === workspace.id
- );
-
- if (!currentWorkspace) {
- // create workspace here
- const createdWorkspace = await databaseService.appDatabase
- .insertInto('workspaces')
- .values({
- workspace_id: workspace.id,
- user_id: workspace.user.id,
- account_id: account.id,
- name: workspace.name,
- avatar: workspace.avatar,
- description: workspace.description,
- role: workspace.user.role,
- })
- .returningAll()
- .executeTakeFirst();
-
- if (!createdWorkspace) {
- this.debug(
- `Failed to create workspace ${workspace.id} for account ${account.email}`
- );
- return;
- } else {
- this.debug(
- `Created workspace ${workspace.id} for account ${account.email} after sync`
- );
- }
-
- eventBus.publish({
- type: 'workspace_created',
- workspace: mapWorkspace(createdWorkspace),
- });
- } else {
- // update workspace here
- const updatedWorkspace = await databaseService.appDatabase
- .updateTable('workspaces')
- .returningAll()
- .set({
- name: workspace.name,
- avatar: workspace.avatar,
- description: workspace.description,
- role: workspace.user.role,
- })
- .where('user_id', '=', currentWorkspace.user_id)
- .executeTakeFirst();
-
- if (!updatedWorkspace) {
- this.debug(
- `Failed to update workspace ${currentWorkspace.user_id} for account ${account.email}`
- );
- return;
- } else {
- this.debug(
- `Updated workspace ${currentWorkspace.user_id} for account ${account.email} after sync`
- );
- }
-
- eventBus.publish({
- type: 'workspace_updated',
- workspace: mapWorkspace(updatedWorkspace),
- });
- }
- }
-
- for (const workspace of currentWorkspaces) {
- const updatedWorkspace = data.workspaces.find(
- (w) => w.id === workspace.workspace_id
- );
-
- if (!updatedWorkspace) {
- await this.deleteWorkspace(workspace.user_id);
- }
- }
- } catch (error) {
- const parsedError = parseApiError(error);
- if (this.isSyncInvalid(parsedError)) {
- this.debug(`Account ${account.email} is not valid, logging out...`);
- await this.logoutAccount(account);
- return;
- }
-
- this.debug(`Failed to sync account ${account.email}: ${parsedError}`);
- }
- }
-
- public async logoutAccount(account: SelectAccount): Promise<boolean> {
- this.debug(`Logging out account ${account.email}`);
-
- const workspaces = await databaseService.appDatabase
- .selectFrom('workspaces')
- .select(['user_id'])
- .where('account_id', '=', account.id)
- .execute();
-
- for (const workspace of workspaces) {
- await this.deleteWorkspace(workspace.user_id);
- }
-
- const avatarsDir = getAccountAvatarsDirectoryPath(account.id);
- if (fs.existsSync(avatarsDir)) {
- fs.rmSync(avatarsDir, { recursive: true });
- }
-
- const deletedAccount = await databaseService.appDatabase
- .deleteFrom('accounts')
- .returningAll()
- .where('id', '=', account.id)
- .executeTakeFirst();
-
- if (!deletedAccount) {
- this.debug(`Failed to delete account ${account.email}`);
- return false;
- } else {
- this.debug(`Deleted account ${account.email}`);
- }
-
- eventBus.publish({
- type: 'account_deleted',
- account: mapAccount(deletedAccount),
- });
-
- await databaseService.appDatabase
- .insertInto('deleted_tokens')
- .values({
- token: account.token,
- account_id: account.id,
- server: account.server,
- created_at: new Date().toISOString(),
- })
- .execute();
-
- socketService.removeConnection(account.id);
-
- return true;
- }
-
- private async deleteWorkspace(userId: string): Promise<boolean> {
- this.debug(`Deleting workspace ${userId}`);
-
- const deletedWorkspace = await databaseService.appDatabase
- .deleteFrom('workspaces')
- .returningAll()
- .where('user_id', '=', userId)
- .executeTakeFirst();
-
- if (!deletedWorkspace) {
- this.debug(`Failed to delete workspace ${userId}`);
- return false;
- }
-
- await databaseService.removeWorkspaceDatabase(userId);
- const workspaceDir = getWorkspaceDirectoryPath(userId);
-
- let deleted = false;
- for (let attempt = 1; attempt <= 10; attempt++) {
- try {
- if (fs.existsSync(workspaceDir)) {
- fs.rmSync(workspaceDir, { recursive: true, force: true });
- deleted = true;
- break;
- }
- } catch (error) {
- this.debug(
- `Failed to delete workspace directory ${workspaceDir} on attempt ${attempt}`,
- error
- );
- if (attempt === 10) {
- break;
- }
- await new Promise((resolve) => setTimeout(resolve, 1000));
- }
- }
-
- if (deleted) {
- this.debug(`Deleted workspace directory ${workspaceDir}`);
- } else {
- this.debug(`Failed to delete workspace directory ${workspaceDir}`);
- }
-
- eventBus.publish({
- type: 'workspace_deleted',
- workspace: mapWorkspace(deletedWorkspace),
- });
-
- return true;
- }
-
- private isSyncInvalid(error: ApiErrorOutput) {
- return (
- error.code === ApiErrorCode.TokenInvalid ||
- error.code === ApiErrorCode.TokenMissing ||
- error.code === ApiErrorCode.AccountNotFound ||
- error.code === ApiErrorCode.DeviceNotFound
- );
- }
-}
-
-export const accountService = new AccountService();
diff --git a/apps/desktop/src/main/services/accounts/account-client.ts b/apps/desktop/src/main/services/accounts/account-client.ts
new file mode 100644
index 00000000..755612fd
--- /dev/null
+++ b/apps/desktop/src/main/services/accounts/account-client.ts
@@ -0,0 +1,98 @@
+import axios, {
+ AxiosError,
+ AxiosInstance,
+ AxiosRequestConfig,
+ AxiosResponse,
+ isAxiosError,
+} from 'axios';
+import { createDebugger } from '@colanode/core';
+
+import { AccountService } from '@/main/services/accounts/account-service';
+import { BackoffCalculator } from '@/shared/lib/backoff-calculator';
+
+export class AccountClient {
+ private readonly debug = createDebugger('desktop:service:account');
+ private readonly backoff: BackoffCalculator = new BackoffCalculator();
+ private readonly axiosInstance: AxiosInstance;
+ private readonly account: AccountService;
+
+ constructor(account: AccountService) {
+ this.account = account;
+ this.axiosInstance = axios.create({
+ baseURL: this.account.server.apiBaseUrl,
+ });
+ }
+
+ private async request<T>(
+ method: 'get' | 'post' | 'put' | 'delete',
+ path: string,
+ config: AxiosRequestConfig = {}
+ ): Promise<AxiosResponse<T>> {
+ if (!this.backoff.canRetry()) {
+ throw new Error(`Backoff in progress for account: ${this.account.id}`);
+ }
+
+ try {
+ this.debug(`Requesting ${method} ${path} for account ${this.account.id}`);
+
+ const headers = {
+ ...config.headers,
+ Authorization: `Bearer ${this.account.token}`,
+ };
+
+ const response = await this.axiosInstance.request<T>({
+ method,
+ url: path,
+ ...config,
+ headers,
+ });
+
+ this.backoff.reset();
+ return response;
+ } catch (error) {
+ this.debug(`Error in request for account ${this.account.id}: ${error}`);
+ if (isAxiosError(error) && this.isServerError(error)) {
+ this.backoff.increaseError();
+ }
+ throw error;
+ }
+ }
+
+ public async get<T>(
+ path: string,
+ config?: AxiosRequestConfig
+ ): Promise<AxiosResponse<T>> {
+ return this.request<T>('get', path, config);
+ }
+
+ public async post<T>(
+ path: string,
+ data: unknown,
+ config?: AxiosRequestConfig
+ ): Promise<AxiosResponse<T>> {
+ return this.request<T>('post', path, { ...config, data });
+ }
+
+ public async put<T>(
+ path: string,
+ data: unknown,
+ config?: AxiosRequestConfig
+ ): Promise<AxiosResponse<T>> {
+ return this.request<T>('put', path, { ...config, data });
+ }
+
+ public async delete<T>(
+ path: string,
+ config?: AxiosRequestConfig
+ ): Promise<AxiosResponse<T>> {
+ return this.request<T>('delete', path, config);
+ }
+
+ private isServerError(error: AxiosError): boolean {
+ if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
+ return true;
+ }
+ const status = error.response?.status ?? 0;
+ return status >= 500 && status < 600;
+ }
+}
diff --git a/apps/desktop/src/main/services/socket-connection.ts b/apps/desktop/src/main/services/accounts/account-connection.ts
similarity index 58%
rename from apps/desktop/src/main/services/socket-connection.ts
rename to apps/desktop/src/main/services/accounts/account-connection.ts
index 98d4e1be..44c09f07 100644
--- a/apps/desktop/src/main/services/socket-connection.ts
+++ b/apps/desktop/src/main/services/accounts/account-connection.ts
@@ -1,30 +1,46 @@
import { Message, createDebugger } from '@colanode/core';
import { WebSocket } from 'ws';
+import ms from 'ms';
+
+import { EventEmitter } from 'events';
-import { scheduler } from '@/main/scheduler';
-import { SelectAccount } from '@/main/data/app/schema';
-import { syncService } from '@/main/services/sync-service';
import { BackoffCalculator } from '@/shared/lib/backoff-calculator';
-import { eventBus } from '@/shared/lib/event-bus';
+import { AccountService } from '@/main/services/accounts/account-service';
+import { EventLoop } from '@/shared/lib/event-loop';
-export class SocketConnection {
- private readonly debug = createDebugger('service:socket-connection');
+export class AccountConnection extends EventEmitter {
+ private readonly debug = createDebugger('service:account-connection');
+ private readonly account: AccountService;
+ private readonly eventLoop: EventLoop;
- private readonly synapseUrl: string;
- private readonly account: SelectAccount;
private socket: WebSocket | null;
private backoffCalculator: BackoffCalculator;
private closingCount: number;
- constructor(synapseUrl: string, account: SelectAccount) {
- this.synapseUrl = synapseUrl;
- this.account = account;
+ constructor(accountService: AccountService) {
+ super();
+
+ this.account = accountService;
this.socket = null;
this.backoffCalculator = new BackoffCalculator();
this.closingCount = 0;
+
+ this.eventLoop = new EventLoop(ms('1 minute'), ms('1 second'), () => {
+ this.checkConnection();
+ });
+
+ this.account.server.on('availability_change', () => {
+ this.eventLoop.trigger();
+ });
}
public init(): void {
+ this.eventLoop.start();
+
+ if (!this.account.server.isAvailable()) {
+ return;
+ }
+
this.debug(`Initializing socket connection for account ${this.account.id}`);
if (this.socket && this.isConnected()) {
@@ -36,66 +52,40 @@ export class SocketConnection {
return;
}
- this.socket = new WebSocket(this.synapseUrl, {
+ this.socket = new WebSocket(this.account.server.synapseUrl, {
headers: {
authorization: this.account.token,
},
});
this.socket.onmessage = async (event) => {
- let data: string;
-
- if (typeof event.data === 'string') {
- data = event.data;
- } else if (event.data instanceof ArrayBuffer) {
- data = new TextDecoder().decode(event.data);
- } else {
- console.error('Unsupported message data type:', typeof event.data);
- return;
- }
+ const data: string = event.data.toString();
const message: Message = JSON.parse(data);
+
this.debug(
`Received message of type ${message.type} for account ${this.account.id}`
);
- if (message.type === 'synchronizer_output') {
- syncService.processSyncMessage(message);
- } else if (message.type === 'account_updated') {
- scheduler.trigger({
- type: 'sync_account',
- accountId: this.account.id,
- });
- } else if (message.type === 'workspace_updated') {
- scheduler.trigger({
- type: 'sync_account',
- accountId: this.account.id,
- });
- } else if (message.type === 'workspace_deleted') {
- scheduler.trigger({
- type: 'sync_account',
- accountId: this.account.id,
- });
- }
+ this.emit('message', message);
};
this.socket.onopen = () => {
this.debug(`Socket connection for account ${this.account.id} opened`);
this.backoffCalculator.reset();
- eventBus.publish({
- type: 'socket_connection_opened',
- accountId: this.account.id,
- });
+ this.emit('open');
};
this.socket.onerror = () => {
this.debug(`Socket connection for account ${this.account.id} errored`);
this.backoffCalculator.increaseError();
+ this.emit('close');
};
this.socket.onclose = () => {
this.debug(`Socket connection for account ${this.account.id} closed`);
this.backoffCalculator.increaseError();
+ this.emit('close');
};
}
@@ -103,7 +93,7 @@ export class SocketConnection {
return this.socket !== null && this.socket.readyState === WebSocket.OPEN;
}
- public sendMessage(message: Message): boolean {
+ public send(message: Message): boolean {
if (this.socket && this.isConnected()) {
this.debug(
`Sending message of type ${message.type} for account ${this.account.id}`
@@ -122,9 +112,17 @@ export class SocketConnection {
this.socket.close();
this.socket = null;
}
+
+ this.removeAllListeners();
+ this.eventLoop.stop();
}
- public checkConnection(): void {
+ private checkConnection(): void {
+ this.debug(`Checking connection for account ${this.account.id}`);
+ if (!this.account.server.isAvailable()) {
+ return;
+ }
+
if (this.isConnected()) {
this.socket?.ping();
return;
diff --git a/apps/desktop/src/main/services/accounts/account-service.ts b/apps/desktop/src/main/services/accounts/account-service.ts
new file mode 100644
index 00000000..fd198966
--- /dev/null
+++ b/apps/desktop/src/main/services/accounts/account-service.ts
@@ -0,0 +1,324 @@
+import {
+ AccountSyncOutput,
+ ApiErrorCode,
+ ApiErrorOutput,
+ createDebugger,
+ Message,
+} from '@colanode/core';
+import { Kysely, Migration, Migrator, SqliteDialect } from 'kysely';
+import SQLite from 'better-sqlite3';
+import ms from 'ms';
+
+import fs from 'fs';
+import path from 'path';
+
+import { ServerService } from '@/main/services/server-service';
+import {
+ AccountDatabaseSchema,
+ accountDatabaseMigrations,
+} from '@/main/databases/account';
+import {
+ getAccountDirectoryPath,
+ mapAccount,
+ mapWorkspace,
+} from '@/main/utils';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { AccountConnection } from '@/main/services/accounts/account-connection';
+import { AccountClient } from '@/main/services/accounts/account-client';
+import { AppService } from '@/main/services/app-service';
+import { eventBus } from '@/shared/lib/event-bus';
+import { parseApiError } from '@/shared/lib/axios';
+import { Account } from '@/shared/types/accounts';
+import { Workspace } from '@/shared/types/workspaces';
+import { EventLoop } from '@/shared/lib/event-loop';
+
+export class AccountService {
+ private readonly debug = createDebugger('desktop:service:account');
+ private readonly workspaces: Map<string, WorkspaceService> = new Map();
+ private readonly eventLoop: EventLoop;
+ private readonly account: Account;
+
+ public readonly app: AppService;
+ public readonly server: ServerService;
+ public readonly database: Kysely<AccountDatabaseSchema>;
+
+ public readonly connection: AccountConnection;
+ public readonly client: AccountClient;
+
+ constructor(account: Account, server: ServerService, app: AppService) {
+ this.debug(`Initializing account service for account ${account.id}`);
+
+ this.account = account;
+ this.server = server;
+ this.app = app;
+
+ const accountDataPath = getAccountDirectoryPath(account.id);
+
+ if (!fs.existsSync(accountDataPath)) {
+ fs.mkdirSync(accountDataPath, { recursive: true });
+ }
+
+ const accountDatabasePath = path.join(accountDataPath, 'account.db');
+ const database = new SQLite(accountDatabasePath);
+ database.pragma('journal_mode = WAL');
+
+ this.database = new Kysely<AccountDatabaseSchema>({
+ dialect: new SqliteDialect({
+ database,
+ }),
+ });
+
+ this.client = new AccountClient(this);
+ this.connection = new AccountConnection(this);
+
+ this.handleMessage = this.handleMessage.bind(this);
+ this.connection.on('message', this.handleMessage);
+
+ this.triggerSync = this.triggerSync.bind(this);
+ this.server.on('availability_change', this.triggerSync);
+
+ this.eventLoop = new EventLoop(ms('1 minute'), ms('1 second'), () => {
+ this.sync();
+ });
+ }
+
+ public get id(): string {
+ return this.account.id;
+ }
+
+ public get token(): string {
+ return this.account.token;
+ }
+
+ public get deviceId(): string {
+ return this.account.deviceId;
+ }
+
+ public async init(): Promise<void> {
+ await this.migrate();
+ this.connection.init();
+ this.eventLoop.start();
+
+ await this.initWorkspaces();
+ }
+
+ public updateAccount(account: Account): void {
+ this.account.email = account.email;
+ this.account.token = account.token;
+ this.account.deviceId = account.deviceId;
+ }
+
+ public getWorkspace(id: string): WorkspaceService | null {
+ return this.workspaces.get(id) ?? null;
+ }
+
+ public getWorkspaces(): WorkspaceService[] {
+ return Array.from(this.workspaces.values());
+ }
+
+ public async logout(): Promise<void> {
+ try {
+ const workspaces = this.workspaces.values();
+ for (const workspace of workspaces) {
+ await workspace.delete();
+ }
+
+ this.database.destroy();
+ this.connection.close();
+ this.eventLoop.stop();
+
+ const accountPath = getAccountDirectoryPath(this.account.id);
+ if (fs.existsSync(accountPath)) {
+ fs.rmSync(accountPath, { recursive: true, force: true });
+ }
+ } catch (error) {
+ this.debug(`Error logging out of account ${this.account.id}: ${error}`);
+ }
+ }
+
+ private async migrate(): Promise<void> {
+ this.debug(`Migrating account database for account ${this.account.id}`);
+ const migrator = new Migrator({
+ db: this.database,
+ provider: {
+ getMigrations(): Promise<Record<string, Migration>> {
+ return Promise.resolve(accountDatabaseMigrations);
+ },
+ },
+ });
+
+ await migrator.migrateToLatest();
+ }
+
+ private async initWorkspaces(): Promise<void> {
+ const workspaces = await this.database
+ .selectFrom('workspaces')
+ .selectAll()
+ .where('account_id', '=', this.account.id)
+ .execute();
+
+ for (const workspace of workspaces) {
+ const mappedWorkspace = mapWorkspace(workspace);
+ await this.initWorkspace(mappedWorkspace);
+ }
+ }
+
+ public async initWorkspace(workspace: Workspace): Promise<void> {
+ if (this.workspaces.has(workspace.id)) {
+ return;
+ }
+
+ const workspaceService = new WorkspaceService(workspace, this);
+ await workspaceService.init();
+
+ this.workspaces.set(workspace.id, workspaceService);
+ }
+
+ public async deleteWorkspace(id: string): Promise<void> {
+ const workspaceService = this.workspaces.get(id);
+ if (workspaceService) {
+ await workspaceService.delete();
+ this.workspaces.delete(id);
+ }
+ }
+
+ private handleMessage(message: Message): void {
+ if (
+ message.type === 'account_updated' ||
+ message.type === 'workspace_updated' ||
+ message.type === 'workspace_deleted'
+ ) {
+ this.eventLoop.trigger();
+ }
+ }
+
+ private triggerSync(): void {
+ this.eventLoop.trigger();
+ }
+
+ private async sync(): Promise<void> {
+ this.debug(`Syncing account ${this.account.id}`);
+
+ if (!this.server.isAvailable()) {
+ this.debug(
+ `Server ${this.server.server.domain} is not available for syncing account ${this.account.email}`
+ );
+ return;
+ }
+
+ try {
+ const { data } = await this.client.post<AccountSyncOutput>(
+ '/v1/accounts/sync',
+ {
+ platform: process.platform,
+ version: this.app.version,
+ }
+ );
+
+ const updatedAccount = await this.app.database
+ .updateTable('accounts')
+ .returningAll()
+ .set({
+ name: data.account.name,
+ avatar: data.account.avatar,
+ })
+ .where('id', '=', this.account.id)
+ .executeTakeFirst();
+
+ if (!updatedAccount) {
+ this.debug(`Failed to update account ${this.account.email} after sync`);
+ return;
+ } else {
+ this.debug(`Updated account ${this.account.email} after sync`);
+ }
+
+ const account = mapAccount(updatedAccount);
+ this.updateAccount(account);
+
+ eventBus.publish({
+ type: 'account_updated',
+ account,
+ });
+
+ for (const workspace of data.workspaces) {
+ const workspaceService = this.getWorkspace(workspace.id);
+ if (!workspaceService) {
+ const createdWorkspace = await this.database
+ .insertInto('workspaces')
+ .returningAll()
+ .values({
+ id: workspace.id,
+ account_id: this.account.id,
+ user_id: workspace.user.id,
+ name: workspace.name,
+ description: workspace.description,
+ avatar: workspace.avatar,
+ role: workspace.user.role,
+ })
+ .executeTakeFirst();
+
+ if (!createdWorkspace) {
+ this.debug(`Failed to create workspace ${workspace.id}`);
+ continue;
+ }
+
+ const mappedWorkspace = mapWorkspace(createdWorkspace);
+ await this.initWorkspace(mappedWorkspace);
+ } else {
+ const updatedWorkspace = await this.database
+ .updateTable('workspaces')
+ .returningAll()
+ .set({
+ name: workspace.name,
+ description: workspace.description,
+ avatar: workspace.avatar,
+ role: workspace.user.role,
+ })
+ .where('id', '=', workspace.id)
+ .executeTakeFirst();
+
+ if (updatedWorkspace) {
+ const mappedWorkspace = mapWorkspace(updatedWorkspace);
+ workspaceService.updateWorkspace(mappedWorkspace);
+
+ eventBus.publish({
+ type: 'workspace_updated',
+ workspace: mappedWorkspace,
+ });
+ }
+ }
+ }
+
+ const workspaceIds = this.workspaces.keys();
+ for (const workspaceId of workspaceIds) {
+ const updatedWorkspace = data.workspaces.find(
+ (w) => w.id === workspaceId
+ );
+
+ if (!updatedWorkspace) {
+ await this.deleteWorkspace(workspaceId);
+ }
+ }
+ } catch (error) {
+ const parsedError = parseApiError(error);
+ if (this.isSyncInvalid(parsedError)) {
+ this.debug(
+ `Account ${this.account.email} is not valid, logging out...`
+ );
+ await this.logout();
+ return;
+ }
+
+ this.debug(`Failed to sync account ${this.account.email}: ${error}`);
+ }
+ }
+
+ private isSyncInvalid(error: ApiErrorOutput) {
+ return (
+ error.code === ApiErrorCode.TokenInvalid ||
+ error.code === ApiErrorCode.TokenMissing ||
+ error.code === ApiErrorCode.AccountNotFound ||
+ error.code === ApiErrorCode.DeviceNotFound
+ );
+ }
+}
diff --git a/apps/desktop/src/main/services/app-service.ts b/apps/desktop/src/main/services/app-service.ts
new file mode 100644
index 00000000..1db63259
--- /dev/null
+++ b/apps/desktop/src/main/services/app-service.ts
@@ -0,0 +1,258 @@
+import { Kysely, Migration, Migrator, SqliteDialect } from 'kysely';
+import SQLite from 'better-sqlite3';
+import { ApiErrorCode, createDebugger } from '@colanode/core';
+import ms from 'ms';
+import axios from 'axios';
+
+import { app } from 'electron';
+
+import { AppDatabaseSchema, appDatabaseMigrations } from '@/main/databases/app';
+import { appDatabasePath, mapAccount, mapServer } from '@/main/utils';
+import { MetadataService } from '@/main/services/metadata-service';
+import { AccountService } from '@/main/services/accounts/account-service';
+import { ServerService } from '@/main/services/server-service';
+import { Account } from '@/shared/types/accounts';
+import { Server } from '@/shared/types/servers';
+import { EventLoop } from '@/shared/lib/event-loop';
+import { parseApiError } from '@/shared/lib/axios';
+import { NotificationService } from '@/main/services/notification-service';
+import { eventBus } from '@/shared/lib/event-bus';
+
+export class AppService {
+ private readonly debug = createDebugger('desktop:service:app');
+ private readonly servers: Map<string, ServerService> = new Map();
+ private readonly accounts: Map<string, AccountService> = new Map();
+ private readonly cleanupEventLoop: EventLoop;
+
+ public readonly database: Kysely<AppDatabaseSchema>;
+ public readonly metadata: MetadataService;
+ public readonly notifications: NotificationService;
+ public readonly version: string;
+
+ constructor() {
+ this.version = app.getVersion();
+
+ const database = new SQLite(appDatabasePath);
+ database.pragma('journal_mode = WAL');
+
+ this.database = new Kysely<AppDatabaseSchema>({
+ dialect: new SqliteDialect({
+ database,
+ }),
+ });
+
+ this.metadata = new MetadataService(this);
+ this.notifications = new NotificationService(this);
+
+ this.cleanupEventLoop = new EventLoop(
+ ms('10 minutes'),
+ ms('1 minute'),
+ () => {
+ this.cleanup();
+ }
+ );
+ }
+
+ public async migrate(): Promise<void> {
+ this.debug('Migrating app database');
+
+ const migrator = new Migrator({
+ db: this.database,
+ provider: {
+ getMigrations(): Promise<Record<string, Migration>> {
+ return Promise.resolve(appDatabaseMigrations);
+ },
+ },
+ });
+
+ await migrator.migrateToLatest();
+ }
+
+ public getAccount(id: string): AccountService | null {
+ return this.accounts.get(id) ?? null;
+ }
+
+ public getAccounts(): AccountService[] {
+ return Array.from(this.accounts.values());
+ }
+
+ public getServer(domain: string): ServerService | null {
+ return this.servers.get(domain) ?? null;
+ }
+
+ public async init(): Promise<void> {
+ await this.initServers();
+ await this.initAccounts();
+ this.cleanupEventLoop.start();
+ }
+
+ private async initServers(): Promise<void> {
+ const servers = await this.database
+ .selectFrom('servers')
+ .selectAll()
+ .execute();
+
+ for (const server of servers) {
+ await this.initServer(mapServer(server));
+ }
+ }
+
+ private async initAccounts(): Promise<void> {
+ const accounts = await this.database
+ .selectFrom('accounts')
+ .selectAll()
+ .execute();
+
+ for (const account of accounts) {
+ await this.initAccount(mapAccount(account));
+ }
+ }
+
+ public async initAccount(account: Account): Promise<AccountService> {
+ if (this.accounts.has(account.id)) {
+ return this.accounts.get(account.id)!;
+ }
+
+ const server = this.servers.get(account.server);
+ if (!server) {
+ throw new Error('Server not found');
+ }
+
+ const accountService = new AccountService(account, server, this);
+ await accountService.init();
+
+ this.accounts.set(account.id, accountService);
+ return accountService;
+ }
+
+ public async initServer(server: Server): Promise<ServerService> {
+ if (this.servers.has(server.domain)) {
+ return this.servers.get(server.domain)!;
+ }
+
+ const serverService = new ServerService(this, server);
+ this.servers.set(server.domain, serverService);
+
+ return serverService;
+ }
+
+ public async createServer(domain: string): Promise<ServerService | null> {
+ if (this.servers.has(domain)) {
+ return this.servers.get(domain)!;
+ }
+
+ const config = await ServerService.fetchServerConfig(domain);
+ if (!config) {
+ return null;
+ }
+
+ const createdServer = await this.database
+ .insertInto('servers')
+ .values({
+ domain,
+ attributes: JSON.stringify(config.attributes),
+ avatar: config.avatar,
+ name: config.name,
+ version: config.version,
+ created_at: new Date().toISOString(),
+ })
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!createdServer) {
+ return null;
+ }
+
+ const server = mapServer(createdServer);
+ const serverService = await this.initServer(server);
+
+ eventBus.publish({
+ type: 'server_created',
+ server,
+ });
+
+ return serverService;
+ }
+
+ public triggerCleanup(): void {
+ this.cleanupEventLoop.trigger();
+ }
+
+ private async cleanup(): Promise<void> {
+ await this.syncDeletedTokens();
+ }
+
+ private async syncDeletedTokens(): Promise<void> {
+ this.debug('Syncing deleted tokens');
+
+ const deletedTokens = await this.database
+ .selectFrom('deleted_tokens')
+ .innerJoin('servers', 'deleted_tokens.server', 'servers.domain')
+ .select([
+ 'deleted_tokens.token',
+ 'deleted_tokens.account_id',
+ 'servers.domain',
+ 'servers.attributes',
+ ])
+ .execute();
+
+ if (deletedTokens.length === 0) {
+ this.debug('No deleted tokens found');
+ return;
+ }
+
+ for (const deletedToken of deletedTokens) {
+ const serverService = this.servers.get(deletedToken.domain);
+ if (!serverService) {
+ this.debug(
+ `Server ${deletedToken.domain} is not available for logging out account ${deletedToken.account_id}`
+ );
+ continue;
+ }
+
+ try {
+ await axios.delete(`${serverService.apiBaseUrl}/v1/accounts/logout`, {
+ headers: {
+ Authorization: `Bearer ${deletedToken.token}`,
+ },
+ });
+
+ await this.database
+ .deleteFrom('deleted_tokens')
+ .where('token', '=', deletedToken.token)
+ .where('account_id', '=', deletedToken.account_id)
+ .execute();
+
+ this.debug(
+ `Logged out account ${deletedToken.account_id} from server ${deletedToken.domain}`
+ );
+ } catch (error) {
+ const parsedError = parseApiError(error);
+ if (
+ parsedError.code === ApiErrorCode.TokenInvalid ||
+ parsedError.code === ApiErrorCode.AccountNotFound ||
+ parsedError.code === ApiErrorCode.DeviceNotFound
+ ) {
+ this.debug(
+ `Account ${deletedToken.account_id} is already logged out, skipping...`
+ );
+
+ await this.database
+ .deleteFrom('deleted_tokens')
+ .where('token', '=', deletedToken.token)
+ .where('account_id', '=', deletedToken.account_id)
+ .execute();
+
+ continue;
+ }
+
+ this.debug(
+ `Failed to logout account ${deletedToken.account_id} from server ${deletedToken.domain}`,
+ error
+ );
+ }
+ }
+ }
+}
+
+export const appService = new AppService();
diff --git a/apps/desktop/src/main/services/asset-service.ts b/apps/desktop/src/main/services/asset-service.ts
deleted file mode 100644
index af79da8a..00000000
--- a/apps/desktop/src/main/services/asset-service.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { net } from 'electron';
-import fs from 'fs';
-import path from 'path';
-
-import { getAssetsSourcePath } from '@/main/utils';
-import { EmojiData } from '@/shared/types/emojis';
-import { IconData } from '@/shared/types/icons';
-
-class AssetService {
- public async handleAssetRequest(request: Request): Promise<Response> {
- const url = request.url.replace('asset://', '');
- const assetPath = this.getAssetPath(url);
- const localFileUrl = `file://${assetPath}`;
- return net.fetch(localFileUrl);
- }
-
- private getAssetPath(url: string): string {
- return path.join(getAssetsSourcePath(), url);
- }
-
- public getEmojiData(): EmojiData {
- const emojisMetadataPath = path.join(
- getAssetsSourcePath(),
- 'emojis',
- 'emojis.json'
- );
- return JSON.parse(fs.readFileSync(emojisMetadataPath, 'utf8'));
- }
-
- public getIconData(): IconData {
- const iconsMetadataPath = path.join(
- getAssetsSourcePath(),
- 'icons',
- 'icons.json'
- );
- return JSON.parse(fs.readFileSync(iconsMetadataPath, 'utf8'));
- }
-}
-
-export const assetService = new AssetService();
diff --git a/apps/desktop/src/main/services/avatar-service.ts b/apps/desktop/src/main/services/avatar-service.ts
deleted file mode 100644
index c4826146..00000000
--- a/apps/desktop/src/main/services/avatar-service.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { createDebugger } from '@colanode/core';
-
-import { net } from 'electron';
-import fs from 'fs';
-import path from 'path';
-
-import { databaseService } from '@/main/data/database-service';
-import { getAccountAvatarsDirectoryPath } from '@/main/utils';
-import { httpClient } from '@/shared/lib/http-client';
-
-class AvatarService {
- private readonly debug = createDebugger('desktop:service:avatar');
-
- public async handleAvatarRequest(request: Request): Promise<Response> {
- const url = request.url.replace('avatar://', '');
- const [accountId, avatarId] = url.split('/');
- if (!accountId || !avatarId) {
- this.debug(`Invalid avatar request url: ${url}`);
- return new Response(null, { status: 400 });
- }
-
- const avatarsDir = getAccountAvatarsDirectoryPath(accountId);
- const avatarPath = path.join(avatarsDir, `${avatarId}.jpeg`);
- const avatarLocalUrl = `file://${avatarPath}`;
-
- // Check if the avatar file already exists
- if (fs.existsSync(avatarPath)) {
- return net.fetch(avatarLocalUrl);
- }
-
- this.debug(`Downloading avatar ${avatarId} for account ${accountId}`);
- // Download the avatar file if it doesn't exist
- const credentials = await databaseService.appDatabase
- .selectFrom('accounts')
- .innerJoin('servers', 'accounts.server', 'servers.domain')
- .select(['domain', 'attributes', 'token'])
- .where('id', '=', accountId)
- .executeTakeFirst();
-
- if (!credentials) {
- this.debug(`Account ${accountId} not found`);
- return new Response(null, { status: 404 });
- }
-
- const response = await httpClient.get<NodeJS.ReadableStream>(
- `/v1/avatars/${avatarId}`,
- {
- domain: credentials.domain,
- token: credentials.token,
- responseType: 'stream',
- }
- );
-
- if (response.status !== 200 || !response.data) {
- this.debug(
- `Failed to download avatar ${avatarId} for account ${accountId}`
- );
- return new Response(null, { status: 404 });
- }
-
- if (!fs.existsSync(avatarsDir)) {
- fs.mkdirSync(avatarsDir, { recursive: true });
- }
-
- const fileStream = fs.createWriteStream(avatarPath);
-
- return new Promise((resolve, reject) => {
- response.data.pipe(fileStream);
-
- fileStream.on('finish', async () => {
- // Ensure the file is written before trying to fetch it
- this.debug(`Avatar ${avatarId} for account ${accountId} downloaded`);
- resolve(net.fetch(avatarLocalUrl));
- });
-
- fileStream.on('error', (err) => {
- this.debug(
- `Failed to download avatar ${avatarId} for account ${accountId}`
- );
- reject(new Response(null, { status: 500, statusText: err.message }));
- });
- });
- }
-}
-
-export const avatarService = new AvatarService();
diff --git a/apps/desktop/src/main/services/command-service.ts b/apps/desktop/src/main/services/command-service.ts
deleted file mode 100644
index 79e0fa4e..00000000
--- a/apps/desktop/src/main/services/command-service.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { createDebugger } from '@colanode/core';
-
-import { commandHandlerMap } from '@/main/commands';
-import { CommandHandler } from '@/main/types';
-import { CommandInput, CommandMap } from '@/shared/commands';
-
-class CommandService {
- private readonly debug = createDebugger('desktop:service:command');
-
- public async executeCommand<T extends CommandInput>(
- input: T
- ): Promise<CommandMap[T['type']]['output']> {
- this.debug(`Executing command: ${input.type}`);
-
- const handler = commandHandlerMap[
- input.type
- ] as unknown as CommandHandler<T>;
-
- if (!handler) {
- throw new Error(`No handler found for command type: ${input.type}`);
- }
-
- return handler.handleCommand(input);
- }
-}
-
-export const commandService = new CommandService();
diff --git a/apps/desktop/src/main/services/file-service.ts b/apps/desktop/src/main/services/file-service.ts
deleted file mode 100644
index 9f87052f..00000000
--- a/apps/desktop/src/main/services/file-service.ts
+++ /dev/null
@@ -1,820 +0,0 @@
-import {
- CompleteUploadOutput,
- CreateDownloadOutput,
- CreateUploadOutput,
- extractFileType,
- FileStatus,
- SyncFileData,
- SyncFileInteractionData,
- SyncFileTombstoneData,
- createDebugger,
-} from '@colanode/core';
-import axios from 'axios';
-import mime from 'mime-types';
-
-import { net, shell } from 'electron';
-import fs from 'fs';
-import path from 'path';
-
-import { databaseService } from '@/main/data/database-service';
-import { serverService } from '@/main/services/server-service';
-import {
- fetchWorkspaceCredentials,
- getWorkspaceFilesDirectoryPath,
- getWorkspaceTempFilesDirectoryPath,
- mapFile,
- mapFileInteraction,
- mapFileState,
-} from '@/main/utils';
-import { eventBus } from '@/shared/lib/event-bus';
-import { httpClient } from '@/shared/lib/http-client';
-import {
- DownloadStatus,
- FileMetadata,
- UploadStatus,
-} from '@/shared/types/files';
-
-class FileService {
- private readonly debug = createDebugger('desktop:service:file');
-
- public async handleFileRequest(request: Request): Promise<Response> {
- const url = request.url.replace('local-file://', '');
- const [userId, file] = url.split('/');
- if (!userId || !file) {
- this.debug(`Invalid file request url: ${url}`);
- return new Response(null, { status: 400 });
- }
-
- const filesDir = getWorkspaceFilesDirectoryPath(userId);
- const filePath = path.join(filesDir, file);
-
- if (fs.existsSync(filePath)) {
- const fileUrl = `file://${filePath}`;
- return net.fetch(fileUrl);
- }
-
- this.debug(`File ${file} not found for user ${userId}`);
- return new Response(null, { status: 404 });
- }
-
- public async handleFilePreviewRequest(request: Request): Promise<Response> {
- const url = request.url.replace('local-file-preview://', 'file://');
- return net.fetch(url);
- }
-
- public copyFileToWorkspace(
- filePath: string,
- fileId: string,
- fileExtension: string,
- userId: string
- ): void {
- const filesDir = getWorkspaceFilesDirectoryPath(userId);
-
- if (!fs.existsSync(filesDir)) {
- fs.mkdirSync(filesDir, { recursive: true });
- }
-
- const destinationFilePath = path.join(
- filesDir,
- `${fileId}${fileExtension}`
- );
-
- this.debug(
- `Copying file ${filePath} to ${destinationFilePath} for user ${userId}`
- );
- fs.copyFileSync(filePath, destinationFilePath);
-
- // check if the file is in the temp files directory. If it is in
- // temp files directory it means it has been pasted or dragged
- // therefore we need to delete it
- const fileDirectory = path.dirname(filePath);
- const tempFilesDir = getWorkspaceTempFilesDirectoryPath(userId);
- if (fileDirectory === tempFilesDir) {
- fs.rmSync(filePath);
- }
- }
-
- public openFile(userId: string, id: string, extension: string): void {
- const filesDir = getWorkspaceFilesDirectoryPath(userId);
- const filePath = path.join(filesDir, `${id}${extension}`);
-
- this.debug(`Opening file ${filePath} for user ${userId}`);
- shell.openPath(filePath);
- }
-
- public deleteFile(userId: string, id: string, extension: string): void {
- const filesDir = getWorkspaceFilesDirectoryPath(userId);
- const filePath = path.join(filesDir, `${id}${extension}`);
-
- this.debug(`Deleting file ${filePath} for user ${userId}`);
- fs.rmSync(filePath, { force: true });
- }
-
- public getFileMetadata(filePath: string): FileMetadata | null {
- if (!fs.existsSync(filePath)) {
- return null;
- }
-
- const mimeType = mime.lookup(filePath);
- if (mimeType === false) {
- return null;
- }
-
- const stats = fs.statSync(filePath);
- const type = extractFileType(mimeType);
-
- this.debug(`Getting file metadata for ${filePath}`);
-
- return {
- path: filePath,
- mimeType,
- extension: path.extname(filePath),
- name: path.basename(filePath),
- size: stats.size,
- type,
- };
- }
-
- public async uploadFiles(userId: string): Promise<void> {
- this.debug(`Uploading files for user ${userId}`);
-
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const uploads = await workspaceDatabase
- .selectFrom('file_states')
- .selectAll()
- .where('upload_status', '=', UploadStatus.Pending)
- .execute();
-
- if (uploads.length === 0) {
- return;
- }
-
- const credentials = await fetchWorkspaceCredentials(userId);
- if (!credentials) {
- this.debug(`Workspace credentials not found for user ${userId}`);
- return;
- }
-
- const filesDir = getWorkspaceFilesDirectoryPath(userId);
- for (const upload of uploads) {
- if (upload.upload_retries >= 10) {
- await workspaceDatabase
- .updateTable('file_states')
- .set({
- upload_status: UploadStatus.Failed,
- updated_at: new Date().toISOString(),
- })
- .where('file_id', '=', upload.file_id)
- .execute();
-
- continue;
- }
-
- const file = await workspaceDatabase
- .selectFrom('files')
- .selectAll()
- .where('id', '=', upload.file_id)
- .executeTakeFirst();
-
- if (!file) {
- await workspaceDatabase
- .deleteFrom('file_states')
- .where('file_id', '=', upload.file_id)
- .execute();
-
- continue;
- }
-
- if (file.version === BigInt(0)) {
- // file is not synced with the server, we need to wait for the sync to complete
- continue;
- }
-
- if (file.status === FileStatus.Ready) {
- // file is already uploaded to the server
- await workspaceDatabase
- .updateTable('file_states')
- .set({
- upload_status: UploadStatus.Completed,
- upload_progress: 100,
- updated_at: new Date().toISOString(),
- })
- .where('file_id', '=', file.id)
- .execute();
-
- continue;
- }
-
- const filePath = path.join(filesDir, `${file.id}${file.extension}`);
-
- if (!fs.existsSync(filePath)) {
- await workspaceDatabase
- .deleteFrom('file_states')
- .where('file_id', '=', file.id)
- .execute();
-
- continue;
- }
-
- if (!serverService.isAvailable(credentials.serverDomain)) {
- continue;
- }
-
- try {
- const { data } = await httpClient.post<CreateUploadOutput>(
- `/v1/workspaces/${credentials.workspaceId}/files`,
- {
- fileId: file.id,
- },
- {
- domain: credentials.serverDomain,
- token: credentials.token,
- }
- );
-
- const presignedUrl = data.url;
- const fileStream = fs.createReadStream(filePath);
-
- let lastProgress = 0;
- await axios.put(presignedUrl, fileStream, {
- headers: {
- 'Content-Type': file.mime_type,
- 'Content-Length': file.size,
- },
- onUploadProgress: async (progressEvent) => {
- const progress = Math.round(
- (progressEvent.loaded / file.size) * 100
- );
-
- if (progress >= lastProgress) {
- return;
- }
-
- lastProgress = progress;
-
- const updatedFileState = await workspaceDatabase
- .updateTable('file_states')
- .returningAll()
- .set({
- upload_progress: progress,
- updated_at: new Date().toISOString(),
- })
- .where('file_id', '=', file.id)
- .executeTakeFirst();
-
- if (!updatedFileState) {
- return;
- }
-
- eventBus.publish({
- type: 'file_state_updated',
- userId,
- fileState: mapFileState(updatedFileState),
- });
- },
- });
-
- const { status } = await httpClient.put<CompleteUploadOutput>(
- `/v1/workspaces/${credentials.workspaceId}/files/${file.id}`,
- {},
- {
- domain: credentials.serverDomain,
- token: credentials.token,
- }
- );
-
- if (status !== 200) {
- continue;
- }
-
- await workspaceDatabase
- .updateTable('file_states')
- .set({
- upload_status: UploadStatus.Completed,
- upload_progress: 100,
- updated_at: new Date().toISOString(),
- })
- .where('file_id', '=', file.id)
- .execute();
- } catch {
- await workspaceDatabase
- .updateTable('file_states')
- .set((eb) => ({ upload_retries: eb('upload_retries', '+', 1) }))
- .where('file_id', '=', file.id)
- .execute();
- }
- }
- }
-
- public async downloadFiles(userId: string): Promise<void> {
- this.debug(`Downloading files for user ${userId}`);
-
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const downloads = await workspaceDatabase
- .selectFrom('file_states')
- .selectAll()
- .where('download_status', '=', DownloadStatus.Pending)
- .execute();
-
- if (downloads.length === 0) {
- return;
- }
-
- const credentials = await fetchWorkspaceCredentials(userId);
- if (!credentials) {
- this.debug(`Workspace credentials not found for user ${userId}`);
- return;
- }
-
- const filesDir = getWorkspaceFilesDirectoryPath(userId);
- if (!fs.existsSync(filesDir)) {
- fs.mkdirSync(filesDir, { recursive: true });
- }
-
- for (const download of downloads) {
- const file = await workspaceDatabase
- .selectFrom('files')
- .selectAll()
- .where('id', '=', download.file_id)
- .executeTakeFirst();
-
- if (!file) {
- const deletedFileState = await workspaceDatabase
- .deleteFrom('file_states')
- .returningAll()
- .where('file_id', '=', download.file_id)
- .executeTakeFirst();
-
- if (!deletedFileState) {
- continue;
- }
-
- eventBus.publish({
- type: 'file_state_deleted',
- userId,
- fileState: mapFileState(deletedFileState),
- });
-
- continue;
- }
-
- const filePath = path.join(filesDir, `${file.id}${file.extension}`);
-
- if (fs.existsSync(filePath)) {
- const updatedFileState = await workspaceDatabase
- .updateTable('file_states')
- .returningAll()
- .set({
- download_status: DownloadStatus.Completed,
- download_progress: 100,
- updated_at: new Date().toISOString(),
- })
- .where('file_id', '=', file.id)
- .executeTakeFirst();
-
- if (!updatedFileState) {
- continue;
- }
-
- eventBus.publish({
- type: 'file_state_updated',
- userId,
- fileState: mapFileState(updatedFileState),
- });
-
- continue;
- }
-
- if (!serverService.isAvailable(credentials.serverDomain)) {
- continue;
- }
-
- try {
- const { data } = await httpClient.get<CreateDownloadOutput>(
- `/v1/workspaces/${credentials.workspaceId}/downloads/${file.id}`,
- {
- domain: credentials.serverDomain,
- token: credentials.token,
- }
- );
-
- const presignedUrl = data.url;
- const fileStream = fs.createWriteStream(filePath);
- let lastProgress = 0;
-
- await axios
- .get(presignedUrl, {
- responseType: 'stream',
- onDownloadProgress: async (progressEvent) => {
- const progress = Math.round(
- (progressEvent.loaded / file.size) * 100
- );
-
- if (progress <= lastProgress) {
- return;
- }
-
- lastProgress = progress;
-
- const updatedFileState = await workspaceDatabase
- .updateTable('file_states')
- .returningAll()
- .set({
- download_progress: progress,
- updated_at: new Date().toISOString(),
- })
- .where('file_id', '=', file.id)
- .executeTakeFirst();
-
- if (!updatedFileState) {
- return;
- }
-
- eventBus.publish({
- type: 'file_state_updated',
- userId,
- fileState: mapFileState(updatedFileState),
- });
- },
- })
- .then((response) => {
- response.data.pipe(fileStream);
- });
-
- const updatedFileState = await workspaceDatabase
- .updateTable('file_states')
- .returningAll()
- .set({
- download_status: DownloadStatus.Completed,
- download_progress: 100,
- updated_at: new Date().toISOString(),
- })
- .where('file_id', '=', file.id)
- .executeTakeFirst();
-
- if (!updatedFileState) {
- continue;
- }
-
- eventBus.publish({
- type: 'file_state_updated',
- userId,
- fileState: mapFileState(updatedFileState),
- });
- } catch {
- const updatedFileState = await workspaceDatabase
- .updateTable('file_states')
- .returningAll()
- .set((eb) => ({ download_retries: eb('download_retries', '+', 1) }))
- .where('file_id', '=', file.id)
- .executeTakeFirst();
-
- if (!updatedFileState) {
- continue;
- }
-
- eventBus.publish({
- type: 'file_state_updated',
- userId,
- fileState: mapFileState(updatedFileState),
- });
- }
- }
- }
-
- public async cleanDeletedFiles(userId: string): Promise<void> {
- this.debug(`Checking deleted files for user ${userId}`);
-
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const filesDir = getWorkspaceFilesDirectoryPath(userId);
- if (!fs.existsSync(filesDir)) {
- return;
- }
-
- const files = fs.readdirSync(filesDir);
- while (files.length > 0) {
- const batch = files.splice(0, 100);
- const fileIdMap: Record<string, string> = {};
-
- for (const file of batch) {
- const id = path.parse(file).name;
- fileIdMap[id] = file;
- }
-
- const fileIds = Object.keys(fileIdMap);
- const fileStates = await workspaceDatabase
- .selectFrom('file_states')
- .select(['file_id'])
- .where('file_id', 'in', fileIds)
- .execute();
-
- for (const fileId of fileIds) {
- const fileState = fileStates.find((f) => f.file_id === fileId);
- if (fileState) {
- continue;
- }
-
- const filePath = path.join(
- getWorkspaceFilesDirectoryPath(userId),
- fileIdMap[fileId]!
- );
- fs.rmSync(filePath, { force: true });
- }
- }
- }
-
- public async cleanTempFiles(userId: string): Promise<void> {
- this.debug(`Checking temp files for user ${userId}`);
-
- const tempFilesDir = getWorkspaceTempFilesDirectoryPath(userId);
- if (!fs.existsSync(tempFilesDir)) {
- return;
- }
-
- const files = fs.readdirSync(tempFilesDir);
- const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000; // 24 hours in milliseconds
-
- for (const file of files) {
- const filePath = path.join(tempFilesDir, file);
- const stats = fs.statSync(filePath);
-
- if (stats.mtimeMs < oneDayAgo) {
- try {
- fs.unlinkSync(filePath);
- this.debug(`Deleted old temp file: ${filePath}`);
- } catch (error) {
- this.debug(`Failed to delete temp file: ${filePath}`, error);
- }
- }
- }
- }
-
- public async syncServerFile(
- userId: string,
- file: SyncFileData
- ): Promise<void> {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const existingFile = await workspaceDatabase
- .selectFrom('files')
- .selectAll()
- .where('id', '=', file.id)
- .executeTakeFirst();
-
- const version = BigInt(file.version);
- if (existingFile) {
- if (existingFile.version === version) {
- this.debug(`Server file ${file.id} is already synced`);
- return;
- }
-
- const updatedFile = await workspaceDatabase
- .updateTable('files')
- .returningAll()
- .set({
- name: file.name,
- original_name: file.originalName,
- mime_type: file.mimeType,
- extension: file.extension,
- size: file.size,
- parent_id: file.parentId,
- root_id: file.rootId,
- status: file.status,
- type: file.type,
- updated_at: file.updatedAt,
- updated_by: file.updatedBy,
- version,
- })
- .where('id', '=', file.id)
- .executeTakeFirst();
-
- if (!updatedFile) {
- return;
- }
-
- eventBus.publish({
- type: 'file_updated',
- userId,
- file: mapFile(updatedFile),
- });
-
- this.debug(`Server file ${file.id} has been synced`);
- return;
- }
-
- const createdFile = await workspaceDatabase
- .insertInto('files')
- .returningAll()
- .values({
- id: file.id,
- version,
- type: file.type,
- parent_id: file.parentId,
- entry_id: file.entryId,
- root_id: file.rootId,
- name: file.name,
- original_name: file.originalName,
- mime_type: file.mimeType,
- extension: file.extension,
- size: file.size,
- created_at: file.createdAt,
- created_by: file.createdBy,
- updated_at: file.updatedAt,
- updated_by: file.updatedBy,
- status: file.status,
- })
- .executeTakeFirst();
-
- if (!createdFile) {
- return;
- }
-
- eventBus.publish({
- type: 'file_created',
- userId,
- file: mapFile(createdFile),
- });
-
- this.debug(`Server file ${file.id} has been synced`);
- }
-
- public async syncServerFileTombstone(
- userId: string,
- fileTombstone: SyncFileTombstoneData
- ) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const deletedFile = await workspaceDatabase
- .deleteFrom('files')
- .returningAll()
- .where('id', '=', fileTombstone.id)
- .executeTakeFirst();
-
- await workspaceDatabase
- .deleteFrom('file_interactions')
- .where('file_id', '=', fileTombstone.id)
- .execute();
-
- await workspaceDatabase
- .deleteFrom('file_states')
- .where('file_id', '=', fileTombstone.id)
- .execute();
-
- if (deletedFile) {
- // if the file exists in the workspace, we need to delete it
- const filePath = path.join(
- getWorkspaceFilesDirectoryPath(userId),
- `${fileTombstone.id}${deletedFile.extension}`
- );
-
- if (fs.existsSync(filePath)) {
- fs.rmSync(filePath, { force: true });
- }
-
- eventBus.publish({
- type: 'file_deleted',
- userId,
- file: mapFile(deletedFile),
- });
- }
-
- this.debug(`Server file tombstone ${fileTombstone.id} has been synced`);
- }
-
- public async syncServerFileInteraction(
- userId: string,
- fileInteraction: SyncFileInteractionData
- ) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const existingFileInteraction = await workspaceDatabase
- .selectFrom('file_interactions')
- .selectAll()
- .where('file_id', '=', fileInteraction.fileId)
- .executeTakeFirst();
-
- const version = BigInt(fileInteraction.version);
- if (existingFileInteraction) {
- if (existingFileInteraction.version === version) {
- this.debug(
- `Server file interaction for file ${fileInteraction.fileId} is already synced`
- );
- return;
- }
- }
-
- const createdFileInteraction = await workspaceDatabase
- .insertInto('file_interactions')
- .returningAll()
- .values({
- file_id: fileInteraction.fileId,
- root_id: fileInteraction.rootId,
- collaborator_id: fileInteraction.collaboratorId,
- first_seen_at: fileInteraction.firstSeenAt,
- last_seen_at: fileInteraction.lastSeenAt,
- last_opened_at: fileInteraction.lastOpenedAt,
- first_opened_at: fileInteraction.firstOpenedAt,
- version,
- })
- .onConflict((b) =>
- b.columns(['file_id', 'collaborator_id']).doUpdateSet({
- last_seen_at: fileInteraction.lastSeenAt,
- first_seen_at: fileInteraction.firstSeenAt,
- last_opened_at: fileInteraction.lastOpenedAt,
- first_opened_at: fileInteraction.firstOpenedAt,
- version,
- })
- )
- .executeTakeFirst();
-
- if (!createdFileInteraction) {
- return;
- }
-
- eventBus.publish({
- type: 'file_interaction_updated',
- userId,
- fileInteraction: mapFileInteraction(createdFileInteraction),
- });
-
- this.debug(
- `Server file interaction for file ${fileInteraction.fileId} has been synced`
- );
- }
-
- public async revertFileCreation(userId: string, fileId: string) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const deletedFile = await workspaceDatabase
- .deleteFrom('files')
- .returningAll()
- .where('id', '=', fileId)
- .executeTakeFirst();
-
- if (!deletedFile) {
- return;
- }
-
- await workspaceDatabase
- .deleteFrom('file_states')
- .returningAll()
- .where('file_id', '=', fileId)
- .executeTakeFirst();
-
- await workspaceDatabase
- .deleteFrom('file_interactions')
- .where('file_id', '=', fileId)
- .execute();
-
- const filePath = path.join(
- getWorkspaceFilesDirectoryPath(userId),
- `${fileId}${deletedFile.extension}`
- );
-
- if (fs.existsSync(filePath)) {
- fs.rmSync(filePath, { force: true });
- }
-
- eventBus.publish({
- type: 'file_deleted',
- userId,
- file: mapFile(deletedFile),
- });
- }
-
- public async revertFileDeletion(userId: string, fileId: string) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const deletedFile = await workspaceDatabase
- .updateTable('files')
- .returningAll()
- .set({
- deleted_at: null,
- })
- .where('id', '=', fileId)
- .executeTakeFirst();
-
- if (!deletedFile) {
- return;
- }
-
- eventBus.publish({
- type: 'file_created',
- userId,
- file: mapFile(deletedFile),
- });
- }
-}
-
-export const fileService = new FileService();
diff --git a/apps/desktop/src/main/services/metadata-service.ts b/apps/desktop/src/main/services/metadata-service.ts
index eae9cf3c..e96e3de0 100644
--- a/apps/desktop/src/main/services/metadata-service.ts
+++ b/apps/desktop/src/main/services/metadata-service.ts
@@ -1,8 +1,17 @@
-import { databaseService } from '@/main/data/database-service';
+import { createDebugger } from '@colanode/core';
+
+import { AppService } from '@/main/services/app-service';
+
+export class MetadataService {
+ private readonly debug = createDebugger('desktop:service:metadata');
+ private readonly app: AppService;
+
+ constructor(app: AppService) {
+ this.app = app;
+ }
-class MetadataService {
public async get<T>(key: string): Promise<T | null> {
- const metadata = await databaseService.appDatabase
+ const metadata = await this.app.database
.selectFrom('metadata')
.selectAll()
.where('key', '=', key)
@@ -16,7 +25,9 @@ class MetadataService {
}
public async set<T>(key: string, value: T) {
- await databaseService.appDatabase
+ this.debug(`Setting metadata key ${key} to value ${value}`);
+
+ await this.app.database
.insertInto('metadata')
.values({
key,
@@ -33,11 +44,11 @@ class MetadataService {
}
public async delete(key: string) {
- await databaseService.appDatabase
+ this.debug(`Deleting metadata key ${key}`);
+
+ await this.app.database
.deleteFrom('metadata')
.where('key', '=', key)
.execute();
}
}
-
-export const metadataService = new MetadataService();
diff --git a/apps/desktop/src/main/services/mutation-service.ts b/apps/desktop/src/main/services/mutation-service.ts
deleted file mode 100644
index 2c92910a..00000000
--- a/apps/desktop/src/main/services/mutation-service.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { createDebugger } from '@colanode/core';
-
-import { mutationHandlerMap } from '@/main/mutations';
-import { MutationHandler } from '@/main/types';
-import {
- MutationError,
- MutationErrorCode,
- MutationInput,
- MutationResult,
-} from '@/shared/mutations';
-
-class MutationService {
- private readonly debug = createDebugger('desktop:service:mutation');
-
- public async executeMutation<T extends MutationInput>(
- input: T
- ): Promise<MutationResult<T>> {
- const handler = mutationHandlerMap[
- input.type
- ] as unknown as MutationHandler<T>;
-
- this.debug(`Executing mutation: ${input.type}`);
-
- try {
- if (!handler) {
- throw new Error(`No handler found for mutation type: ${input.type}`);
- }
-
- const output = await handler.handleMutation(input);
- return { success: true, output };
- } catch (error) {
- this.debug(`Error executing mutation: ${input.type}`, error);
- if (error instanceof MutationError) {
- return {
- success: false,
- error: {
- code: error.code,
- message: error.message,
- },
- };
- }
-
- return {
- success: false,
- error: {
- code: MutationErrorCode.Unknown,
- message: 'Something went wrong trying to execute the mutation.',
- },
- };
- }
- }
-}
-
-export const mutationService = new MutationService();
diff --git a/apps/desktop/src/main/services/notification-service.ts b/apps/desktop/src/main/services/notification-service.ts
index dac37654..5a84a6a8 100644
--- a/apps/desktop/src/main/services/notification-service.ts
+++ b/apps/desktop/src/main/services/notification-service.ts
@@ -1,10 +1,14 @@
import { app } from 'electron';
-import { radarService } from '@/main/services/radar-service';
import { eventBus } from '@/shared/lib/event-bus';
+import { AppService } from '@/main/services/app-service';
+
+export class NotificationService {
+ private readonly appService: AppService;
+
+ constructor(appService: AppService) {
+ this.appService = appService;
-class NotificationService {
- constructor() {
if (process.platform !== 'darwin') {
return;
}
@@ -21,14 +25,24 @@ class NotificationService {
return;
}
- const radarData = radarService.getData();
- const importantCount = Object.values(radarData).reduce(
- (acc, curr) => acc + curr.importantCount,
- 0
- );
- const hasUnseenChanges = Object.values(radarData).some(
- (data) => data.hasUnseenChanges
- );
+ const accounts = this.appService.getAccounts();
+ if (accounts.length === 0) {
+ app.dock.setBadge('');
+ return;
+ }
+
+ let importantCount = 0;
+ let hasUnseenChanges = false;
+
+ for (const account of accounts) {
+ const workspaces = account.getWorkspaces();
+
+ for (const workspace of workspaces) {
+ const radarData = workspace.radar.getData();
+ importantCount += radarData.importantCount;
+ hasUnseenChanges = hasUnseenChanges || radarData.hasUnseenChanges;
+ }
+ }
if (importantCount > 0) {
app.dock.setBadge(importantCount.toString());
@@ -39,5 +53,3 @@ class NotificationService {
}
}
}
-
-export const notificationService = new NotificationService();
diff --git a/apps/desktop/src/main/services/server-service.ts b/apps/desktop/src/main/services/server-service.ts
index 0978dbd7..2c6ff304 100644
--- a/apps/desktop/src/main/services/server-service.ts
+++ b/apps/desktop/src/main/services/server-service.ts
@@ -1,10 +1,14 @@
import { createDebugger, ServerConfig } from '@colanode/core';
import axios from 'axios';
+import ms from 'ms';
+
+import { EventEmitter } from 'events';
-import { databaseService } from '@/main/data/database-service';
import { mapServer } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
import { Server } from '@/shared/types/servers';
+import { AppService } from '@/main/services/app-service';
+import { EventLoop } from '@/shared/lib/event-loop';
type ServerState = {
isAvailable: boolean;
@@ -13,76 +17,38 @@ type ServerState = {
count: number;
};
-class ServerService {
- private readonly states: Map<string, ServerState> = new Map();
+export class ServerService extends EventEmitter {
private readonly debug = createDebugger('desktop:service:server');
+ private readonly appService: AppService;
- public async syncServers() {
- this.debug('Syncing servers');
-
- const rows = await databaseService.appDatabase
- .selectFrom('servers')
- .selectAll()
- .execute();
-
- const servers = rows.map(mapServer);
- for (const server of servers) {
- await this.syncServer(server);
- }
- }
-
- public isAvailable(domain: string) {
- const state = this.states.get(domain);
- return state?.isAvailable ?? false;
- }
+ private state: ServerState | null = null;
+ private eventLoop: EventLoop;
- public async createServer(domain: string): Promise<Server | null> {
- if (this.states.has(domain)) {
- return null;
- }
+ public readonly server: Server;
+ public readonly synapseUrl: string;
+ public readonly apiBaseUrl: string;
- const config = await this.fetchServerConfig(domain);
- if (config === null) {
- return null;
- }
+ constructor(appService: AppService, server: Server) {
+ super();
- const createdServer = await databaseService.appDatabase
- .insertInto('servers')
- .returningAll()
- .values({
- domain,
- name: config.name,
- avatar: config.avatar,
- attributes: JSON.stringify(config.attributes),
- version: config.version,
- created_at: new Date().toISOString(),
- })
- .executeTakeFirst();
-
- if (!createdServer) {
- return null;
- }
+ this.appService = appService;
+ this.server = server;
+ this.synapseUrl = ServerService.buildSynapseUrl(server.domain);
+ this.apiBaseUrl = ServerService.buildApiBaseUrl(server.domain);
- const server = mapServer(createdServer);
- eventBus.publish({
- type: 'server_created',
- server,
+ this.eventLoop = new EventLoop(ms('1 minute'), ms('1 second'), () => {
+ this.sync();
});
+ this.eventLoop.start();
+ }
- const state: ServerState = {
- isAvailable: true,
- lastCheckedAt: new Date(),
- lastCheckedSuccessfullyAt: new Date(),
- count: 1,
- };
-
- this.states.set(domain, state);
- return server;
+ public isAvailable() {
+ return this.state?.isAvailable ?? false;
}
- private async syncServer(server: Server) {
- const config = await this.fetchServerConfig(server.domain);
- const existingState = this.states.get(server.domain);
+ private async sync() {
+ const config = await ServerService.fetchServerConfig(this.server.domain);
+ const existingState = this.state;
const newState: ServerState = {
isAvailable: config !== null,
@@ -91,24 +57,20 @@ class ServerService {
count: existingState ? existingState.count + 1 : 1,
};
- this.states.set(server.domain, newState);
+ this.state = newState;
const wasAvailable = existingState?.isAvailable ?? false;
const isAvailable = newState.isAvailable;
if (wasAvailable !== isAvailable) {
- eventBus.publish({
- type: 'server_availability_changed',
- server,
- isAvailable,
- });
+ this.emit('availability_change', isAvailable);
}
this.debug(
- `Server ${server.domain} is ${isAvailable ? 'available' : 'unavailable'}`
+ `Server ${this.server.domain} is ${isAvailable ? 'available' : 'unavailable'}`
);
if (config) {
- const updatedServer = await databaseService.appDatabase
+ const updatedServer = await this.appService.database
.updateTable('servers')
.returningAll()
.set({
@@ -118,9 +80,14 @@ class ServerService {
name: config.name,
version: config.version,
})
- .where('domain', '=', server.domain)
+ .where('domain', '=', this.server.domain)
.executeTakeFirst();
+ this.server.attributes = config.attributes;
+ this.server.avatar = config.avatar;
+ this.server.name = config.name;
+ this.server.version = config.version;
+
if (updatedServer) {
eventBus.publish({
type: 'server_updated',
@@ -130,9 +97,7 @@ class ServerService {
}
}
- public async fetchServerConfig(domain: string) {
- this.debug(`Fetching server config for ${domain}`);
-
+ public static async fetchServerConfig(domain: string) {
const baseUrl = this.buildApiBaseUrl(domain);
const configUrl = `${baseUrl}/v1/config`;
try {
@@ -143,15 +108,13 @@ class ServerService {
}
}
- public buildApiBaseUrl(domain: string) {
+ private static buildApiBaseUrl(domain: string) {
const protocol = domain.startsWith('localhost:') ? 'http' : 'https';
return `${protocol}://${domain}/client`;
}
- public buildSynapseUrl(domain: string) {
+ private static buildSynapseUrl(domain: string) {
const protocol = domain.startsWith('localhost:') ? 'ws' : 'wss';
return `${protocol}://${domain}/client/v1/synapse`;
}
}
-
-export const serverService = new ServerService();
diff --git a/apps/desktop/src/main/services/socket-service.ts b/apps/desktop/src/main/services/socket-service.ts
deleted file mode 100644
index a5679655..00000000
--- a/apps/desktop/src/main/services/socket-service.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { createDebugger, Message } from '@colanode/core';
-
-import { SelectAccount } from '@/main/data/app/schema';
-import { serverService } from '@/main/services/server-service';
-import { SocketConnection } from '@/main/services/socket-connection';
-
-class SocketService {
- private readonly debug = createDebugger('desktop:service:socket');
- private readonly sockets: Map<string, SocketConnection> = new Map();
-
- constructor() {}
-
- public sendMessage(accountId: string, message: Message): boolean {
- const connection = this.sockets.get(accountId);
- if (!connection) {
- return false;
- }
-
- return connection.sendMessage(message);
- }
-
- public checkConnection(account: SelectAccount) {
- const socket = this.sockets.get(account.id);
- if (socket) {
- socket.checkConnection();
- return;
- }
-
- const synapseUrl = serverService.buildSynapseUrl(account.server);
- const connection = new SocketConnection(synapseUrl, account);
- connection.init();
-
- this.sockets.set(account.id, connection);
- }
-
- public removeConnection(accountId: string) {
- const connection = this.sockets.get(accountId);
- if (connection) {
- connection.close();
- this.sockets.delete(accountId);
- }
- }
-
- public isConnected(accountId: string): boolean {
- const connection = this.sockets.get(accountId);
- return connection?.isConnected() ?? false;
- }
-}
-
-export const socketService = new SocketService();
diff --git a/apps/desktop/src/main/services/sync-service.ts b/apps/desktop/src/main/services/sync-service.ts
deleted file mode 100644
index 0850cea1..00000000
--- a/apps/desktop/src/main/services/sync-service.ts
+++ /dev/null
@@ -1,431 +0,0 @@
-import {
- createDebugger,
- SynchronizerInput,
- SynchronizerOutputMessage,
-} from '@colanode/core';
-import { Kysely } from 'kysely';
-
-import { databaseService } from '@/main/data/database-service';
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { UserSynchronizer } from '@/main/synchronizers/users';
-import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';
-import { CollaborationSynchronizer } from '@/main/synchronizers/collaborations';
-import { EntryTransactionSynchronizer } from '@/main/synchronizers/entry-transactions';
-import { MessageSynchronizer } from '@/main/synchronizers/messages';
-import { MessageReactionSynchronizer } from '@/main/synchronizers/message-reactions';
-import { FileSynchronizer } from '@/main/synchronizers/files';
-import { EntryInteractionSynchronizer } from '@/main/synchronizers/entry-interactions';
-import { FileInteractionSynchronizer } from '@/main/synchronizers/file-interactions';
-import { MessageInteractionSynchronizer } from '@/main/synchronizers/message-interactions';
-import { FileTombstoneSynchronizer } from '@/main/synchronizers/file-tombstones';
-import { MessageTombstoneSynchronizer } from '@/main/synchronizers/message-tombstones';
-import { eventBus } from '@/shared/lib/event-bus';
-
-class SyncService {
- private readonly debug = createDebugger('desktop:service:sync');
- private readonly synchronizers: Map<
- string,
- BaseSynchronizer<SynchronizerInput>
- > = new Map();
-
- constructor() {
- eventBus.subscribe((event) => {
- if (event.type === 'workspace_deleted') {
- this.removeWorkspaceSynchronizers(event.workspace.userId);
- } else if (event.type === 'account_deleted') {
- this.removeAccountSynchronizers(event.account.id);
- } else if (event.type === 'collaboration_deleted') {
- this.removeRootNodeSynchronizers(event.userId, event.entryId);
- }
- });
- }
-
- public async initSynchronizers(userId: string) {
- const workspace = await databaseService.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .where('user_id', '=', userId)
- .executeTakeFirst();
-
- if (!workspace) {
- return;
- }
-
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- await this.initSynchronizer(
- userId,
- workspace.account_id,
- workspaceDatabase,
- {
- type: 'users',
- }
- );
-
- await this.initSynchronizer(
- userId,
- workspace.account_id,
- workspaceDatabase,
- {
- type: 'collaborations',
- }
- );
-
- const collaborations = await workspaceDatabase
- .selectFrom('collaborations')
- .selectAll()
- .execute();
-
- for (const collaboration of collaborations) {
- const rootId = collaboration.entry_id;
- if (collaboration.deleted_at) {
- this.removeRootNodeSynchronizers(userId, rootId);
- } else {
- await this.initRootNodeSynchronizers(
- userId,
- workspace.account_id,
- rootId,
- workspaceDatabase
- );
- }
- }
- }
-
- public processSyncMessage(
- message: SynchronizerOutputMessage<SynchronizerInput>
- ) {
- const synchronizer = this.synchronizers.get(message.id);
- if (!synchronizer) {
- return;
- }
-
- synchronizer.sync(message);
- }
-
- private async initSynchronizer(
- userId: string,
- accountId: string,
- workspaceDatabase: Kysely<WorkspaceDatabaseSchema>,
- input: SynchronizerInput
- ) {
- this.debug('Initializing synchronizer', input);
- const synchronizer = this.buildSynchronizer(
- userId,
- accountId,
- workspaceDatabase,
- input
- );
-
- if (!synchronizer) {
- return;
- }
-
- const existingSynchronizer = this.synchronizers.get(synchronizer.id);
- if (existingSynchronizer) {
- this.debug(
- 'Synchronizer already exists, pinging',
- existingSynchronizer.id
- );
- existingSynchronizer.ping();
- return;
- }
-
- this.synchronizers.set(synchronizer.id, synchronizer);
- await synchronizer.init();
- }
-
- private buildSynchronizer(
- userId: string,
- accountId: string,
- workspaceDatabase: Kysely<WorkspaceDatabaseSchema>,
- input: SynchronizerInput
- ): BaseSynchronizer<SynchronizerInput> | null {
- if (input.type === 'users') {
- return new UserSynchronizer(userId, accountId, input, workspaceDatabase);
- }
-
- if (input.type === 'collaborations') {
- return new CollaborationSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'files') {
- return new FileSynchronizer(userId, accountId, input, workspaceDatabase);
- }
-
- if (input.type === 'messages') {
- return new MessageSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'message_reactions') {
- return new MessageReactionSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'entry_transactions') {
- return new EntryTransactionSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'entry_interactions') {
- return new EntryInteractionSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'file_interactions') {
- return new FileInteractionSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'message_interactions') {
- return new MessageInteractionSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'file_tombstones') {
- return new FileTombstoneSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- if (input.type === 'message_tombstones') {
- return new MessageTombstoneSynchronizer(
- userId,
- accountId,
- input,
- workspaceDatabase
- );
- }
-
- return null;
- }
-
- private async initRootNodeSynchronizers(
- userId: string,
- accountId: string,
- rootId: string,
- workspaceDatabase: Kysely<WorkspaceDatabaseSchema>
- ) {
- this.debug('Initializing root node synchronizers', rootId);
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'entry_transactions',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'messages',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'message_reactions',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'files',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'entry_interactions',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'file_interactions',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'message_interactions',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'file_tombstones',
- rootId,
- });
-
- await this.initSynchronizer(userId, accountId, workspaceDatabase, {
- type: 'message_tombstones',
- rootId,
- });
- }
-
- private async removeRootNodeSynchronizers(userId: string, rootId: string) {
- this.debug('Removing root node synchronizers', rootId);
-
- const keys = Array.from(this.synchronizers.keys());
-
- for (const key of keys) {
- const synchronizer = this.synchronizers.get(key);
- if (!synchronizer) {
- continue;
- }
-
- if (synchronizer.userId !== userId) {
- continue;
- }
-
- if (!this.isRootNodeSynchronizer(synchronizer, rootId)) {
- continue;
- }
-
- await synchronizer.delete();
- this.synchronizers.delete(key);
-
- this.debug('Removed root node synchronizer', userId, synchronizer.input);
- }
- }
-
- private async removeWorkspaceSynchronizers(userId: string) {
- const keys = Array.from(this.synchronizers.keys());
-
- for (const key of keys) {
- const synchronizer = this.synchronizers.get(key);
- if (!synchronizer) {
- continue;
- }
-
- if (synchronizer.userId === userId) {
- await synchronizer.delete();
- this.synchronizers.delete(key);
-
- this.debug(
- 'Removed workspace synchronizer',
- userId,
- synchronizer.input
- );
- }
- }
- }
-
- private async removeAccountSynchronizers(accountId: string) {
- const keys = Array.from(this.synchronizers.keys());
-
- for (const key of keys) {
- const synchronizer = this.synchronizers.get(key);
- if (!synchronizer) {
- continue;
- }
-
- if (synchronizer.accountId === accountId) {
- await synchronizer.delete();
- this.synchronizers.delete(key);
-
- this.debug(
- 'Removed account synchronizer',
- accountId,
- synchronizer.input
- );
- }
- }
- }
-
- private isRootNodeSynchronizer(
- synchronizer: BaseSynchronizer<SynchronizerInput>,
- rootId: string
- ) {
- if (
- synchronizer.input.type === 'entry_transactions' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'entry_interactions' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'messages' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'message_reactions' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'message_interactions' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'message_tombstones' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'files' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'file_interactions' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- if (
- synchronizer.input.type === 'file_tombstones' &&
- synchronizer.input.rootId === rootId
- ) {
- return true;
- }
-
- return false;
- }
-}
-
-export const syncService = new SyncService();
diff --git a/apps/desktop/src/main/services/collaboration-service.ts b/apps/desktop/src/main/services/workspaces/collaboration-service.ts
similarity index 71%
rename from apps/desktop/src/main/services/collaboration-service.ts
rename to apps/desktop/src/main/services/workspaces/collaboration-service.ts
index c667c09f..2d0030d1 100644
--- a/apps/desktop/src/main/services/collaboration-service.ts
+++ b/apps/desktop/src/main/services/workspaces/collaboration-service.ts
@@ -1,23 +1,22 @@
import { SyncCollaborationData, createDebugger } from '@colanode/core';
-import { databaseService } from '@/main/data/database-service';
import { eventBus } from '@/shared/lib/event-bus';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
-class CollaborationService {
+export class CollaborationService {
private readonly debug = createDebugger('desktop:service:collaboration');
+ private readonly workspace: WorkspaceService;
- public async syncServerCollaboration(
- userId: string,
- collaboration: SyncCollaborationData
- ) {
+ constructor(workspace: WorkspaceService) {
+ this.workspace = workspace;
+ }
+
+ public async syncServerCollaboration(collaboration: SyncCollaborationData) {
this.debug(
- `Applying server collaboration: ${collaboration.entryId} for user ${userId}`
+ `Applying server collaboration: ${collaboration.entryId} for workspace ${this.workspace.id}`
);
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- await workspaceDatabase
+ await this.workspace.database
.insertInto('collaborations')
.values({
entry_id: collaboration.entryId,
@@ -41,59 +40,59 @@ class CollaborationService {
.execute();
if (collaboration.deletedAt) {
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('entries')
.where('root_id', '=', collaboration.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('entry_transactions')
.where('root_id', '=', collaboration.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('entry_interactions')
.where('root_id', '=', collaboration.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('messages')
.where('root_id', '=', collaboration.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('message_reactions')
.where('root_id', '=', collaboration.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('message_interactions')
.where('root_id', '=', collaboration.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('files')
.where('root_id', '=', collaboration.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('file_interactions')
.where('root_id', '=', collaboration.entryId)
.execute();
eventBus.publish({
type: 'collaboration_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entryId: collaboration.entryId,
});
} else {
eventBus.publish({
type: 'collaboration_created',
- userId,
entryId: collaboration.entryId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
});
}
}
}
-
-export const collaborationService = new CollaborationService();
diff --git a/apps/desktop/src/main/services/entry-service.ts b/apps/desktop/src/main/services/workspaces/entry-service.ts
similarity index 82%
rename from apps/desktop/src/main/services/entry-service.ts
rename to apps/desktop/src/main/services/workspaces/entry-service.ts
index 6744b517..eb81c1cd 100644
--- a/apps/desktop/src/main/services/entry-service.ts
+++ b/apps/desktop/src/main/services/workspaces/entry-service.ts
@@ -21,16 +21,15 @@ import {
} from '@colanode/core';
import { decodeState, YDoc } from '@colanode/crdt';
-import { databaseService } from '@/main/data/database-service';
-import { SelectEntryTransaction } from '@/main/data/workspace/schema';
+import { SelectEntryTransaction } from '@/main/databases/workspace';
import {
fetchEntry,
- fetchUser,
mapEntry,
mapEntryInteraction,
mapEntryTransaction,
} from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
const UPDATE_RETRIES_LIMIT = 20;
@@ -47,30 +46,30 @@ export type UpdateEntryResult =
| 'failed'
| 'invalid_attributes';
-class EntryService {
+export class EntryService {
private readonly debug = createDebugger('desktop:service:entry');
+ private readonly workspace: WorkspaceService;
- public async createEntry(userId: string, input: CreateEntryInput) {
- this.debug(`Creating ${Array.isArray(input) ? 'entries' : 'entry'}`);
-
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
+ constructor(workspaceService: WorkspaceService) {
+ this.workspace = workspaceService;
+ }
- const user = await fetchUser(workspaceDatabase, userId);
- if (!user) {
- throw new Error('User not found');
- }
+ public async createEntry(input: CreateEntryInput) {
+ this.debug(`Creating ${Array.isArray(input) ? 'entries' : 'entry'}`);
let root: Entry | null = null;
if (input.parentId) {
- const parent = await fetchEntry(workspaceDatabase, input.parentId);
+ const parent = await fetchEntry(this.workspace.database, input.parentId);
if (parent) {
if (parent.id === parent.root_id) {
root = mapEntry(parent);
} else {
- const rootRow = await fetchEntry(workspaceDatabase, parent.root_id);
+ const rootRow = await fetchEntry(
+ this.workspace.database,
+ parent.root_id
+ );
if (rootRow) {
root = mapEntry(rootRow);
}
@@ -82,8 +81,8 @@ class EntryService {
!canCreateEntry(
{
user: {
- userId,
- role: user.role,
+ userId: this.workspace.userId,
+ role: this.workspace.role,
},
root: root,
},
@@ -103,7 +102,7 @@ class EntryService {
const transactionId = generateId(IdType.Transaction);
const text = extractEntryText(input.id, input.attributes);
- const { createdEntry, createdMutation } = await workspaceDatabase
+ const { createdEntry, createdMutation } = await this.workspace.database
.transaction()
.execute(async (trx) => {
const createdEntry = await trx
@@ -114,7 +113,7 @@ class EntryService {
root_id: root?.id ?? input.id,
attributes: JSON.stringify(input.attributes),
created_at: createdAt,
- created_by: userId,
+ created_by: this.workspace.userId,
transaction_id: transactionId,
})
.executeTakeFirst();
@@ -133,7 +132,7 @@ class EntryService {
operation: TransactionOperation.Create,
data: update,
created_at: createdAt,
- created_by: userId,
+ created_by: this.workspace.userId,
version: 0n,
})
.executeTakeFirst();
@@ -181,7 +180,8 @@ class EntryService {
eventBus.publish({
type: 'entry_created',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(createdEntry),
});
@@ -189,21 +189,15 @@ class EntryService {
throw new Error('Failed to create mutation');
}
- this.debug(`Created mutation ${createdMutation.id}`);
-
- eventBus.publish({
- type: 'mutation_created',
- userId,
- });
+ this.workspace.mutations.triggerSync();
}
public async updateEntry<T extends EntryAttributes>(
entryId: string,
- userId: string,
updater: (attributes: T) => T
): Promise<UpdateEntryResult> {
for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryUpdateEntry(entryId, userId, updater);
+ const result = await this.tryUpdateEntry(entryId, updater);
if (result) {
return result;
}
@@ -214,25 +208,16 @@ class EntryService {
private async tryUpdateEntry<T extends EntryAttributes>(
entryId: string,
- userId: string,
updater: (attributes: T) => T
): Promise<UpdateEntryResult | null> {
this.debug(`Updating entry ${entryId}`);
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const entryRow = await fetchEntry(workspaceDatabase, entryId);
+ const entryRow = await fetchEntry(this.workspace.database, entryId);
if (!entryRow) {
return 'not_found';
}
- const user = await fetchUser(workspaceDatabase, userId);
- if (!user) {
- return 'not_found';
- }
-
- const root = await fetchEntry(workspaceDatabase, entryRow.root_id);
+ const root = await fetchEntry(this.workspace.database, entryRow.root_id);
if (!root) {
return 'not_found';
}
@@ -243,7 +228,7 @@ class EntryService {
const updatedAttributes = updater(entry.attributes as T);
const ydoc = new YDoc();
- const previousTransactions = await workspaceDatabase
+ const previousTransactions = await this.workspace.database
.selectFrom('entry_transactions')
.where('entry_id', '=', entryId)
.selectAll()
@@ -266,8 +251,8 @@ class EntryService {
!canUpdateEntry(
{
user: {
- userId,
- role: user.role,
+ userId: this.workspace.userId,
+ role: this.workspace.role,
},
root: mapEntry(root),
entry: entry,
@@ -280,7 +265,7 @@ class EntryService {
const text = extractEntryText(entryId, updatedAttributes);
- const { updatedEntry, createdMutation } = await workspaceDatabase
+ const { updatedEntry, createdMutation } = await this.workspace.database
.transaction()
.execute(async (trx) => {
const updatedEntry = await trx
@@ -289,7 +274,7 @@ class EntryService {
.set({
attributes: JSON.stringify(ydoc.getAttributes()),
updated_at: updatedAt,
- updated_by: userId,
+ updated_by: this.workspace.userId,
transaction_id: transactionId,
})
.where('id', '=', entryId)
@@ -310,7 +295,7 @@ class EntryService {
operation: TransactionOperation.Update,
data: update,
created_at: updatedAt,
- created_by: userId,
+ created_by: this.workspace.userId,
version: 0n,
})
.executeTakeFirst();
@@ -359,7 +344,8 @@ class EntryService {
eventBus.publish({
type: 'entry_updated',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(updatedEntry),
});
} else {
@@ -367,14 +353,7 @@ class EntryService {
}
if (createdMutation) {
- this.debug(`Created mutation ${createdMutation.id} for entry ${entryId}`);
-
- eventBus.publish({
- type: 'mutation_created',
- userId,
- });
- } else {
- this.debug(`Failed to create mutation for entry ${entryId}`);
+ this.workspace.mutations.triggerSync();
}
if (updatedEntry) {
@@ -384,21 +363,13 @@ class EntryService {
return null;
}
- public async deleteEntry(entryId: string, userId: string) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const user = await fetchUser(workspaceDatabase, userId);
- if (!user) {
- throw new Error('User not found');
- }
-
- const entry = await fetchEntry(workspaceDatabase, entryId);
+ public async deleteEntry(entryId: string) {
+ const entry = await fetchEntry(this.workspace.database, entryId);
if (!entry) {
throw new Error('Entry not found');
}
- const root = await fetchEntry(workspaceDatabase, entry.root_id);
+ const root = await fetchEntry(this.workspace.database, entry.root_id);
if (!root) {
throw new Error('Root not found');
}
@@ -406,8 +377,8 @@ class EntryService {
if (
!canDeleteEntry({
user: {
- userId,
- role: user.role,
+ userId: this.workspace.userId,
+ role: this.workspace.role,
},
root: mapEntry(root),
entry: mapEntry(entry),
@@ -416,7 +387,7 @@ class EntryService {
throw new Error('Insufficient permissions');
}
- const { deletedEntry, createdMutation } = await workspaceDatabase
+ const { deletedEntry, createdMutation } = await this.workspace.database
.transaction()
.execute(async (trx) => {
const deletedEntry = await trx
@@ -441,7 +412,7 @@ class EntryService {
operation: TransactionOperation.Delete,
data: null,
created_at: new Date().toISOString(),
- created_by: userId,
+ created_by: this.workspace.userId,
version: 0n,
})
.executeTakeFirst();
@@ -472,7 +443,8 @@ class EntryService {
eventBus.publish({
type: 'entry_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(deletedEntry),
});
} else {
@@ -480,43 +452,29 @@ class EntryService {
}
if (createdMutation) {
- this.debug(`Created mutation ${createdMutation.id} for entry ${entryId}`);
-
- eventBus.publish({
- type: 'mutation_created',
- userId,
- });
- } else {
- this.debug(`Failed to create mutation for entry ${entryId}`);
+ this.workspace.mutations.triggerSync();
}
}
- public async applyServerTransaction(
- userId: string,
- transaction: SyncEntryTransactionData
- ) {
+ public async applyServerTransaction(transaction: SyncEntryTransactionData) {
if (transaction.operation === TransactionOperation.Create) {
- await this.applyServerCreateTransaction(userId, transaction);
+ await this.applyServerCreateTransaction(transaction);
} else if (transaction.operation === TransactionOperation.Update) {
- await this.applyServerUpdateTransaction(userId, transaction);
+ await this.applyServerUpdateTransaction(transaction);
} else if (transaction.operation === TransactionOperation.Delete) {
- await this.applyServerDeleteTransaction(userId, transaction);
+ await this.applyServerDeleteTransaction(transaction);
}
}
private async applyServerCreateTransaction(
- userId: string,
transaction: SyncCreateEntryTransactionData
) {
this.debug(
`Applying server create transaction ${transaction.id} for entry ${transaction.entryId}`
);
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
const version = BigInt(transaction.version);
- const existingTransaction = await workspaceDatabase
+ const existingTransaction = await this.workspace.database
.selectFrom('entry_transactions')
.select(['id', 'version', 'server_created_at'])
.where('id', '=', transaction.id)
@@ -533,7 +491,7 @@ class EntryService {
return;
}
- await workspaceDatabase
+ await this.workspace.database
.updateTable('entry_transactions')
.set({
version,
@@ -553,7 +511,7 @@ class EntryService {
const attributes = ydoc.getAttributes<EntryAttributes>();
const text = extractEntryText(transaction.entryId, attributes);
- const { createdEntry } = await workspaceDatabase
+ const { createdEntry } = await this.workspace.database
.transaction()
.execute(async (trx) => {
const createdEntry = await trx
@@ -611,20 +569,17 @@ class EntryService {
eventBus.publish({
type: 'entry_created',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(createdEntry),
});
}
private async applyServerUpdateTransaction(
- userId: string,
transaction: SyncUpdateEntryTransactionData
) {
for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryApplyServerUpdateTransaction(
- userId,
- transaction
- );
+ const result = await this.tryApplyServerUpdateTransaction(transaction);
if (result) {
return;
@@ -633,14 +588,10 @@ class EntryService {
}
private async tryApplyServerUpdateTransaction(
- userId: string,
transaction: SyncUpdateEntryTransactionData
): Promise<boolean> {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
const version = BigInt(transaction.version);
- const existingTransaction = await workspaceDatabase
+ const existingTransaction = await this.workspace.database
.selectFrom('entry_transactions')
.select(['id', 'version', 'server_created_at'])
.where('id', '=', transaction.id)
@@ -657,7 +608,7 @@ class EntryService {
return true;
}
- await workspaceDatabase
+ await this.workspace.database
.updateTable('entry_transactions')
.set({
version,
@@ -672,7 +623,7 @@ class EntryService {
return true;
}
- const entry = await workspaceDatabase
+ const entry = await this.workspace.database
.selectFrom('entries')
.selectAll()
.where('id', '=', transaction.entryId)
@@ -682,7 +633,7 @@ class EntryService {
return false;
}
- const previousTransactions = await workspaceDatabase
+ const previousTransactions = await this.workspace.database
.selectFrom('entry_transactions')
.selectAll()
.where('entry_id', '=', transaction.entryId)
@@ -701,7 +652,7 @@ class EntryService {
const attributes = ydoc.getAttributes<EntryAttributes>();
const text = extractEntryText(transaction.entryId, attributes);
- const { updatedEntry } = await workspaceDatabase
+ const { updatedEntry } = await this.workspace.database
.transaction()
.execute(async (trx) => {
const updatedEntry = await trx
@@ -770,7 +721,8 @@ class EntryService {
eventBus.publish({
type: 'entry_updated',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(updatedEntry),
});
@@ -778,17 +730,13 @@ class EntryService {
}
private async applyServerDeleteTransaction(
- userId: string,
transaction: SyncDeleteEntryTransactionData
) {
this.debug(
`Applying server delete transaction ${transaction.id} for entry ${transaction.entryId}`
);
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const { deletedEntry } = await workspaceDatabase
+ const { deletedEntry } = await this.workspace.database
.transaction()
.execute(async (trx) => {
const deletedEntry = await trx
@@ -825,19 +773,14 @@ class EntryService {
eventBus.publish({
type: 'entry_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(deletedEntry),
});
}
- public async revertCreateTransaction(
- userId: string,
- transaction: LocalCreateTransaction
- ) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const entry = await workspaceDatabase
+ public async revertCreateTransaction(transaction: LocalCreateTransaction) {
+ const entry = await this.workspace.database
.selectFrom('entries')
.selectAll()
.where('id', '=', transaction.entryId)
@@ -847,7 +790,7 @@ class EntryService {
return;
}
- const transactionRow = await workspaceDatabase
+ const transactionRow = await this.workspace.database
.selectFrom('entry_transactions')
.selectAll()
.where('id', '=', transaction.id)
@@ -857,7 +800,7 @@ class EntryService {
return;
}
- await workspaceDatabase.transaction().execute(async (tx) => {
+ await this.workspace.database.transaction().execute(async (tx) => {
await tx
.deleteFrom('entries')
.where('id', '=', transaction.entryId)
@@ -881,17 +824,15 @@ class EntryService {
eventBus.publish({
type: 'entry_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(entry),
});
}
- public async revertUpdateTransaction(
- userId: string,
- transaction: LocalUpdateTransaction
- ) {
+ public async revertUpdateTransaction(transaction: LocalUpdateTransaction) {
for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryRevertUpdateTransaction(userId, transaction);
+ const result = await this.tryRevertUpdateTransaction(transaction);
if (result) {
return;
@@ -900,13 +841,9 @@ class EntryService {
}
private async tryRevertUpdateTransaction(
- userId: string,
transaction: LocalUpdateTransaction
): Promise<boolean> {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const entry = await workspaceDatabase
+ const entry = await this.workspace.database
.selectFrom('entries')
.selectAll()
.where('id', '=', transaction.entryId)
@@ -914,17 +851,17 @@ class EntryService {
if (!entry) {
// Make sure we don't have any data left behind
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('entry_transactions')
.where('id', '=', transaction.id)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('entry_interactions')
.where('entry_id', '=', transaction.entryId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('texts')
.where('id', '=', transaction.entryId)
.execute();
@@ -932,7 +869,7 @@ class EntryService {
return true;
}
- const transactionRow = await workspaceDatabase
+ const transactionRow = await this.workspace.database
.selectFrom('entry_transactions')
.selectAll()
.where('id', '=', transaction.id)
@@ -942,7 +879,7 @@ class EntryService {
return true;
}
- const previousTransactions = await workspaceDatabase
+ const previousTransactions = await this.workspace.database
.selectFrom('entry_transactions')
.selectAll()
.where('entry_id', '=', transaction.entryId)
@@ -970,7 +907,7 @@ class EntryService {
const attributes = ydoc.getAttributes<EntryAttributes>();
const text = extractEntryText(transaction.entryId, attributes);
- const updatedEntry = await workspaceDatabase
+ const updatedEntry = await this.workspace.database
.transaction()
.execute(async (trx) => {
const updatedEntry = await trx
@@ -1017,7 +954,8 @@ class EntryService {
if (updatedEntry) {
eventBus.publish({
type: 'entry_updated',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(updatedEntry),
});
@@ -1027,14 +965,8 @@ class EntryService {
return false;
}
- public async revertDeleteTransaction(
- userId: string,
- transaction: LocalDeleteTransaction
- ) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const transactionRow = await workspaceDatabase
+ public async revertDeleteTransaction(transaction: LocalDeleteTransaction) {
+ const transactionRow = await this.workspace.database
.selectFrom('entry_transactions')
.selectAll()
.where('id', '=', transaction.id)
@@ -1044,7 +976,7 @@ class EntryService {
return;
}
- const previousTransactions = await workspaceDatabase
+ const previousTransactions = await this.workspace.database
.selectFrom('entry_transactions')
.selectAll()
.where('entry_id', '=', transaction.entryId)
@@ -1073,7 +1005,7 @@ class EntryService {
const attributes = ydoc.getAttributes<EntryAttributes>();
const text = extractEntryText(transaction.entryId, attributes);
- const createdEntry = await workspaceDatabase
+ const createdEntry = await this.workspace.database
.transaction()
.execute(async (trx) => {
const createdEntry = await trx
@@ -1133,7 +1065,8 @@ class EntryService {
if (createdEntry) {
eventBus.publish({
type: 'entry_created',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entry: mapEntry(createdEntry),
});
@@ -1144,13 +1077,9 @@ class EntryService {
}
public async syncServerEntryInteraction(
- userId: string,
entryInteraction: SyncEntryInteractionData
) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const existingEntryInteraction = await workspaceDatabase
+ const existingEntryInteraction = await this.workspace.database
.selectFrom('entry_interactions')
.selectAll()
.where('entry_id', '=', entryInteraction.entryId)
@@ -1166,7 +1095,7 @@ class EntryService {
}
}
- const createdEntryInteraction = await workspaceDatabase
+ const createdEntryInteraction = await this.workspace.database
.insertInto('entry_interactions')
.returningAll()
.values({
@@ -1196,7 +1125,8 @@ class EntryService {
eventBus.publish({
type: 'entry_interaction_updated',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
entryInteraction: mapEntryInteraction(createdEntryInteraction),
});
@@ -1205,5 +1135,3 @@ class EntryService {
);
}
}
-
-export const entryService = new EntryService();
diff --git a/apps/desktop/src/main/services/workspaces/file-service.ts b/apps/desktop/src/main/services/workspaces/file-service.ts
new file mode 100644
index 00000000..d74d9dd9
--- /dev/null
+++ b/apps/desktop/src/main/services/workspaces/file-service.ts
@@ -0,0 +1,831 @@
+import {
+ CompleteUploadOutput,
+ CreateDownloadOutput,
+ CreateUploadOutput,
+ FileStatus,
+ SyncFileData,
+ SyncFileInteractionData,
+ SyncFileTombstoneData,
+ createDebugger,
+} from '@colanode/core';
+import axios from 'axios';
+import ms from 'ms';
+
+import fs from 'fs';
+import path from 'path';
+
+import {
+ getWorkspaceFilesDirectoryPath,
+ getWorkspaceTempFilesDirectoryPath,
+ mapFile,
+ mapFileInteraction,
+ mapFileState,
+} from '@/main/utils';
+import { eventBus } from '@/shared/lib/event-bus';
+import { DownloadStatus, UploadStatus } from '@/shared/types/files';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { EventLoop } from '@/shared/lib/event-loop';
+import { SelectFileState } from '@/main/databases/workspace';
+
+const UPLOAD_RETRIES_LIMIT = 10;
+const DOWNLOAD_RETRIES_LIMIT = 10;
+
+export class FileService {
+ private readonly debug = createDebugger('desktop:service:file');
+ private readonly workspace: WorkspaceService;
+ private readonly filesDir: string;
+ private readonly tempFilesDir: string;
+
+ private readonly uploadsEventLoop: EventLoop;
+ private readonly downloadsEventLoop: EventLoop;
+ private readonly cleanupEventLoop: EventLoop;
+
+ constructor(workspace: WorkspaceService) {
+ this.workspace = workspace;
+ this.filesDir = getWorkspaceFilesDirectoryPath(
+ this.workspace.accountId,
+ this.workspace.id
+ );
+
+ this.tempFilesDir = getWorkspaceTempFilesDirectoryPath(
+ this.workspace.accountId,
+ this.workspace.id
+ );
+
+ if (!fs.existsSync(this.filesDir)) {
+ fs.mkdirSync(this.filesDir, { recursive: true });
+ }
+
+ if (!fs.existsSync(this.tempFilesDir)) {
+ fs.mkdirSync(this.tempFilesDir, { recursive: true });
+ }
+
+ this.uploadsEventLoop = new EventLoop(
+ ms('1 minute'),
+ ms('1 second'),
+ () => {
+ this.uploadFiles();
+ }
+ );
+
+ this.downloadsEventLoop = new EventLoop(
+ ms('1 minute'),
+ ms('1 second'),
+ () => {
+ this.downloadFiles();
+ }
+ );
+
+ this.cleanupEventLoop = new EventLoop(
+ ms('10 minutes'),
+ ms('5 minutes'),
+ () => {
+ this.cleanDeletedFiles();
+ this.cleanTempFiles();
+ }
+ );
+
+ this.uploadsEventLoop.start();
+ this.downloadsEventLoop.start();
+ this.cleanupEventLoop.start();
+ }
+
+ public copyFileToWorkspace(
+ filePath: string,
+ fileId: string,
+ fileExtension: string
+ ): void {
+ const destinationFilePath = this.buildFilePath(fileId, fileExtension);
+
+ if (!fs.existsSync(this.filesDir)) {
+ fs.mkdirSync(this.filesDir, { recursive: true });
+ }
+
+ this.debug(`Copying file ${filePath} to ${destinationFilePath}`);
+ fs.copyFileSync(filePath, destinationFilePath);
+
+ // check if the file is in the temp files directory. If it is in
+ // temp files directory it means it has been pasted or dragged
+ // therefore we need to delete it
+ const fileDirectory = path.dirname(filePath);
+ if (fileDirectory === this.tempFilesDir) {
+ fs.rmSync(filePath);
+ }
+ }
+
+ public deleteFile(id: string, extension: string): void {
+ const filePath = this.buildFilePath(id, extension);
+
+ this.debug(`Deleting file ${filePath}`);
+ fs.rmSync(filePath, { force: true });
+ }
+
+ public triggerUploads(): void {
+ this.uploadsEventLoop.trigger();
+ }
+
+ public triggerDownloads(): void {
+ this.downloadsEventLoop.trigger();
+ }
+
+ public destroy(): void {
+ this.uploadsEventLoop.stop();
+ this.downloadsEventLoop.stop();
+ this.cleanupEventLoop.stop();
+ }
+
+ private async uploadFiles(): Promise<void> {
+ if (!this.workspace.account.server.isAvailable()) {
+ return;
+ }
+
+ this.debug(`Uploading files for workspace ${this.workspace.id}`);
+
+ const uploads = await this.workspace.database
+ .selectFrom('file_states')
+ .selectAll()
+ .where('upload_status', '=', UploadStatus.Pending)
+ .execute();
+
+ if (uploads.length === 0) {
+ return;
+ }
+
+ for (const upload of uploads) {
+ await this.uploadFile(upload);
+ }
+ }
+
+ private async uploadFile(state: SelectFileState): Promise<void> {
+ if (state.upload_retries >= UPLOAD_RETRIES_LIMIT) {
+ this.debug(
+ `File ${state.file_id} upload retries limit reached, marking as failed`
+ );
+
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set({
+ upload_status: UploadStatus.Failed,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', state.file_id)
+ .executeTakeFirst();
+
+ if (updatedFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ }
+
+ return;
+ }
+
+ const file = await this.workspace.database
+ .selectFrom('files')
+ .selectAll()
+ .where('id', '=', state.file_id)
+ .executeTakeFirst();
+
+ if (!file) {
+ await this.workspace.database
+ .deleteFrom('file_states')
+ .where('file_id', '=', state.file_id)
+ .execute();
+
+ this.debug(
+ `File ${state.file_id} not found, deleting state from database`
+ );
+ return;
+ }
+
+ if (file.version === BigInt(0)) {
+ // file is not synced with the server, we need to wait for the sync to complete
+ return;
+ }
+
+ if (file.status === FileStatus.Ready) {
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set({
+ upload_status: UploadStatus.Completed,
+ upload_progress: 100,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', state.file_id)
+ .executeTakeFirst();
+
+ if (updatedFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ }
+
+ return;
+ }
+
+ const filePath = this.buildFilePath(state.file_id, file.extension);
+
+ if (!fs.existsSync(filePath)) {
+ await this.workspace.database
+ .deleteFrom('file_states')
+ .where('file_id', '=', file.id)
+ .execute();
+
+ this.debug(
+ `File ${state.file_id} not found, deleting state from database`
+ );
+ return;
+ }
+
+ try {
+ const { data } =
+ await this.workspace.account.client.post<CreateUploadOutput>(
+ `/v1/workspaces/${this.workspace.id}/files`,
+ {
+ fileId: file.id,
+ }
+ );
+
+ const presignedUrl = data.url;
+ const fileStream = fs.createReadStream(filePath);
+
+ let lastProgress = 0;
+ await axios.put(presignedUrl, fileStream, {
+ headers: {
+ 'Content-Type': file.mime_type,
+ 'Content-Length': file.size,
+ },
+ onUploadProgress: async (progressEvent) => {
+ const progress = Math.round((progressEvent.loaded / file.size) * 100);
+
+ if (progress >= lastProgress) {
+ return;
+ }
+
+ lastProgress = progress;
+
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set({
+ upload_progress: progress,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', file.id)
+ .executeTakeFirst();
+
+ if (!updatedFileState) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ },
+ });
+
+ await this.workspace.account.client.put<CompleteUploadOutput>(
+ `/v1/workspaces/${this.workspace.id}/files/${file.id}`,
+ {}
+ );
+
+ const finalFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set({
+ upload_status: UploadStatus.Completed,
+ upload_progress: 100,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', file.id)
+ .executeTakeFirst();
+
+ if (finalFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(finalFileState),
+ });
+ }
+
+ this.debug(`File ${file.id} uploaded successfully`);
+ } catch {
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set((eb) => ({ upload_retries: eb('upload_retries', '+', 1) }))
+ .where('file_id', '=', file.id)
+ .executeTakeFirst();
+
+ if (updatedFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ }
+ }
+ }
+
+ public async downloadFiles(): Promise<void> {
+ if (!this.workspace.account.server.isAvailable()) {
+ return;
+ }
+
+ this.debug(`Downloading files for workspace ${this.workspace.id}`);
+
+ const downloads = await this.workspace.database
+ .selectFrom('file_states')
+ .selectAll()
+ .where('download_status', '=', DownloadStatus.Pending)
+ .execute();
+
+ if (downloads.length === 0) {
+ return;
+ }
+
+ for (const download of downloads) {
+ await this.downloadFile(download);
+ }
+ }
+
+ private async downloadFile(state: SelectFileState): Promise<void> {
+ if (state.download_retries >= DOWNLOAD_RETRIES_LIMIT) {
+ this.debug(
+ `File ${state.file_id} download retries limit reached, marking as failed`
+ );
+
+ await this.workspace.database
+ .updateTable('file_states')
+ .set({
+ download_status: DownloadStatus.Failed,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', state.file_id)
+ .execute();
+ }
+
+ const file = await this.workspace.database
+ .selectFrom('files')
+ .selectAll()
+ .where('id', '=', state.file_id)
+ .executeTakeFirst();
+
+ if (!file) {
+ this.debug(
+ `File ${state.file_id} not found, deleting state from database`
+ );
+
+ const deletedFileState = await this.workspace.database
+ .deleteFrom('file_states')
+ .returningAll()
+ .where('file_id', '=', state.file_id)
+ .executeTakeFirst();
+
+ if (deletedFileState) {
+ eventBus.publish({
+ type: 'file_state_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(deletedFileState),
+ });
+ }
+
+ return;
+ }
+
+ const filePath = this.buildFilePath(state.file_id, file.extension);
+
+ if (fs.existsSync(filePath)) {
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set({
+ download_status: DownloadStatus.Completed,
+ download_progress: 100,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', file.id)
+ .executeTakeFirst();
+
+ if (updatedFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ }
+
+ return;
+ }
+
+ try {
+ const { data } =
+ await this.workspace.account.client.get<CreateDownloadOutput>(
+ `/v1/workspaces/${this.workspace.id}/downloads/${file.id}`,
+ {}
+ );
+
+ const presignedUrl = data.url;
+ const fileStream = fs.createWriteStream(filePath);
+ let lastProgress = 0;
+
+ await axios
+ .get(presignedUrl, {
+ responseType: 'stream',
+ onDownloadProgress: async (progressEvent) => {
+ const progress = Math.round(
+ (progressEvent.loaded / file.size) * 100
+ );
+
+ if (progress <= lastProgress) {
+ return;
+ }
+
+ lastProgress = progress;
+
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set({
+ download_progress: progress,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', file.id)
+ .executeTakeFirst();
+
+ if (updatedFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ }
+ },
+ })
+ .then((response) => {
+ response.data.pipe(fileStream);
+ });
+
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set({
+ download_status: DownloadStatus.Completed,
+ download_progress: 100,
+ updated_at: new Date().toISOString(),
+ })
+ .where('file_id', '=', file.id)
+ .executeTakeFirst();
+
+ if (updatedFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ }
+ } catch {
+ const updatedFileState = await this.workspace.database
+ .updateTable('file_states')
+ .returningAll()
+ .set((eb) => ({ download_retries: eb('download_retries', '+', 1) }))
+ .where('file_id', '=', file.id)
+ .executeTakeFirst();
+
+ if (updatedFileState) {
+ eventBus.publish({
+ type: 'file_state_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileState: mapFileState(updatedFileState),
+ });
+ }
+ }
+ }
+
+ public async cleanDeletedFiles(): Promise<void> {
+ this.debug(`Checking deleted files for workspace ${this.workspace.id}`);
+
+ const files = fs.readdirSync(this.filesDir);
+ while (files.length > 0) {
+ const batch = files.splice(0, 100);
+ const fileIdMap: Record<string, string> = {};
+
+ for (const file of batch) {
+ const id = path.parse(file).name;
+ fileIdMap[id] = file;
+ }
+
+ const fileIds = Object.keys(fileIdMap);
+ const fileStates = await this.workspace.database
+ .selectFrom('file_states')
+ .select(['file_id'])
+ .where('file_id', 'in', fileIds)
+ .execute();
+
+ for (const fileId of fileIds) {
+ const fileState = fileStates.find((f) => f.file_id === fileId);
+ if (fileState) {
+ continue;
+ }
+
+ const filePath = path.join(this.filesDir, fileIdMap[fileId]!);
+ fs.rmSync(filePath, { force: true });
+ }
+ }
+ }
+
+ public async cleanTempFiles(): Promise<void> {
+ this.debug(`Checking temp files for workspace ${this.workspace.id}`);
+
+ if (!fs.existsSync(this.tempFilesDir)) {
+ return;
+ }
+
+ const files = fs.readdirSync(this.tempFilesDir);
+ const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000; // 24 hours in milliseconds
+
+ for (const file of files) {
+ const filePath = path.join(this.tempFilesDir, file);
+ const stats = fs.statSync(filePath);
+
+ if (stats.mtimeMs < oneDayAgo) {
+ try {
+ fs.unlinkSync(filePath);
+ this.debug(`Deleted old temp file: ${filePath}`);
+ } catch (error) {
+ this.debug(`Failed to delete temp file: ${filePath}`, error);
+ }
+ }
+ }
+ }
+
+ public async syncServerFile(file: SyncFileData): Promise<void> {
+ const existingFile = await this.workspace.database
+ .selectFrom('files')
+ .selectAll()
+ .where('id', '=', file.id)
+ .executeTakeFirst();
+
+ const version = BigInt(file.version);
+ if (existingFile) {
+ if (existingFile.version === version) {
+ this.debug(`Server file ${file.id} is already synced`);
+ return;
+ }
+
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
+ .returningAll()
+ .set({
+ name: file.name,
+ original_name: file.originalName,
+ mime_type: file.mimeType,
+ extension: file.extension,
+ size: file.size,
+ parent_id: file.parentId,
+ root_id: file.rootId,
+ status: file.status,
+ type: file.type,
+ updated_at: file.updatedAt,
+ updated_by: file.updatedBy,
+ version,
+ })
+ .where('id', '=', file.id)
+ .executeTakeFirst();
+
+ if (!updatedFile) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'file_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ file: mapFile(updatedFile),
+ });
+
+ this.triggerUploads();
+ this.triggerDownloads();
+
+ this.debug(`Server file ${file.id} has been synced`);
+ return;
+ }
+
+ const createdFile = await this.workspace.database
+ .insertInto('files')
+ .returningAll()
+ .values({
+ id: file.id,
+ version,
+ type: file.type,
+ parent_id: file.parentId,
+ entry_id: file.entryId,
+ root_id: file.rootId,
+ name: file.name,
+ original_name: file.originalName,
+ mime_type: file.mimeType,
+ extension: file.extension,
+ size: file.size,
+ created_at: file.createdAt,
+ created_by: file.createdBy,
+ updated_at: file.updatedAt,
+ updated_by: file.updatedBy,
+ status: file.status,
+ })
+ .executeTakeFirst();
+
+ if (!createdFile) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'file_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ file: mapFile(createdFile),
+ });
+
+ this.debug(`Server file ${file.id} has been synced`);
+ }
+
+ public async syncServerFileTombstone(fileTombstone: SyncFileTombstoneData) {
+ const deletedFile = await this.workspace.database
+ .deleteFrom('files')
+ .returningAll()
+ .where('id', '=', fileTombstone.id)
+ .executeTakeFirst();
+
+ await this.workspace.database
+ .deleteFrom('file_interactions')
+ .where('file_id', '=', fileTombstone.id)
+ .execute();
+
+ await this.workspace.database
+ .deleteFrom('file_states')
+ .where('file_id', '=', fileTombstone.id)
+ .execute();
+
+ if (deletedFile) {
+ // if the file exists in the workspace, we need to delete it
+ const filePath = this.buildFilePath(
+ fileTombstone.id,
+ deletedFile.extension
+ );
+
+ if (fs.existsSync(filePath)) {
+ fs.rmSync(filePath, { force: true });
+ }
+
+ eventBus.publish({
+ type: 'file_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ file: mapFile(deletedFile),
+ });
+ }
+
+ this.debug(`Server file tombstone ${fileTombstone.id} has been synced`);
+ }
+
+ public async syncServerFileInteraction(
+ fileInteraction: SyncFileInteractionData
+ ) {
+ const existingFileInteraction = await this.workspace.database
+ .selectFrom('file_interactions')
+ .selectAll()
+ .where('file_id', '=', fileInteraction.fileId)
+ .executeTakeFirst();
+
+ const version = BigInt(fileInteraction.version);
+ if (existingFileInteraction) {
+ if (existingFileInteraction.version === version) {
+ this.debug(
+ `Server file interaction for file ${fileInteraction.fileId} is already synced`
+ );
+ return;
+ }
+ }
+
+ const createdFileInteraction = await this.workspace.database
+ .insertInto('file_interactions')
+ .returningAll()
+ .values({
+ file_id: fileInteraction.fileId,
+ root_id: fileInteraction.rootId,
+ collaborator_id: fileInteraction.collaboratorId,
+ first_seen_at: fileInteraction.firstSeenAt,
+ last_seen_at: fileInteraction.lastSeenAt,
+ last_opened_at: fileInteraction.lastOpenedAt,
+ first_opened_at: fileInteraction.firstOpenedAt,
+ version,
+ })
+ .onConflict((b) =>
+ b.columns(['file_id', 'collaborator_id']).doUpdateSet({
+ last_seen_at: fileInteraction.lastSeenAt,
+ first_seen_at: fileInteraction.firstSeenAt,
+ last_opened_at: fileInteraction.lastOpenedAt,
+ first_opened_at: fileInteraction.firstOpenedAt,
+ version,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdFileInteraction) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'file_interaction_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ fileInteraction: mapFileInteraction(createdFileInteraction),
+ });
+
+ this.debug(
+ `Server file interaction for file ${fileInteraction.fileId} has been synced`
+ );
+ }
+
+ public async revertFileCreation(fileId: string) {
+ const deletedFile = await this.workspace.database
+ .deleteFrom('files')
+ .returningAll()
+ .where('id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!deletedFile) {
+ return;
+ }
+
+ await this.workspace.database
+ .deleteFrom('file_states')
+ .returningAll()
+ .where('file_id', '=', fileId)
+ .executeTakeFirst();
+
+ await this.workspace.database
+ .deleteFrom('file_interactions')
+ .where('file_id', '=', fileId)
+ .execute();
+
+ const filePath = path.join(
+ this.filesDir,
+ `${fileId}${deletedFile.extension}`
+ );
+
+ if (fs.existsSync(filePath)) {
+ fs.rmSync(filePath, { force: true });
+ }
+
+ eventBus.publish({
+ type: 'file_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ file: mapFile(deletedFile),
+ });
+ }
+
+ public async revertFileDeletion(fileId: string) {
+ const deletedFile = await this.workspace.database
+ .updateTable('files')
+ .returningAll()
+ .set({
+ deleted_at: null,
+ })
+ .where('id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!deletedFile) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'file_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ file: mapFile(deletedFile),
+ });
+ }
+
+ private buildFilePath(id: string, extension: string): string {
+ return path.join(this.filesDir, `${id}${extension}`);
+ }
+}
diff --git a/apps/desktop/src/main/services/message-service.ts b/apps/desktop/src/main/services/workspaces/message-service.ts
similarity index 79%
rename from apps/desktop/src/main/services/message-service.ts
rename to apps/desktop/src/main/services/workspaces/message-service.ts
index 6c972e91..114f066e 100644
--- a/apps/desktop/src/main/services/message-service.ts
+++ b/apps/desktop/src/main/services/workspaces/message-service.ts
@@ -9,23 +9,24 @@ import {
createDebugger,
} from '@colanode/core';
-import { fileService } from '@/main/services/file-service';
import {
mapMessage,
mapMessageInteraction,
mapMessageReaction,
} from '@/main/utils';
-import { databaseService } from '@/main/data/database-service';
import { eventBus } from '@/shared/lib/event-bus';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
-class MessageService {
+export class MessageService {
private readonly debug = createDebugger('desktop:service:message');
+ private readonly workspace: WorkspaceService;
- public async syncServerMessage(userId: string, message: SyncMessageData) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
+ constructor(workspace: WorkspaceService) {
+ this.workspace = workspace;
+ }
- const existingMessage = await workspaceDatabase
+ public async syncServerMessage(message: SyncMessageData) {
+ const existingMessage = await this.workspace.database
.selectFrom('messages')
.selectAll()
.where('id', '=', message.id)
@@ -38,7 +39,7 @@ class MessageService {
return;
}
- const updatedMessage = await workspaceDatabase
+ const updatedMessage = await this.workspace.database
.updateTable('messages')
.returningAll()
.set({
@@ -55,14 +56,14 @@ class MessageService {
return;
}
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('texts')
.where('id', '=', message.id)
.execute();
const text = extractMessageText(message.id, message.attributes);
if (text) {
- await workspaceDatabase
+ await this.workspace.database
.insertInto('texts')
.values({
id: message.id,
@@ -74,7 +75,8 @@ class MessageService {
eventBus.publish({
type: 'message_updated',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
message: mapMessage(updatedMessage),
});
@@ -82,7 +84,7 @@ class MessageService {
return;
}
- const createdMessage = await workspaceDatabase
+ const createdMessage = await this.workspace.database
.insertInto('messages')
.returningAll()
.values({
@@ -105,7 +107,7 @@ class MessageService {
const text = extractMessageText(message.id, message.attributes);
if (text) {
- await workspaceDatabase
+ await this.workspace.database
.insertInto('texts')
.values({
id: message.id,
@@ -117,7 +119,8 @@ class MessageService {
eventBus.publish({
type: 'message_created',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
message: mapMessage(createdMessage),
});
@@ -125,29 +128,25 @@ class MessageService {
}
public async syncServerMessageTombstone(
- userId: string,
messageTombstone: SyncMessageTombstoneData
) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const deletedMessage = await workspaceDatabase
+ const deletedMessage = await this.workspace.database
.deleteFrom('messages')
.returningAll()
.where('id', '=', messageTombstone.id)
.executeTakeFirst();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('message_reactions')
.where('message_id', '=', messageTombstone.id)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('message_interactions')
.where('message_id', '=', messageTombstone.id)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('texts')
.where('id', '=', messageTombstone.id)
.execute();
@@ -155,7 +154,8 @@ class MessageService {
if (deletedMessage) {
eventBus.publish({
type: 'message_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
message: mapMessage(deletedMessage),
});
}
@@ -166,14 +166,10 @@ class MessageService {
}
public async syncServerMessageReaction(
- userId: string,
messageReaction: SyncMessageReactionData
) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
if (messageReaction.deletedAt) {
- const deletedMessageReaction = await workspaceDatabase
+ const deletedMessageReaction = await this.workspace.database
.deleteFrom('message_reactions')
.returningAll()
.where('message_id', '=', messageReaction.messageId)
@@ -184,7 +180,8 @@ class MessageService {
if (deletedMessageReaction) {
eventBus.publish({
type: 'message_reaction_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
messageReaction: mapMessageReaction(deletedMessageReaction),
});
}
@@ -195,7 +192,7 @@ class MessageService {
return;
}
- const existingMessageReaction = await workspaceDatabase
+ const existingMessageReaction = await this.workspace.database
.selectFrom('message_reactions')
.selectAll()
.where('message_id', '=', messageReaction.messageId)
@@ -212,7 +209,7 @@ class MessageService {
return;
}
- const updatedMessageReaction = await workspaceDatabase
+ const updatedMessageReaction = await this.workspace.database
.updateTable('message_reactions')
.returningAll()
.set({
@@ -233,7 +230,7 @@ class MessageService {
return;
}
- const createdMessageReaction = await workspaceDatabase
+ const createdMessageReaction = await this.workspace.database
.insertInto('message_reactions')
.returningAll()
.values({
@@ -258,7 +255,8 @@ class MessageService {
eventBus.publish({
type: 'message_reaction_created',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
messageReaction: mapMessageReaction(createdMessageReaction),
});
@@ -268,13 +266,9 @@ class MessageService {
}
public async syncServerMessageInteraction(
- userId: string,
messageInteraction: SyncMessageInteractionData
) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const existingMessageInteraction = await workspaceDatabase
+ const existingMessageInteraction = await this.workspace.database
.selectFrom('message_interactions')
.selectAll()
.where('message_id', '=', messageInteraction.messageId)
@@ -290,7 +284,7 @@ class MessageService {
}
}
- const createdMessageInteraction = await workspaceDatabase
+ const createdMessageInteraction = await this.workspace.database
.insertInto('message_interactions')
.returningAll()
.values({
@@ -320,7 +314,8 @@ class MessageService {
eventBus.publish({
type: 'message_interaction_updated',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
messageInteraction: mapMessageInteraction(createdMessageInteraction),
});
@@ -329,11 +324,8 @@ class MessageService {
);
}
- public async revertMessageCreation(userId: string, messageId: string) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const deletedMessage = await workspaceDatabase
+ public async revertMessageCreation(messageId: string) {
+ const deletedMessage = await this.workspace.database
.deleteFrom('messages')
.returningAll()
.where('id', '=', messageId)
@@ -343,38 +335,36 @@ class MessageService {
return;
}
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('message_reactions')
.where('message_id', '=', messageId)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('message_interactions')
.where('message_id', '=', messageId)
.execute();
eventBus.publish({
type: 'message_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
message: mapMessage(deletedMessage),
});
- const files = await workspaceDatabase
+ const files = await this.workspace.database
.selectFrom('files')
.selectAll()
.where('parent_id', '=', messageId)
.execute();
for (const file of files) {
- await fileService.revertFileCreation(userId, file.id);
+ await this.workspace.files.revertFileCreation(file.id);
}
}
- public async revertMessageDeletion(userId: string, messageId: string) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const deletedMessage = await workspaceDatabase
+ public async revertMessageDeletion(messageId: string) {
+ const deletedMessage = await this.workspace.database
.updateTable('messages')
.returningAll()
.set({
@@ -389,23 +379,20 @@ class MessageService {
eventBus.publish({
type: 'message_created',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
message: mapMessage(deletedMessage),
});
}
public async revertMessageReactionCreation(
- userId: string,
messageReaction: CreateMessageReactionMutationData
) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const deletedMessageReaction = await workspaceDatabase
+ const deletedMessageReaction = await this.workspace.database
.deleteFrom('message_reactions')
.returningAll()
.where('message_id', '=', messageReaction.messageId)
- .where('collaborator_id', '=', userId)
+ .where('collaborator_id', '=', this.workspace.userId)
.where('reaction', '=', messageReaction.reaction)
.executeTakeFirst();
@@ -415,26 +402,23 @@ class MessageService {
eventBus.publish({
type: 'message_reaction_deleted',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
messageReaction: mapMessageReaction(deletedMessageReaction),
});
}
public async revertMessageReactionDeletion(
- userId: string,
messageReaction: DeleteMessageReactionMutationData
) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const createdMessageReaction = await workspaceDatabase
+ const createdMessageReaction = await this.workspace.database
.updateTable('message_reactions')
.returningAll()
.set({
deleted_at: null,
})
.where('message_id', '=', messageReaction.messageId)
- .where('collaborator_id', '=', userId)
+ .where('collaborator_id', '=', this.workspace.userId)
.where('reaction', '=', messageReaction.reaction)
.executeTakeFirst();
@@ -444,10 +428,9 @@ class MessageService {
eventBus.publish({
type: 'message_reaction_created',
- userId,
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
messageReaction: mapMessageReaction(createdMessageReaction),
});
}
}
-
-export const messageService = new MessageService();
diff --git a/apps/desktop/src/main/jobs/sync-pending-mutations.ts b/apps/desktop/src/main/services/workspaces/mutation-service.ts
similarity index 64%
rename from apps/desktop/src/main/jobs/sync-pending-mutations.ts
rename to apps/desktop/src/main/services/workspaces/mutation-service.ts
index 89e8bc22..c6eedf2b 100644
--- a/apps/desktop/src/main/jobs/sync-pending-mutations.ts
+++ b/apps/desktop/src/main/services/workspaces/mutation-service.ts
@@ -1,53 +1,56 @@
-import { Mutation, SyncMutationsOutput, createDebugger } from '@colanode/core';
-
-import { fetchWorkspaceCredentials, mapMutation } from '@/main/utils';
-import { databaseService } from '@/main/data/database-service';
-import { serverService } from '@/main/services/server-service';
-import { JobHandler } from '@/main/jobs';
-import { httpClient } from '@/shared/lib/http-client';
-
-export type SyncPendingMutationsInput = {
- type: 'sync_pending_mutations';
- userId: string;
-};
-
-declare module '@/main/jobs' {
- interface JobMap {
- sync_pending_mutations: {
- input: SyncPendingMutationsInput;
- };
- }
-}
+import { createDebugger, Mutation, SyncMutationsOutput } from '@colanode/core';
+import ms from 'ms';
+
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { mapMutation } from '@/main/utils';
+import { EventLoop } from '@/shared/lib/event-loop';
const READ_SIZE = 500;
const BATCH_SIZE = 50;
-export class SyncPendingMutationsJobHandler
- implements JobHandler<SyncPendingMutationsInput>
-{
- public triggerDebounce = 0;
- public interval = 1000 * 60;
+export class MutationService {
+ private readonly debug = createDebugger('desktop:service:mutation');
+ private readonly workspace: WorkspaceService;
+ private readonly eventLoop: EventLoop;
- private readonly debug = createDebugger('desktop:job:sync-pending-mutations');
+ constructor(workspaceService: WorkspaceService) {
+ this.workspace = workspaceService;
- public async handleJob(input: SyncPendingMutationsInput) {
- let hasMore = true;
+ this.eventLoop = new EventLoop(ms('1 minute'), ms('1 second'), () => {
+ this.sync();
+ });
- while (hasMore) {
- hasMore = await this.syncMutations(input);
- }
+ this.eventLoop.start();
}
- private async syncMutations(
- input: SyncPendingMutationsInput
- ): Promise<boolean> {
- this.debug(`Sending local pending mutations for user ${input.userId}`);
+ public destroy(): void {
+ this.eventLoop.stop();
+ }
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
+ public triggerSync(): void {
+ this.eventLoop.trigger();
+ }
+
+ private async sync(): Promise<void> {
+ try {
+ let hasMore = true;
+
+ while (hasMore) {
+ hasMore = await this.sendMutations();
+ }
- const unsyncedMutations = await workspaceDatabase
+ await this.revertInvalidMutations();
+ } catch (error) {
+ this.debug(`Error syncing mutations: ${error}`);
+ }
+ }
+
+ private async sendMutations(): Promise<boolean> {
+ if (!this.workspace.account.server.isAvailable()) {
+ return false;
+ }
+
+ const unsyncedMutations = await this.workspace.database
.selectFrom('mutations')
.selectAll()
.orderBy('id', 'asc')
@@ -60,38 +63,19 @@ export class SyncPendingMutationsJobHandler
const allMutations: Mutation[] = unsyncedMutations.map(mapMutation);
const { validMutations, deletedMutationIds } =
- await this.consolidateMutations(allMutations);
+ this.consolidateMutations(allMutations);
if (deletedMutationIds.size > 0) {
- this.debug(
- `Deleting ${deletedMutationIds.size} redundant local pending mutations for user ${input.userId}`
+ await this.deleteMutations(
+ Array.from(deletedMutationIds),
+ 'consolidated'
);
-
- await workspaceDatabase
- .deleteFrom('mutations')
- .where('id', 'in', Array.from(deletedMutationIds))
- .execute();
}
this.debug(
- `Sending ${unsyncedMutations.length} local pending mutations for user ${input.userId}`
+ `Sending ${unsyncedMutations.length} local pending mutations for user ${this.workspace.id}`
);
- const credentials = await fetchWorkspaceCredentials(input.userId);
- if (!credentials) {
- this.debug(
- `No workspace credentials found for user ${input.userId}, skipping sending local pending mutations`
- );
- return false;
- }
-
- if (!serverService.isAvailable(credentials.serverDomain)) {
- this.debug(
- `Server ${credentials.serverDomain} is not available, skipping sending local pending mutations`
- );
- return false;
- }
-
const totalBatches = Math.ceil(validMutations.length / BATCH_SIZE);
let currentBatch = 1;
@@ -100,19 +84,16 @@ export class SyncPendingMutationsJobHandler
const batch = validMutations.splice(0, BATCH_SIZE);
this.debug(
- `Sending batch ${currentBatch++} of ${totalBatches} mutations for user ${input.userId}`
+ `Sending batch ${currentBatch++} of ${totalBatches} mutations for user ${this.workspace.id}`
);
- const { data } = await httpClient.post<SyncMutationsOutput>(
- `/v1/workspaces/${credentials.workspaceId}/mutations`,
- {
- mutations: batch,
- },
- {
- domain: credentials.serverDomain,
- token: credentials.token,
- }
- );
+ const { data } =
+ await this.workspace.account.client.post<SyncMutationsOutput>(
+ `/v1/workspaces/${this.workspace.id}/mutations`,
+ {
+ mutations: batch,
+ }
+ );
const syncedMutationIds: string[] = [];
const unsyncedMutationIds: string[] = [];
@@ -126,38 +107,96 @@ export class SyncPendingMutationsJobHandler
}
if (syncedMutationIds.length > 0) {
- this.debug(
- `Marking ${syncedMutationIds.length} local pending mutations as sent for user ${input.userId}`
- );
-
- await workspaceDatabase
- .deleteFrom('mutations')
- .where('id', 'in', syncedMutationIds)
- .execute();
+ await this.deleteMutations(syncedMutationIds, 'synced');
}
if (unsyncedMutationIds.length > 0) {
- this.debug(
- `Marking ${unsyncedMutationIds.length} local pending mutations as failed for user ${input.userId}`
- );
-
- await workspaceDatabase
- .updateTable('mutations')
- .set((eb) => ({ retries: eb('retries', '+', 1) }))
- .where('id', 'in', unsyncedMutationIds)
- .execute();
+ await this.markMutationsAsFailed(unsyncedMutationIds);
}
}
} catch (error) {
this.debug(
- `Failed to send local pending mutations for user ${input.userId}: ${error}`
+ `Failed to send local pending mutations for user ${this.workspace.id}: ${error}`
);
}
return unsyncedMutations.length === READ_SIZE;
}
- private async consolidateMutations(mutations: Mutation[]) {
+ private async revertInvalidMutations(): Promise<void> {
+ const invalidMutations = await this.workspace.database
+ .selectFrom('mutations')
+ .selectAll()
+ .where('retries', '>=', 10)
+ .execute();
+
+ if (invalidMutations.length === 0) {
+ return;
+ }
+
+ this.debug(
+ `Reverting ${invalidMutations.length} invalid mutations for workspace ${this.workspace.id}`
+ );
+
+ for (const mutationRow of invalidMutations) {
+ const mutation = mapMutation(mutationRow);
+
+ if (mutation.type === 'create_file') {
+ await this.workspace.files.revertFileCreation(mutation.id);
+ } else if (mutation.type === 'delete_file') {
+ await this.workspace.files.revertFileDeletion(mutation.id);
+ } else if (mutation.type === 'apply_create_transaction') {
+ await this.workspace.entries.revertCreateTransaction(mutation.data);
+ } else if (mutation.type === 'apply_update_transaction') {
+ await this.workspace.entries.revertUpdateTransaction(mutation.data);
+ } else if (mutation.type === 'apply_delete_transaction') {
+ await this.workspace.entries.revertDeleteTransaction(mutation.data);
+ } else if (mutation.type === 'create_message') {
+ await this.workspace.messages.revertMessageCreation(mutation.data.id);
+ } else if (mutation.type === 'delete_message') {
+ await this.workspace.messages.revertMessageDeletion(mutation.data.id);
+ } else if (mutation.type === 'create_message_reaction') {
+ await this.workspace.messages.revertMessageReactionCreation(
+ mutation.data
+ );
+ } else if (mutation.type === 'delete_message_reaction') {
+ await this.workspace.messages.revertMessageReactionDeletion(
+ mutation.data
+ );
+ }
+ }
+
+ const mutationIds = invalidMutations.map((m) => m.id);
+ await this.deleteMutations(mutationIds, 'invalid');
+ }
+
+ private async deleteMutations(
+ mutationIds: string[],
+ reason: string
+ ): Promise<void> {
+ this.debug(
+ `Deleting ${mutationIds.length} local mutations for user ${this.workspace.id}. Reason: ${reason}`
+ );
+
+ await this.workspace.database
+ .deleteFrom('mutations')
+ .where('id', 'in', mutationIds)
+ .execute();
+ }
+
+ private async markMutationsAsFailed(mutationIds: string[]): Promise<void> {
+ this.debug(
+ `Marking ${mutationIds.length} local pending mutations as failed for user ${this.workspace.id}`
+ );
+
+ await this.workspace.database
+ .updateTable('mutations')
+ .set((eb) => ({ retries: eb('retries', '+', 1) }))
+ .where('id', 'in', mutationIds)
+ .execute();
+ }
+
+ private consolidateMutations(mutations: Mutation[]) {
const validMutations: Mutation[] = [];
const deletedMutationIds: Set<string> = new Set();
diff --git a/apps/desktop/src/main/services/radar-service.ts b/apps/desktop/src/main/services/workspaces/radar-service.ts
similarity index 62%
rename from apps/desktop/src/main/services/radar-service.ts
rename to apps/desktop/src/main/services/workspaces/radar-service.ts
index be01466a..01b1f09a 100644
--- a/apps/desktop/src/main/services/radar-service.ts
+++ b/apps/desktop/src/main/services/workspaces/radar-service.ts
@@ -1,27 +1,21 @@
import { getIdType, IdType } from '@colanode/core';
-import { Kysely } from 'kysely';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { SelectCollaboration } from '@/main/databases/workspace';
import {
- SelectCollaboration,
- WorkspaceDatabaseSchema,
-} from '@/main/data/workspace/schema';
-import { mapWorkspace } from '@/main/utils';
-import { databaseService } from '@/main/data/database-service';
-import { eventBus } from '@/shared/lib/event-bus';
+ ChannelReadState,
+ ChatReadState,
+ WorkspaceRadarData,
+} from '@/shared/types/radars';
import {
CollaborationCreatedEvent,
CollaborationDeletedEvent,
- Event,
MessageCreatedEvent,
MessageDeletedEvent,
MessageInteractionUpdatedEvent,
+ Event,
} from '@/shared/types/events';
-import {
- WorkspaceRadarData,
- ChannelReadState,
- ChatReadState,
-} from '@/shared/types/radars';
-import { Workspace } from '@/shared/types/workspaces';
+import { eventBus } from '@/shared/lib/event-bus';
interface UndreadMessage {
messageId: string;
@@ -29,21 +23,17 @@ interface UndreadMessage {
parentIdType: IdType;
}
-class RadarWorkspace {
- public readonly workspace: Workspace;
- private readonly workspaceDatabase: Kysely<WorkspaceDatabaseSchema>;
+export class RadarService {
+ private readonly workspace: WorkspaceService;
private readonly unreadMessages: Map<string, UndreadMessage> = new Map();
private readonly collaborations: Map<string, SelectCollaboration> = new Map();
- constructor(
- workspace: Workspace,
- workspaceDatabase: Kysely<WorkspaceDatabaseSchema>
- ) {
+ constructor(workspace: WorkspaceService) {
this.workspace = workspace;
- this.workspaceDatabase = workspaceDatabase;
+ eventBus.subscribe(this.handleEvent.bind(this));
}
- public getWorkspaceData(): WorkspaceRadarData {
+ public getData(): WorkspaceRadarData {
const data: WorkspaceRadarData = {
accountId: this.workspace.accountId,
userId: this.workspace.userId,
@@ -93,7 +83,7 @@ class RadarWorkspace {
}
public async init(): Promise<void> {
- const collaborations = await this.workspaceDatabase
+ const collaborations = await this.workspace.database
.selectFrom('collaborations')
.selectAll()
.execute();
@@ -106,7 +96,7 @@ class RadarWorkspace {
return;
}
- const unreadMessagesRows = await this.workspaceDatabase
+ const unreadMessagesRows = await this.workspace.database
.selectFrom('messages as message')
.leftJoin('message_interactions as message_interactions', (join) =>
join
@@ -138,12 +128,27 @@ class RadarWorkspace {
}
}
- public async handleMessageInteractionUpdated(
+ private async handleEvent(event: Event) {
+ if (event.type === 'message_interaction_updated') {
+ await this.handleMessageInteractionUpdated(event);
+ } else if (event.type === 'message_created') {
+ await this.handleMessageCreated(event);
+ } else if (event.type === 'message_deleted') {
+ await this.handleMessageDeleted(event);
+ } else if (event.type === 'collaboration_created') {
+ await this.handleCollaborationCreated(event);
+ } else if (event.type === 'collaboration_deleted') {
+ await this.handleCollaborationDeleted(event);
+ }
+ }
+
+ private async handleMessageInteractionUpdated(
event: MessageInteractionUpdatedEvent
): Promise<void> {
const interaction = event.messageInteraction;
if (
- event.userId !== this.workspace.userId ||
+ event.accountId !== this.workspace.accountId ||
+ event.workspaceId !== this.workspace.id ||
interaction.collaboratorId !== this.workspace.userId
) {
return;
@@ -161,7 +166,9 @@ class RadarWorkspace {
}
}
- public async handleMessageCreated(event: MessageCreatedEvent): Promise<void> {
+ private async handleMessageCreated(
+ event: MessageCreatedEvent
+ ): Promise<void> {
const message = event.message;
if (message.createdBy === this.workspace.userId) {
return;
@@ -180,7 +187,7 @@ class RadarWorkspace {
return;
}
- const messageInteraction = await this.workspaceDatabase
+ const messageInteraction = await this.workspace.database
.selectFrom('message_interactions')
.selectAll()
.where('message_id', '=', message.id)
@@ -202,7 +209,9 @@ class RadarWorkspace {
});
}
- public async handleMessageDeleted(event: MessageDeletedEvent): Promise<void> {
+ private async handleMessageDeleted(
+ event: MessageDeletedEvent
+ ): Promise<void> {
const message = event.message;
if (message.createdBy === this.workspace.userId) {
return;
@@ -218,10 +227,10 @@ class RadarWorkspace {
});
}
- public async handleCollaborationCreated(
+ private async handleCollaborationCreated(
event: CollaborationCreatedEvent
): Promise<void> {
- const collaboration = await this.workspaceDatabase
+ const collaboration = await this.workspace.database
.selectFrom('collaborations')
.selectAll()
.where('entry_id', '=', event.entryId)
@@ -234,96 +243,9 @@ class RadarWorkspace {
this.collaborations.set(event.entryId, collaboration);
}
- public async handleCollaborationDeleted(
+ private async handleCollaborationDeleted(
event: CollaborationDeletedEvent
): Promise<void> {
this.collaborations.delete(event.entryId);
}
}
-
-class RadarService {
- private readonly workspaces: Map<string, RadarWorkspace> = new Map();
-
- constructor() {
- eventBus.subscribe(this.handleEvent.bind(this));
- }
-
- public async init(): Promise<void> {
- const workspaces = await databaseService.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .execute();
-
- for (const workspace of workspaces) {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- workspace.user_id
- );
-
- const radarWorkspace = new RadarWorkspace(
- mapWorkspace(workspace),
- workspaceDatabase
- );
- this.workspaces.set(workspace.user_id, radarWorkspace);
- await radarWorkspace.init();
- }
-
- eventBus.publish({
- type: 'radar_data_updated',
- });
- }
-
- public getData(): Record<string, WorkspaceRadarData> {
- const data: Record<string, WorkspaceRadarData> = {};
- for (const radarWorkspace of this.workspaces.values()) {
- data[radarWorkspace.workspace.userId] = radarWorkspace.getWorkspaceData();
- }
- return data;
- }
-
- private async handleEvent(event: Event) {
- if (event.type === 'workspace_deleted') {
- this.workspaces.delete(event.workspace.userId);
- eventBus.publish({
- type: 'radar_data_updated',
- });
- } else if (event.type === 'message_interaction_updated') {
- const radarWorkspace = this.workspaces.get(event.userId);
- if (radarWorkspace) {
- radarWorkspace.handleMessageInteractionUpdated(event);
- }
- } else if (event.type === 'workspace_created') {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- event.workspace.userId
- );
-
- const radarWorkspace = new RadarWorkspace(
- event.workspace,
- workspaceDatabase
- );
- this.workspaces.set(event.workspace.userId, radarWorkspace);
- await radarWorkspace.init();
- } else if (event.type === 'message_created') {
- const radarWorkspace = this.workspaces.get(event.userId);
- if (radarWorkspace) {
- radarWorkspace.handleMessageCreated(event);
- }
- } else if (event.type === 'message_deleted') {
- const radarWorkspace = this.workspaces.get(event.userId);
- if (radarWorkspace) {
- radarWorkspace.handleMessageDeleted(event);
- }
- } else if (event.type === 'collaboration_created') {
- const radarWorkspace = this.workspaces.get(event.userId);
- if (radarWorkspace) {
- radarWorkspace.handleCollaborationCreated(event);
- }
- } else if (event.type === 'collaboration_deleted') {
- const radarWorkspace = this.workspaces.get(event.userId);
- if (radarWorkspace) {
- radarWorkspace.handleCollaborationDeleted(event);
- }
- }
- }
-}
-
-export const radarService = new RadarService();
diff --git a/apps/desktop/src/main/services/workspaces/sync-service.ts b/apps/desktop/src/main/services/workspaces/sync-service.ts
new file mode 100644
index 00000000..0791950d
--- /dev/null
+++ b/apps/desktop/src/main/services/workspaces/sync-service.ts
@@ -0,0 +1,267 @@
+import {
+ createDebugger,
+ SyncCollaborationsInput,
+ SyncUsersInput,
+ SyncEntryTransactionsInput,
+ SyncEntryInteractionsInput,
+ SyncMessagesInput,
+ SyncMessageInteractionsInput,
+ SyncMessageReactionsInput,
+ SyncFilesInput,
+ SyncFileInteractionsInput,
+ SyncFileTombstonesInput,
+ SyncMessageTombstonesInput,
+ SyncEntryTransactionData,
+ SyncMessageTombstoneData,
+ SyncMessageInteractionData,
+ SyncEntryInteractionData,
+ SyncMessageData,
+ SyncMessageReactionData,
+ SyncFileInteractionData,
+ SyncFileTombstoneData,
+ SyncFileData,
+ SyncUserData,
+ SyncCollaborationData,
+} from '@colanode/core';
+
+import { Event } from '@/shared/types/events';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { Synchronizer } from '@/main/services/workspaces/synchronizer';
+import { eventBus } from '@/shared/lib/event-bus';
+
+interface RootSynchronizers {
+ entryTransactions: Synchronizer<SyncEntryTransactionsInput>;
+ entryInteractions: Synchronizer<SyncEntryInteractionsInput>;
+ messages: Synchronizer<SyncMessagesInput>;
+ messageInteractions: Synchronizer<SyncMessageInteractionsInput>;
+ messageReactions: Synchronizer<SyncMessageReactionsInput>;
+ messageTombstones: Synchronizer<SyncMessageTombstonesInput>;
+ files: Synchronizer<SyncFilesInput>;
+ fileInteractions: Synchronizer<SyncFileInteractionsInput>;
+ fileTombstones: Synchronizer<SyncFileTombstonesInput>;
+}
+
+type SyncHandlers = {
+ users: (data: SyncUserData) => Promise<void>;
+ collaborations: (data: SyncCollaborationData) => Promise<void>;
+ entry_transactions: (data: SyncEntryTransactionData) => Promise<void>;
+ entry_interactions: (data: SyncEntryInteractionData) => Promise<void>;
+ messages: (data: SyncMessageData) => Promise<void>;
+ message_interactions: (data: SyncMessageInteractionData) => Promise<void>;
+ message_reactions: (data: SyncMessageReactionData) => Promise<void>;
+ message_tombstones: (data: SyncMessageTombstoneData) => Promise<void>;
+ files: (data: SyncFileData) => Promise<void>;
+ file_interactions: (data: SyncFileInteractionData) => Promise<void>;
+ file_tombstones: (data: SyncFileTombstoneData) => Promise<void>;
+};
+
+export class SyncService {
+ private readonly debug = createDebugger('desktop:service:sync');
+ private readonly workspace: WorkspaceService;
+
+ private readonly rootSynchronizers: Map<string, RootSynchronizers> =
+ new Map();
+
+ private readonly syncHandlers: SyncHandlers;
+
+ private userSynchronizer: Synchronizer<SyncUsersInput> | undefined;
+ private collaborationSynchronizer:
+ | Synchronizer<SyncCollaborationsInput>
+ | undefined;
+
+ constructor(workspaceService: WorkspaceService) {
+ this.workspace = workspaceService;
+ this.syncHandlers = {
+ users: this.workspace.users.syncServerUser.bind(this.workspace.users),
+ collaborations:
+ this.workspace.collaborations.syncServerCollaboration.bind(
+ this.workspace.collaborations
+ ),
+ entry_transactions: this.workspace.entries.applyServerTransaction.bind(
+ this.workspace.entries
+ ),
+ entry_interactions:
+ this.workspace.entries.syncServerEntryInteraction.bind(
+ this.workspace.entries
+ ),
+ messages: this.workspace.messages.syncServerMessage.bind(
+ this.workspace.messages
+ ),
+ message_interactions:
+ this.workspace.messages.syncServerMessageInteraction.bind(
+ this.workspace.messages
+ ),
+ message_reactions: this.workspace.messages.syncServerMessageReaction.bind(
+ this.workspace.messages
+ ),
+ message_tombstones:
+ this.workspace.messages.syncServerMessageTombstone.bind(
+ this.workspace.messages
+ ),
+ files: this.workspace.files.syncServerFile.bind(this.workspace.files),
+ file_interactions: this.workspace.files.syncServerFileInteraction.bind(
+ this.workspace.files
+ ),
+ file_tombstones: this.workspace.files.syncServerFileTombstone.bind(
+ this.workspace.files
+ ),
+ };
+ eventBus.subscribe(this.handleEvent.bind(this));
+ }
+
+ private handleEvent(event: Event): void {
+ if (
+ event.type === 'collaboration_created' &&
+ event.accountId === this.workspace.accountId &&
+ event.workspaceId === this.workspace.id
+ ) {
+ this.initRootSynchronizers(event.entryId);
+ } else if (
+ event.type === 'collaboration_deleted' &&
+ event.accountId === this.workspace.accountId &&
+ event.workspaceId === this.workspace.id
+ ) {
+ this.removeRootSynchronizers(event.entryId);
+ }
+ }
+
+ public async init() {
+ this.debug(`Initializing sync service for workspace ${this.workspace.id}`);
+
+ if (!this.userSynchronizer) {
+ this.userSynchronizer = new Synchronizer(
+ this.workspace,
+ { type: 'users' },
+ 'users',
+ this.syncHandlers.users
+ );
+
+ await this.userSynchronizer.init();
+ }
+
+ if (!this.collaborationSynchronizer) {
+ this.collaborationSynchronizer = new Synchronizer(
+ this.workspace,
+ { type: 'collaborations' },
+ 'collaborations',
+ this.syncHandlers.collaborations
+ );
+
+ await this.collaborationSynchronizer.init();
+ }
+
+ const collaborations = await this.workspace.database
+ .selectFrom('collaborations')
+ .selectAll()
+ .execute();
+
+ for (const collaboration of collaborations) {
+ await this.initRootSynchronizers(collaboration.entry_id);
+ }
+ }
+
+ public destroy(): void {
+ this.userSynchronizer?.destroy();
+ this.collaborationSynchronizer?.destroy();
+
+ for (const rootSynchronizers of this.rootSynchronizers.values()) {
+ this.destroyRootSynchronizers(rootSynchronizers);
+ }
+ }
+
+ private destroyRootSynchronizers(rootSynchronizers: RootSynchronizers): void {
+ rootSynchronizers.entryTransactions.destroy();
+ rootSynchronizers.entryInteractions.destroy();
+ rootSynchronizers.messages.destroy();
+ rootSynchronizers.messageInteractions.destroy();
+ rootSynchronizers.messageReactions.destroy();
+ rootSynchronizers.messageTombstones.destroy();
+ rootSynchronizers.files.destroy();
+ rootSynchronizers.fileInteractions.destroy();
+ rootSynchronizers.fileTombstones.destroy();
+ }
+
+ private async initRootSynchronizers(rootId: string): Promise<void> {
+ if (this.rootSynchronizers.has(rootId)) {
+ return;
+ }
+
+ this.debug(
+ `Initializing root synchronizers for root ${rootId} in workspace ${this.workspace.id}`
+ );
+
+ const rootSynchronizers = {
+ entryTransactions: new Synchronizer(
+ this.workspace,
+ { type: 'entry_transactions', rootId },
+ `${rootId}_entry_transactions`,
+ this.syncHandlers.entry_transactions
+ ),
+ entryInteractions: new Synchronizer(
+ this.workspace,
+ { type: 'entry_interactions', rootId },
+ `${rootId}_entry_interactions`,
+ this.syncHandlers.entry_interactions
+ ),
+ messages: new Synchronizer(
+ this.workspace,
+ { type: 'messages', rootId },
+ `${rootId}_messages`,
+ this.syncHandlers.messages
+ ),
+ messageInteractions: new Synchronizer(
+ this.workspace,
+ { type: 'message_interactions', rootId },
+ `${rootId}_message_interactions`,
+ this.syncHandlers.message_interactions
+ ),
+ messageReactions: new Synchronizer(
+ this.workspace,
+ { type: 'message_reactions', rootId },
+ `${rootId}_message_reactions`,
+ this.syncHandlers.message_reactions
+ ),
+ messageTombstones: new Synchronizer(
+ this.workspace,
+ { type: 'message_tombstones', rootId },
+ `${rootId}_message_tombstones`,
+ this.syncHandlers.message_tombstones
+ ),
+ files: new Synchronizer(
+ this.workspace,
+ { type: 'files', rootId },
+ `${rootId}_files`,
+ this.syncHandlers.files
+ ),
+ fileInteractions: new Synchronizer(
+ this.workspace,
+ { type: 'file_interactions', rootId },
+ `${rootId}_file_interactions`,
+ this.syncHandlers.file_interactions
+ ),
+ fileTombstones: new Synchronizer(
+ this.workspace,
+ { type: 'file_tombstones', rootId },
+ `${rootId}_file_tombstones`,
+ this.syncHandlers.file_tombstones
+ ),
+ };
+
+ this.rootSynchronizers.set(rootId, rootSynchronizers);
+ await Promise.all(
+ Object.values(rootSynchronizers).map((synchronizer) =>
+ synchronizer.init()
+ )
+ );
+ }
+
+ private removeRootSynchronizers(rootId: string): void {
+ const rootSynchronizers = this.rootSynchronizers.get(rootId);
+ if (!rootSynchronizers) {
+ return;
+ }
+
+ this.destroyRootSynchronizers(rootSynchronizers);
+ this.rootSynchronizers.delete(rootId);
+ }
+}
diff --git a/apps/desktop/src/main/services/workspaces/synchronizer.ts b/apps/desktop/src/main/services/workspaces/synchronizer.ts
new file mode 100644
index 00000000..e31ad9e6
--- /dev/null
+++ b/apps/desktop/src/main/services/workspaces/synchronizer.ts
@@ -0,0 +1,196 @@
+import {
+ SynchronizerOutputMessage,
+ SynchronizerInputMessage,
+ SynchronizerInput,
+ SynchronizerMap,
+ createDebugger,
+ Message,
+} from '@colanode/core';
+import { sha256 } from 'js-sha256';
+import ms from 'ms';
+
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { AccountConnection } from '@/main/services/accounts/account-connection';
+import { EventLoop } from '@/shared/lib/event-loop';
+
+export type SynchronizerStatus = 'idle' | 'waiting' | 'processing';
+
+export class Synchronizer<TInput extends SynchronizerInput> {
+ private readonly debug = createDebugger('desktop:synchronizer');
+ private readonly id: string;
+ private readonly input: TInput;
+ private readonly workspace: WorkspaceService;
+ private readonly connection: AccountConnection;
+ private readonly cursorKey: string;
+ private readonly eventLoop: EventLoop;
+
+ private readonly processor: (
+ data: SynchronizerMap[TInput['type']]['data']
+ ) => Promise<void>;
+
+ private status: SynchronizerStatus = 'idle';
+ private cursor: bigint = 0n;
+ private initialized: boolean = false;
+
+ constructor(
+ workspaceService: WorkspaceService,
+ input: TInput,
+ cursorKey: string,
+ processor: (data: SynchronizerMap[TInput['type']]['data']) => Promise<void>
+ ) {
+ this.workspace = workspaceService;
+ this.connection = workspaceService.account.connection;
+ this.input = input;
+ this.cursorKey = cursorKey;
+ this.id = this.generateId();
+ this.processor = processor;
+
+ this.eventLoop = new EventLoop(ms('1 minute'), ms('1 second'), () => {
+ this.ping();
+ });
+
+ this.connection.on('open', () => {
+ this.eventLoop.trigger();
+ });
+
+ this.connection.on('close', () => {
+ this.eventLoop.stop();
+ });
+
+ this.connection.on('error', () => {
+ this.eventLoop.stop();
+ });
+
+ this.handleMessage = this.handleMessage.bind(this);
+ this.connection.on('message', this.handleMessage);
+
+ this.eventLoop.start();
+ }
+
+ public async init() {
+ this.cursor = await this.fetchCursor();
+ this.initConsumer();
+ this.eventLoop.start();
+ this.initialized = true;
+ }
+
+ private ping() {
+ if (!this.initialized) {
+ return;
+ }
+
+ this.initConsumer();
+ }
+
+ private handleMessage(message: Message) {
+ if (message.type === 'synchronizer_output' && message.id === this.id) {
+ this.sync(message as SynchronizerOutputMessage<TInput>);
+ }
+ }
+
+ private async sync(message: SynchronizerOutputMessage<TInput>) {
+ if (message.id !== this.id) {
+ return;
+ }
+
+ if (this.status === 'processing') {
+ return;
+ }
+
+ this.status = 'processing';
+ let lastCursor: bigint | null = null;
+
+ try {
+ for (const item of message.items) {
+ await this.processor(item.data);
+ lastCursor = BigInt(item.cursor);
+ }
+ } catch (error) {
+ this.debug('Error consuming items', error);
+ } finally {
+ if (lastCursor !== null) {
+ this.cursor = lastCursor;
+ await this.saveCursor(lastCursor);
+ }
+
+ this.status = 'idle';
+ this.initConsumer();
+ }
+ }
+
+ private initConsumer() {
+ if (this.status === 'processing') {
+ return;
+ }
+
+ if (!this.connection.isConnected()) {
+ return;
+ }
+
+ this.debug(`Initializing consumer for ${this.input.type}`);
+
+ const message: SynchronizerInputMessage = {
+ id: this.id,
+ type: 'synchronizer_input',
+ userId: this.workspace.userId,
+ input: this.input,
+ cursor: this.cursor.toString(),
+ };
+
+ const sent = this.connection.send(message);
+ if (sent) {
+ this.status = 'waiting';
+ }
+ }
+
+ private async fetchCursor() {
+ const cursor = await this.workspace.database
+ .selectFrom('cursors')
+ .select('value')
+ .where('key', '=', this.cursorKey)
+ .executeTakeFirst();
+
+ return cursor?.value ?? 0n;
+ }
+
+ private async saveCursor(cursor: bigint) {
+ await this.workspace.database
+ .insertInto('cursors')
+ .values({
+ key: this.cursorKey,
+ value: cursor,
+ created_at: new Date().toISOString(),
+ })
+ .onConflict((eb) =>
+ eb.column('key').doUpdateSet({
+ value: cursor,
+ updated_at: new Date().toISOString(),
+ })
+ )
+ .execute();
+ }
+
+ public destroy() {
+ this.eventLoop.stop();
+ this.connection.off('message', this.handleMessage);
+ }
+
+ public async delete() {
+ await this.workspace.database
+ .deleteFrom('cursors')
+ .where('key', '=', this.cursorKey)
+ .execute();
+
+ this.eventLoop.stop();
+ this.connection.off('message', this.handleMessage);
+ }
+
+ private generateId() {
+ return sha256(
+ JSON.stringify({
+ userId: this.workspace.userId,
+ input: this.input,
+ })
+ );
+ }
+}
diff --git a/apps/desktop/src/main/services/user-service.ts b/apps/desktop/src/main/services/workspaces/user-service.ts
similarity index 66%
rename from apps/desktop/src/main/services/user-service.ts
rename to apps/desktop/src/main/services/workspaces/user-service.ts
index 87e62148..d1a656f9 100644
--- a/apps/desktop/src/main/services/user-service.ts
+++ b/apps/desktop/src/main/services/workspaces/user-service.ts
@@ -1,15 +1,23 @@
-import { SyncUserData, UserStatus } from '@colanode/core';
+import { createDebugger, SyncUserData, UserStatus } from '@colanode/core';
import { mapUser } from '@/main/utils';
-import { databaseService } from '@/main/data/database-service';
import { eventBus } from '@/shared/lib/event-bus';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
-class UserService {
- public async syncServerUser(userId: string, user: SyncUserData) {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
+export class UserService {
+ private readonly debug = createDebugger('desktop:service:user');
+ private readonly workspace: WorkspaceService;
- const createdUser = await workspaceDatabase
+ constructor(workspaceService: WorkspaceService) {
+ this.workspace = workspaceService;
+ }
+
+ public async syncServerUser(user: SyncUserData) {
+ this.debug(
+ `Syncing server user ${user.id} in workspace ${this.workspace.id}`
+ );
+
+ const createdUser = await this.workspace.database
.insertInto('users')
.returningAll()
.values({
@@ -45,12 +53,12 @@ class UserService {
)
.executeTakeFirst();
- await workspaceDatabase
+ await this.workspace.database
.deleteFrom('texts')
.where('id', '=', user.id)
.execute();
- await workspaceDatabase
+ await this.workspace.database
.insertInto('texts')
.values({ id: user.id, name: user.name, text: null })
.execute();
@@ -58,11 +66,10 @@ class UserService {
if (createdUser) {
eventBus.publish({
type: 'user_created',
- userId: userId,
+ accountId: this.workspace.account.id,
+ workspaceId: this.workspace.id,
user: mapUser(createdUser),
});
}
}
}
-
-export const userService = new UserService();
diff --git a/apps/desktop/src/main/services/workspaces/workspace-service.ts b/apps/desktop/src/main/services/workspaces/workspace-service.ts
new file mode 100644
index 00000000..2735f597
--- /dev/null
+++ b/apps/desktop/src/main/services/workspaces/workspace-service.ts
@@ -0,0 +1,140 @@
+import { createDebugger, WorkspaceRole } from '@colanode/core';
+import { Kysely, Migration, Migrator, SqliteDialect } from 'kysely';
+import SQLite from 'better-sqlite3';
+
+import fs from 'fs';
+import path from 'path';
+
+import {
+ WorkspaceDatabaseSchema,
+ workspaceDatabaseMigrations,
+} from '@/main/databases/workspace';
+import { getWorkspaceDirectoryPath } from '@/main/utils';
+import { AccountService } from '@/main/services/accounts/account-service';
+import { EntryService } from '@/main/services/workspaces/entry-service';
+import { MessageService } from '@/main/services/workspaces/message-service';
+import { FileService } from '@/main/services/workspaces/file-service';
+import { Workspace } from '@/shared/types/workspaces';
+import { MutationService } from '@/main/services/workspaces/mutation-service';
+import { UserService } from '@/main/services/workspaces/user-service';
+import { CollaborationService } from '@/main/services/workspaces/collaboration-service';
+import { SyncService } from '@/main/services/workspaces/sync-service';
+import { RadarService } from '@/main/services/workspaces/radar-service';
+
+export class WorkspaceService {
+ private readonly debug = createDebugger('desktop:service:workspace');
+ private readonly workspace: Workspace;
+
+ public readonly database: Kysely<WorkspaceDatabaseSchema>;
+ public readonly account: AccountService;
+ public readonly entries: EntryService;
+ public readonly messages: MessageService;
+ public readonly files: FileService;
+ public readonly mutations: MutationService;
+ public readonly users: UserService;
+ public readonly collaborations: CollaborationService;
+ public readonly synchronizer: SyncService;
+ public readonly radar: RadarService;
+
+ constructor(workspace: Workspace, account: AccountService) {
+ this.debug(`Initializing workspace service ${workspace.id}`);
+
+ this.workspace = workspace;
+ this.account = account;
+
+ const workspacePath = getWorkspaceDirectoryPath(
+ this.account.id,
+ workspace.id
+ );
+
+ if (!fs.existsSync(workspacePath)) {
+ fs.mkdirSync(workspacePath, { recursive: true });
+ }
+
+ const workspaceDatabasePath = path.join(workspacePath, 'workspace.db');
+ const database = new SQLite(workspaceDatabasePath);
+ database.pragma('journal_mode = WAL');
+
+ this.database = new Kysely<WorkspaceDatabaseSchema>({
+ dialect: new SqliteDialect({
+ database,
+ }),
+ });
+
+ this.entries = new EntryService(this);
+ this.messages = new MessageService(this);
+ this.files = new FileService(this);
+ this.mutations = new MutationService(this);
+ this.users = new UserService(this);
+ this.collaborations = new CollaborationService(this);
+ this.synchronizer = new SyncService(this);
+ this.radar = new RadarService(this);
+ }
+
+ public get id(): string {
+ return this.workspace.id;
+ }
+
+ public get accountId(): string {
+ return this.workspace.accountId;
+ }
+
+ public get userId(): string {
+ return this.workspace.userId;
+ }
+
+ public get role(): WorkspaceRole {
+ return this.workspace.role;
+ }
+
+ public updateWorkspace(workspace: Workspace): void {
+ this.workspace.name = workspace.name;
+ this.workspace.description = workspace.description;
+ this.workspace.avatar = workspace.avatar;
+ this.workspace.role = workspace.role;
+ }
+
+ public async init() {
+ await this.migrate();
+ await this.synchronizer.init();
+ await this.radar.init();
+ }
+
+ private async migrate(): Promise<void> {
+ this.debug(
+ `Migrating workspace database for workspace ${this.workspace.id}`
+ );
+
+ const migrator = new Migrator({
+ db: this.database,
+ provider: {
+ getMigrations(): Promise<Record<string, Migration>> {
+ return Promise.resolve(workspaceDatabaseMigrations);
+ },
+ },
+ });
+
+ await migrator.migrateToLatest();
+ }
+
+ public async delete(): Promise<void> {
+ try {
+ this.database.destroy();
+ this.mutations.destroy();
+ this.synchronizer.destroy();
+ this.files.destroy();
+ this.mutations.destroy();
+
+ const workspacePath = getWorkspaceDirectoryPath(
+ this.account.id,
+ this.workspace.id
+ );
+
+ if (fs.existsSync(workspacePath)) {
+ fs.rmSync(workspacePath, { recursive: true, force: true });
+ }
+ } catch (error) {
+ this.debug(`Error deleting workspace ${this.workspace.id}: ${error}`);
+ }
+ }
+}
diff --git a/apps/desktop/src/main/synchronizers/base.ts b/apps/desktop/src/main/synchronizers/base.ts
deleted file mode 100644
index c50a058a..00000000
--- a/apps/desktop/src/main/synchronizers/base.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import { Kysely } from 'kysely';
-import {
- SynchronizerOutputMessage,
- SynchronizerInputMessage,
- SynchronizerInput,
- SynchronizerMap,
- createDebugger,
-} from '@colanode/core';
-import { sha256 } from 'js-sha256';
-
-import { socketService } from '@/main/services/socket-service';
-import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';
-
-export type SynchronizerStatus = 'idle' | 'waiting' | 'processing';
-
-export abstract class BaseSynchronizer<TInput extends SynchronizerInput> {
- public readonly id: string;
- public readonly userId: string;
- public readonly accountId: string;
- public readonly input: TInput;
-
- protected readonly database: Kysely<WorkspaceDatabaseSchema>;
- protected readonly debug = createDebugger('desktop:synchronizer');
-
- private status: SynchronizerStatus = 'idle';
- private cursor: bigint = 0n;
-
- constructor(
- userId: string,
- accountId: string,
- input: TInput,
- database: Kysely<WorkspaceDatabaseSchema>
- ) {
- this.id = this.generateId(userId, input);
- this.userId = userId;
- this.accountId = accountId;
- this.input = input;
- this.database = database;
- }
-
- protected abstract process(
- data: SynchronizerMap[TInput['type']]['data']
- ): Promise<void>;
-
- protected abstract get cursorKey(): string;
-
- public async init() {
- this.cursor = await this.fetchCursor();
- this.initConsumer();
- }
-
- public async ping() {
- this.initConsumer();
- }
-
- public async sync(message: SynchronizerOutputMessage<TInput>) {
- if (message.id !== this.id) {
- return;
- }
-
- if (this.status === 'processing') {
- return;
- }
-
- this.status = 'processing';
- let lastCursor: bigint | null = null;
-
- try {
- for (const item of message.items) {
- await this.process(item.data);
- lastCursor = BigInt(item.cursor);
- }
- } catch (error) {
- this.debug('Error consuming items', error);
- } finally {
- if (lastCursor !== null) {
- this.cursor = lastCursor;
- await this.saveCursor(lastCursor);
- }
-
- this.status = 'idle';
- this.initConsumer();
- }
- }
-
- private initConsumer() {
- if (this.status === 'processing') {
- return;
- }
-
- const message: SynchronizerInputMessage = {
- type: 'synchronizer_input',
- userId: this.userId,
- id: this.id,
- input: this.input,
- cursor: this.cursor.toString(),
- };
-
- const sent = socketService.sendMessage(this.accountId, message);
- if (sent) {
- this.status = 'waiting';
- }
- }
-
- private async fetchCursor() {
- const cursor = await this.database
- .selectFrom('cursors')
- .select('value')
- .where('key', '=', this.cursorKey)
- .executeTakeFirst();
-
- return cursor?.value ?? 0n;
- }
-
- private async saveCursor(cursor: bigint) {
- await this.database
- .insertInto('cursors')
- .values({
- key: this.cursorKey,
- value: cursor,
- created_at: new Date().toISOString(),
- })
- .onConflict((eb) =>
- eb.column('key').doUpdateSet({
- value: cursor,
- updated_at: new Date().toISOString(),
- })
- )
- .execute();
- }
-
- public async delete() {
- try {
- await this.database
- .deleteFrom('cursors')
- .where('key', '=', this.cursorKey)
- .execute();
- } catch {
- this.debug('Failed to delete cursor', this.cursorKey);
- }
- }
-
- private generateId(userId: string, input: TInput) {
- const idObj = {
- userId,
- input,
- };
-
- return sha256(JSON.stringify(idObj));
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/collaborations.ts b/apps/desktop/src/main/synchronizers/collaborations.ts
deleted file mode 100644
index 3dcc69b8..00000000
--- a/apps/desktop/src/main/synchronizers/collaborations.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { SyncCollaborationData, SyncCollaborationsInput } from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { collaborationService } from '@/main/services/collaboration-service';
-
-export class CollaborationSynchronizer extends BaseSynchronizer<SyncCollaborationsInput> {
- protected async process(data: SyncCollaborationData): Promise<void> {
- await collaborationService.syncServerCollaboration(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `collaborations`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/entry-interactions.ts b/apps/desktop/src/main/synchronizers/entry-interactions.ts
deleted file mode 100644
index 645107ba..00000000
--- a/apps/desktop/src/main/synchronizers/entry-interactions.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import {
- SyncEntryInteractionsInput,
- SyncEntryInteractionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { entryService } from '@/main/services/entry-service';
-
-export class EntryInteractionSynchronizer extends BaseSynchronizer<SyncEntryInteractionsInput> {
- protected async process(data: SyncEntryInteractionData): Promise<void> {
- await entryService.syncServerEntryInteraction(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `entry_interactions:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/entry-transactions.ts b/apps/desktop/src/main/synchronizers/entry-transactions.ts
deleted file mode 100644
index 449b5faf..00000000
--- a/apps/desktop/src/main/synchronizers/entry-transactions.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import {
- SyncEntryTransactionData,
- SyncEntryTransactionsInput,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { entryService } from '@/main/services/entry-service';
-
-export class EntryTransactionSynchronizer extends BaseSynchronizer<SyncEntryTransactionsInput> {
- protected async process(data: SyncEntryTransactionData): Promise<void> {
- await entryService.applyServerTransaction(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `entry_transactions:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/file-interactions.ts b/apps/desktop/src/main/synchronizers/file-interactions.ts
deleted file mode 100644
index 71dd4ccd..00000000
--- a/apps/desktop/src/main/synchronizers/file-interactions.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import {
- SyncFileInteractionsInput,
- SyncFileInteractionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { fileService } from '@/main/services/file-service';
-
-export class FileInteractionSynchronizer extends BaseSynchronizer<SyncFileInteractionsInput> {
- protected async process(data: SyncFileInteractionData): Promise<void> {
- await fileService.syncServerFileInteraction(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `file_interactions:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/file-tombstones.ts b/apps/desktop/src/main/synchronizers/file-tombstones.ts
deleted file mode 100644
index 2ee841cc..00000000
--- a/apps/desktop/src/main/synchronizers/file-tombstones.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { SyncFileTombstonesInput, SyncFileTombstoneData } from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { fileService } from '@/main/services/file-service';
-
-export class FileTombstoneSynchronizer extends BaseSynchronizer<SyncFileTombstonesInput> {
- protected async process(data: SyncFileTombstoneData): Promise<void> {
- await fileService.syncServerFileTombstone(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `file_tombstones:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/files.ts b/apps/desktop/src/main/synchronizers/files.ts
deleted file mode 100644
index 26fb8f91..00000000
--- a/apps/desktop/src/main/synchronizers/files.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { SyncFilesInput, SyncFileData } from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { fileService } from '@/main/services/file-service';
-
-export class FileSynchronizer extends BaseSynchronizer<SyncFilesInput> {
- protected async process(data: SyncFileData): Promise<void> {
- await fileService.syncServerFile(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `files:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/message-interactions.ts b/apps/desktop/src/main/synchronizers/message-interactions.ts
deleted file mode 100644
index 2d99a04e..00000000
--- a/apps/desktop/src/main/synchronizers/message-interactions.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import {
- SyncMessageInteractionsInput,
- SyncMessageInteractionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { messageService } from '@/main/services/message-service';
-
-export class MessageInteractionSynchronizer extends BaseSynchronizer<SyncMessageInteractionsInput> {
- protected async process(data: SyncMessageInteractionData): Promise<void> {
- await messageService.syncServerMessageInteraction(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `message_interactions:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/message-reactions.ts b/apps/desktop/src/main/synchronizers/message-reactions.ts
deleted file mode 100644
index 3e2ecea0..00000000
--- a/apps/desktop/src/main/synchronizers/message-reactions.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import {
- SyncMessageReactionsInput,
- SyncMessageReactionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { messageService } from '@/main/services/message-service';
-
-export class MessageReactionSynchronizer extends BaseSynchronizer<SyncMessageReactionsInput> {
- protected async process(data: SyncMessageReactionData): Promise<void> {
- await messageService.syncServerMessageReaction(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `message_reactions:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/message-tombstones.ts b/apps/desktop/src/main/synchronizers/message-tombstones.ts
deleted file mode 100644
index 4ede6cce..00000000
--- a/apps/desktop/src/main/synchronizers/message-tombstones.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import {
- SyncMessageTombstonesInput,
- SyncMessageTombstoneData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { messageService } from '@/main/services/message-service';
-
-export class MessageTombstoneSynchronizer extends BaseSynchronizer<SyncMessageTombstonesInput> {
- protected async process(data: SyncMessageTombstoneData): Promise<void> {
- await messageService.syncServerMessageTombstone(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `message_tombstones:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/messages.ts b/apps/desktop/src/main/synchronizers/messages.ts
deleted file mode 100644
index 93502ea7..00000000
--- a/apps/desktop/src/main/synchronizers/messages.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { SyncMessagesInput, SyncMessageData } from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { messageService } from '@/main/services/message-service';
-
-export class MessageSynchronizer extends BaseSynchronizer<SyncMessagesInput> {
- protected async process(data: SyncMessageData): Promise<void> {
- await messageService.syncServerMessage(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `messages:${this.input.rootId}`;
- }
-}
diff --git a/apps/desktop/src/main/synchronizers/users.ts b/apps/desktop/src/main/synchronizers/users.ts
deleted file mode 100644
index 1bd8a056..00000000
--- a/apps/desktop/src/main/synchronizers/users.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { SyncUserData, SyncUsersInput } from '@colanode/core';
-
-import { BaseSynchronizer } from '@/main/synchronizers/base';
-import { userService } from '@/main/services/user-service';
-
-export class UserSynchronizer extends BaseSynchronizer<SyncUsersInput> {
- protected async process(data: SyncUserData): Promise<void> {
- await userService.syncServerUser(this.userId, data);
- }
-
- protected get cursorKey(): string {
- return `users`;
- }
-}
diff --git a/apps/desktop/src/main/utils.ts b/apps/desktop/src/main/utils.ts
index 7ac3b44e..04c67a9e 100644
--- a/apps/desktop/src/main/utils.ts
+++ b/apps/desktop/src/main/utils.ts
@@ -3,6 +3,7 @@ import {
Mutation,
Entry,
TransactionOperation,
+ extractFileType,
} from '@colanode/core';
import { encodeState } from '@colanode/crdt';
import {
@@ -12,17 +13,14 @@ import {
Transaction,
UpdateResult,
} from 'kysely';
+import mime from 'mime-types';
import { app } from 'electron';
import path from 'path';
+import fs from 'fs';
-import { databaseService } from './data/database-service';
-
-import {
- SelectAccount,
- SelectServer,
- SelectWorkspace,
-} from '@/main/data/app/schema';
+import { SelectAccount, SelectServer } from '@/main/databases/app';
+import { SelectWorkspace } from '@/main/databases/account';
import {
SelectFile,
SelectFileState,
@@ -36,12 +34,17 @@ import {
SelectMessageInteraction,
SelectFileInteraction,
SelectEntryInteraction,
-} from '@/main/data/workspace/schema';
+} from '@/main/databases/workspace';
import { Account } from '@/shared/types/accounts';
import { Server } from '@/shared/types/servers';
import { User } from '@/shared/types/users';
-import { File, FileInteraction, FileState } from '@/shared/types/files';
-import { Workspace, WorkspaceCredentials } from '@/shared/types/workspaces';
+import {
+ File,
+ FileInteraction,
+ FileMetadata,
+ FileState,
+} from '@/shared/types/files';
+import { Workspace } from '@/shared/types/workspaces';
import {
MessageInteraction,
MessageNode,
@@ -53,20 +56,37 @@ export const appPath = app.getPath('userData');
export const appDatabasePath = path.join(appPath, 'app.db');
-export const getWorkspaceDirectoryPath = (userId: string): string => {
- return path.join(appPath, 'workspaces', userId);
+export const getAccountDirectoryPath = (accountId: string): string => {
+ return path.join(appPath, 'accounts', accountId);
};
-export const getWorkspaceFilesDirectoryPath = (userId: string): string => {
- return path.join(getWorkspaceDirectoryPath(userId), 'files');
+export const getWorkspaceDirectoryPath = (
+ accountId: string,
+ workspaceId: string
+): string => {
+ return path.join(
+ getAccountDirectoryPath(accountId),
+ 'workspaces',
+ workspaceId
+ );
};
-export const getWorkspaceTempFilesDirectoryPath = (userId: string): string => {
- return path.join(getWorkspaceDirectoryPath(userId), 'temp');
+export const getWorkspaceFilesDirectoryPath = (
+ accountId: string,
+ workspaceId: string
+): string => {
+ return path.join(getWorkspaceDirectoryPath(accountId, workspaceId), 'files');
+};
+
+export const getWorkspaceTempFilesDirectoryPath = (
+ accountId: string,
+ workspaceId: string
+): string => {
+ return path.join(getWorkspaceDirectoryPath(accountId, workspaceId), 'temp');
};
export const getAccountAvatarsDirectoryPath = (accountId: string): string => {
- return path.join(appPath, 'avatars', accountId);
+ return path.join(getAccountDirectoryPath(accountId), 'avatars');
};
export const getAssetsSourcePath = (): string => {
@@ -103,6 +123,29 @@ export const hasDeleteChanges = (result: DeleteResult[]): boolean => {
return result.some((r) => r.numDeletedRows && r.numDeletedRows > 0n);
};
+export const getFileMetadata = (filePath: string): FileMetadata | null => {
+ if (!fs.existsSync(filePath)) {
+ return null;
+ }
+
+ const mimeType = mime.lookup(filePath);
+ if (mimeType === false) {
+ return null;
+ }
+
+ const stats = fs.statSync(filePath);
+ const type = extractFileType(mimeType);
+
+ return {
+ path: filePath,
+ mimeType,
+ extension: path.extname(filePath),
+ name: path.basename(filePath),
+ size: stats.size,
+ type,
+ };
+};
+
export const fetchEntryAncestors = (
database:
| Kysely<WorkspaceDatabaseSchema>
@@ -164,38 +207,6 @@ export const fetchUserStorageUsed = async (
return BigInt(storageUsedRow?.storage_used ?? 0);
};
-export const fetchWorkspaceCredentials = async (
- userId: string
-): Promise<WorkspaceCredentials | null> => {
- const workspace = await databaseService.appDatabase
- .selectFrom('workspaces')
- .innerJoin('accounts', 'workspaces.account_id', 'accounts.id')
- .innerJoin('servers', 'accounts.server', 'servers.domain')
- .select([
- 'workspaces.workspace_id',
- 'workspaces.user_id',
- 'workspaces.account_id',
- 'accounts.token',
- 'servers.domain',
- 'servers.attributes',
- ])
- .where('workspaces.user_id', '=', userId)
- .executeTakeFirst();
-
- if (!workspace) {
- return null;
- }
-
- return {
- workspaceId: workspace.workspace_id,
- accountId: workspace.account_id,
- userId: workspace.user_id,
- token: workspace.token,
- serverDomain: workspace.domain,
- serverAttributes: workspace.attributes,
- };
-};
-
export const mapUser = (row: SelectUser): User => {
return {
id: row.id,
@@ -239,7 +250,7 @@ export const mapAccount = (row: SelectAccount): Account => {
export const mapWorkspace = (row: SelectWorkspace): Workspace => {
return {
- id: row.workspace_id,
+ id: row.id,
name: row.name,
accountId: row.account_id,
role: row.role,
diff --git a/apps/desktop/src/renderer/components/channels/channel-body.tsx b/apps/desktop/src/renderer/components/channels/channel-body.tsx
index f80a5bed..dd1b85d6 100644
--- a/apps/desktop/src/renderer/components/channels/channel-body.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-body.tsx
@@ -15,10 +15,10 @@ export const ChannelBody = ({ channel, role }: ChannelBodyProps) => {
const radar = useRadar();
useEffect(() => {
- radar.markEntryAsOpened(workspace.userId, channel.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, channel.id);
const interval = setInterval(() => {
- radar.markEntryAsOpened(workspace.userId, channel.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, channel.id);
}, 60000);
return () => clearInterval(interval);
diff --git a/apps/desktop/src/renderer/components/channels/channel-container.tsx b/apps/desktop/src/renderer/components/channels/channel-container.tsx
index e3cdbef6..beea9b27 100644
--- a/apps/desktop/src/renderer/components/channels/channel-container.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-container.tsx
@@ -16,7 +16,8 @@ export const ChannelContainer = ({ channelId }: ChannelContainerProps) => {
const { data: entry, isPending: isPendingEntry } = useQuery({
type: 'entry_get',
entryId: channelId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const channel = entry as ChannelEntry;
@@ -26,7 +27,8 @@ export const ChannelContainer = ({ channelId }: ChannelContainerProps) => {
{
type: 'entry_get',
entryId: channel?.rootId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: channelExists,
diff --git a/apps/desktop/src/renderer/components/channels/channel-create-dialog.tsx b/apps/desktop/src/renderer/components/channels/channel-create-dialog.tsx
index cb3d63ae..6285390d 100644
--- a/apps/desktop/src/renderer/components/channels/channel-create-dialog.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-create-dialog.tsx
@@ -56,7 +56,8 @@ export const ChannelCreateDialog = ({
spaceId: spaceId,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess(output) {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/channels/channel-delete-dialog.tsx b/apps/desktop/src/renderer/components/channels/channel-delete-dialog.tsx
index e7b8b0c8..7f61ea5e 100644
--- a/apps/desktop/src/renderer/components/channels/channel-delete-dialog.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-delete-dialog.tsx
@@ -48,7 +48,8 @@ export const ChannelDeleteDialog = ({
input: {
type: 'channel_delete',
channelId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx b/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx
index 00e13afe..2a1c05a8 100644
--- a/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx
@@ -16,7 +16,11 @@ export const ChannelSidebarItem = ({ channel }: ChannelSidebarItemProps) => {
const radar = useRadar();
const isActive = workspace.isEntryActive(channel.id);
- const channelState = radar.getChannelState(workspace.userId, channel.id);
+ const channelState = radar.getChannelState(
+ workspace.accountId,
+ workspace.id,
+ channel.id
+ );
const unreadCount = channelState.unseenMessagesCount;
const mentionsCount = channelState.mentionsCount;
@@ -25,7 +29,7 @@ export const ChannelSidebarItem = ({ channel }: ChannelSidebarItemProps) => {
rootMargin="20px"
onChange={(inView) => {
if (inView) {
- radar.markEntryAsSeen(workspace.userId, channel.id);
+ radar.markEntryAsSeen(workspace.accountId, workspace.id, channel.id);
}
}}
className={cn(
diff --git a/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx b/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
index 7c0b9321..d033a1f1 100644
--- a/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
@@ -61,7 +61,8 @@ export const ChannelUpdateDialog = ({
channelId: channel.id,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/chats/chat-body.tsx b/apps/desktop/src/renderer/components/chats/chat-body.tsx
index aae312c8..cd6f8c6f 100644
--- a/apps/desktop/src/renderer/components/chats/chat-body.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-body.tsx
@@ -15,10 +15,10 @@ export const ChatBody = ({ chat, role }: ChatBodyProps) => {
const radar = useRadar();
useEffect(() => {
- radar.markEntryAsOpened(workspace.userId, chat.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, chat.id);
const interval = setInterval(() => {
- radar.markEntryAsOpened(workspace.userId, chat.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, chat.id);
}, 60000);
return () => clearInterval(interval);
diff --git a/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
index 37c597a5..e2506088 100644
--- a/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
@@ -17,8 +17,9 @@ export const ChatBreadcrumbItem = ({ chat }: ChatBreadcrumbItemProps) => {
const { data, isPending } = useQuery({
type: 'user_get',
- id: userId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId,
});
if (isPending || !data) {
diff --git a/apps/desktop/src/renderer/components/chats/chat-container.tsx b/apps/desktop/src/renderer/components/chats/chat-container.tsx
index ae62d4ac..84276dd0 100644
--- a/apps/desktop/src/renderer/components/chats/chat-container.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-container.tsx
@@ -16,7 +16,8 @@ export const ChatContainer = ({ chatId }: ChatContainerProps) => {
const { data, isPending } = useQuery({
type: 'entry_get',
entryId: chatId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
if (isPending) {
diff --git a/apps/desktop/src/renderer/components/chats/chat-create-popover.tsx b/apps/desktop/src/renderer/components/chats/chat-create-popover.tsx
index 5f1eab9f..88685bcc 100644
--- a/apps/desktop/src/renderer/components/chats/chat-create-popover.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-create-popover.tsx
@@ -30,9 +30,9 @@ export const ChatCreatePopover = () => {
mutate({
input: {
type: 'chat_create',
- userId: workspace.userId,
- otherUserId: user.id,
+ accountId: workspace.accountId,
workspaceId: workspace.id,
+ userId: user.id,
},
onSuccess(output) {
workspace.openInMain(output.id);
diff --git a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
index cb2bd5f5..8b1d96f8 100644
--- a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
@@ -23,15 +23,20 @@ export const ChatSidebarItem = ({ chat }: ChatSidebarItemProps) => {
const { data, isPending } = useQuery({
type: 'user_get',
- id: userId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId,
});
if (isPending || !data) {
return null;
}
- const nodeReadState = radar.getChatState(workspace.userId, chat.id);
+ const nodeReadState = radar.getChatState(
+ workspace.accountId,
+ workspace.id,
+ chat.id
+ );
const isActive = workspace.isEntryActive(chat.id);
const unreadCount =
nodeReadState.unseenMessagesCount + nodeReadState.mentionsCount;
@@ -41,7 +46,7 @@ export const ChatSidebarItem = ({ chat }: ChatSidebarItemProps) => {
rootMargin="20px"
onChange={(inView) => {
if (inView) {
- radar.markEntryAsSeen(workspace.userId, chat.id);
+ radar.markEntryAsSeen(workspace.accountId, workspace.id, chat.id);
}
}}
className={cn(
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-audit.tsx b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-audit.tsx
index 65fc4fcf..45107e12 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-audit.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-audit.tsx
@@ -16,8 +16,9 @@ export const EntryCollaboratorAudit = ({
const workspace = useWorkspace();
const { data, isPending } = useQuery({
type: 'user_get',
- id: collaboratorId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: collaboratorId,
});
if (isPending || !data) {
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-create.tsx b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-create.tsx
index fd5b4e6d..82d14f1f 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-create.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-create.tsx
@@ -54,7 +54,8 @@ export const EntryCollaboratorCreate = ({
entryId,
collaboratorIds: users.map((user) => user.id),
role: role,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
setUsers([]);
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-search.tsx b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-search.tsx
index 206474c4..ec19d608 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-search.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-search.tsx
@@ -41,7 +41,8 @@ export const EntryCollaboratorSearch = ({
type: 'user_search',
searchQuery: query,
exclude: excluded,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const users = data ?? [];
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator.tsx b/apps/desktop/src/renderer/components/collaborators/entry-collaborator.tsx
index 94ae109f..1fd25496 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/entry-collaborator.tsx
@@ -28,8 +28,9 @@ export const EntryCollaborator = ({
const { data } = useQuery({
type: 'user_get',
- id: collaboratorId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: collaboratorId,
});
if (!data) {
@@ -56,7 +57,8 @@ export const EntryCollaborator = ({
entryId: entryId,
collaboratorId: collaboratorId,
role: newRole,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
@@ -77,7 +79,8 @@ export const EntryCollaborator = ({
type: 'entry_collaborator_delete',
entryId: entryId,
collaboratorId: collaboratorId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
});
}}
diff --git a/apps/desktop/src/renderer/components/databases/database-body.tsx b/apps/desktop/src/renderer/components/databases/database-body.tsx
index cc5148eb..dc42abdf 100644
--- a/apps/desktop/src/renderer/components/databases/database-body.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-body.tsx
@@ -16,10 +16,10 @@ export const DatabaseBody = ({ database, role }: DatabaseBodyProps) => {
const radar = useRadar();
useEffect(() => {
- radar.markEntryAsOpened(workspace.userId, database.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, database.id);
const interval = setInterval(() => {
- radar.markEntryAsOpened(workspace.userId, database.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, database.id);
}, 60000);
return () => clearInterval(interval);
diff --git a/apps/desktop/src/renderer/components/databases/database-container.tsx b/apps/desktop/src/renderer/components/databases/database-container.tsx
index af4e7e3f..ee73064f 100644
--- a/apps/desktop/src/renderer/components/databases/database-container.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-container.tsx
@@ -16,7 +16,8 @@ export const DatabaseContainer = ({ databaseId }: DatabaseContainerProps) => {
const { data: entry, isPending: isPendingEntry } = useQuery({
type: 'entry_get',
entryId: databaseId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const database = entry as DatabaseEntry;
@@ -26,7 +27,8 @@ export const DatabaseContainer = ({ databaseId }: DatabaseContainerProps) => {
{
type: 'entry_get',
entryId: database?.rootId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: databaseExists,
diff --git a/apps/desktop/src/renderer/components/databases/database-create-dialog.tsx b/apps/desktop/src/renderer/components/databases/database-create-dialog.tsx
index 3edd4e48..881f2279 100644
--- a/apps/desktop/src/renderer/components/databases/database-create-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-create-dialog.tsx
@@ -56,7 +56,8 @@ export const DatabaseCreateDialog = ({
spaceId: spaceId,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess(output) {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/databases/database-delete-dialog.tsx b/apps/desktop/src/renderer/components/databases/database-delete-dialog.tsx
index d4440cb0..a4312a74 100644
--- a/apps/desktop/src/renderer/components/databases/database-delete-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-delete-dialog.tsx
@@ -48,7 +48,8 @@ export const DatabaseDeleteDialog = ({
input: {
type: 'database_delete',
databaseId: entryId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/databases/database-select.tsx b/apps/desktop/src/renderer/components/databases/database-select.tsx
index 371901cc..65cdc8fb 100644
--- a/apps/desktop/src/renderer/components/databases/database-select.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-select.tsx
@@ -30,7 +30,8 @@ export const DatabaseSelect = ({ id, onChange }: DatabaseSelectProps) => {
const [open, setOpen] = React.useState(false);
const { data } = useQuery({
type: 'database_list',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const databases = data ?? [];
diff --git a/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx b/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
index a4eb6968..dc499720 100644
--- a/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
@@ -61,7 +61,8 @@ export const DatabaseUpdateDialog = ({
databaseId: database.id,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/databases/database.tsx b/apps/desktop/src/renderer/components/databases/database.tsx
index e7bb6ba1..fcce4bd7 100644
--- a/apps/desktop/src/renderer/components/databases/database.tsx
+++ b/apps/desktop/src/renderer/components/databases/database.tsx
@@ -40,7 +40,8 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
databaseId: database.id,
name,
fieldType: type,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
@@ -62,7 +63,8 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
databaseId: database.id,
fieldId: id,
name,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
@@ -83,7 +85,8 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
type: 'field_delete',
databaseId: database.id,
fieldId: id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
@@ -106,7 +109,8 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
fieldId,
name,
color,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
@@ -130,7 +134,8 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
optionId: attributes.id,
name: attributes.name,
color: attributes.color,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
@@ -152,7 +157,8 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
databaseId: database.id,
fieldId,
optionId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
diff --git a/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx b/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
index 64312855..8f246fd5 100644
--- a/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
+++ b/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
@@ -79,7 +79,8 @@ export const FieldCreatePopover = () => {
databaseId: database.id,
name: values.name,
fieldType: values.type,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
relationDatabaseId: values.relationDatabaseId,
},
onSuccess: () => {
diff --git a/apps/desktop/src/renderer/components/databases/fields/select-field-options.tsx b/apps/desktop/src/renderer/components/databases/fields/select-field-options.tsx
index bbd0001c..620875fd 100644
--- a/apps/desktop/src/renderer/components/databases/fields/select-field-options.tsx
+++ b/apps/desktop/src/renderer/components/databases/fields/select-field-options.tsx
@@ -119,7 +119,8 @@ export const SelectFieldOptions = ({
fieldId: field.id,
name: inputValue.trim(),
color,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess(output) {
setInputValue('');
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
index 79376963..ec7d4553 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
@@ -72,7 +72,8 @@ export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
type: 'record_name_update',
name: newName,
recordId: record.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
setIsEditing(false);
diff --git a/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx b/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx
index cf46d45b..8f55c64b 100644
--- a/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx
@@ -135,7 +135,8 @@ export const ViewCreateDialog = ({
viewType: values.type,
databaseId: database.id,
name: values.name,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
groupBy: values.groupBy ?? null,
},
onSuccess() {
diff --git a/apps/desktop/src/renderer/components/databases/view-delete-dialog.tsx b/apps/desktop/src/renderer/components/databases/view-delete-dialog.tsx
index 994fc504..f583a8c0 100644
--- a/apps/desktop/src/renderer/components/databases/view-delete-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/view-delete-dialog.tsx
@@ -55,7 +55,8 @@ export const ViewDeleteDialog = ({
type: 'view_delete',
viewId: id,
databaseId: database.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/databases/view.tsx b/apps/desktop/src/renderer/components/databases/view.tsx
index 88772583..16e936b8 100644
--- a/apps/desktop/src/renderer/components/databases/view.tsx
+++ b/apps/desktop/src/renderer/components/databases/view.tsx
@@ -83,7 +83,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -107,7 +108,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -144,7 +146,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -181,7 +184,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -209,7 +213,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -251,7 +256,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -296,7 +302,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -329,7 +336,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -361,7 +369,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -405,7 +414,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -438,7 +448,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -471,7 +482,8 @@ export const View = ({ view }: ViewProps) => {
mutate({
input: {
type: 'view_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
view: viewCopy,
},
@@ -520,7 +532,8 @@ export const View = ({ view }: ViewProps) => {
input: {
type: 'record_create',
databaseId: database.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fields,
},
onSuccess: (output) => {
diff --git a/apps/desktop/src/renderer/components/documents/document-editor.tsx b/apps/desktop/src/renderer/components/documents/document-editor.tsx
index bcf53a12..15874cab 100644
--- a/apps/desktop/src/renderer/components/documents/document-editor.tsx
+++ b/apps/desktop/src/renderer/components/documents/document-editor.tsx
@@ -110,7 +110,8 @@ export const DocumentEditor = ({
FolderNode,
FileNode.configure({
context: {
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
documentId,
rootId,
},
@@ -155,7 +156,8 @@ export const DocumentEditor = ({
],
context: {
documentId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
rootId,
},
}),
diff --git a/apps/desktop/src/renderer/components/files/file-block.tsx b/apps/desktop/src/renderer/components/files/file-block.tsx
index 86695375..a73f1853 100644
--- a/apps/desktop/src/renderer/components/files/file-block.tsx
+++ b/apps/desktop/src/renderer/components/files/file-block.tsx
@@ -12,7 +12,8 @@ export const FileBlock = ({ id }: FileBlockProps) => {
const { data } = useQuery({
type: 'file_get',
id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
if (!data) {
diff --git a/apps/desktop/src/renderer/components/files/file-body.tsx b/apps/desktop/src/renderer/components/files/file-body.tsx
index 4052611b..fbb27322 100644
--- a/apps/desktop/src/renderer/components/files/file-body.tsx
+++ b/apps/desktop/src/renderer/components/files/file-body.tsx
@@ -46,7 +46,8 @@ export const FileBody = ({ file }: FileBodyProps) => {
onClick={() =>
window.colanode.executeCommand({
type: 'file_open',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fileId: file.id,
extension: file.extension,
})
diff --git a/apps/desktop/src/renderer/components/files/file-container.tsx b/apps/desktop/src/renderer/components/files/file-container.tsx
index 7832c2e8..aeb9fd62 100644
--- a/apps/desktop/src/renderer/components/files/file-container.tsx
+++ b/apps/desktop/src/renderer/components/files/file-container.tsx
@@ -16,7 +16,8 @@ export const FileContainer = ({ fileId }: FileContainerProps) => {
const { data: file, isPending: isPendingFile } = useQuery({
type: 'file_get',
id: fileId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const fileExists = !!file;
@@ -25,7 +26,8 @@ export const FileContainer = ({ fileId }: FileContainerProps) => {
{
type: 'entry_get',
entryId: file?.entryId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: fileExists,
@@ -36,7 +38,8 @@ export const FileContainer = ({ fileId }: FileContainerProps) => {
{
type: 'entry_get',
entryId: file?.rootId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: fileExists,
diff --git a/apps/desktop/src/renderer/components/files/file-delete-dialog.tsx b/apps/desktop/src/renderer/components/files/file-delete-dialog.tsx
index e3d0fdad..5585a855 100644
--- a/apps/desktop/src/renderer/components/files/file-delete-dialog.tsx
+++ b/apps/desktop/src/renderer/components/files/file-delete-dialog.tsx
@@ -48,7 +48,8 @@ export const FileDeleteDialog = ({
input: {
type: 'file_delete',
fileId: fileId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/files/file-download.tsx b/apps/desktop/src/renderer/components/files/file-download.tsx
index a9f284dd..67c3f881 100644
--- a/apps/desktop/src/renderer/components/files/file-download.tsx
+++ b/apps/desktop/src/renderer/components/files/file-download.tsx
@@ -34,7 +34,8 @@ export const FileDownload = ({ file }: FileDownloadProps) => {
mutate({
input: {
type: 'file_download',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
fileId: file.id,
},
onError(error) {
diff --git a/apps/desktop/src/renderer/components/files/file-sidebar.tsx b/apps/desktop/src/renderer/components/files/file-sidebar.tsx
index 3570795c..97f834b3 100644
--- a/apps/desktop/src/renderer/components/files/file-sidebar.tsx
+++ b/apps/desktop/src/renderer/components/files/file-sidebar.tsx
@@ -25,8 +25,9 @@ export const FileSidebar = ({ file }: FileSidebarProps) => {
const workspace = useWorkspace();
const { data } = useQuery({
type: 'user_get',
- id: file.createdBy,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: file.createdBy,
});
const user = data ?? null;
diff --git a/apps/desktop/src/renderer/components/folders/folder-body.tsx b/apps/desktop/src/renderer/components/folders/folder-body.tsx
index ed2536ca..8557b79c 100644
--- a/apps/desktop/src/renderer/components/folders/folder-body.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-body.tsx
@@ -101,7 +101,8 @@ export const FolderBody = ({ folder }: FolderBodyProps) => {
mutate({
input: {
type: 'file_create',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
filePath,
parentId: folder.id,
entryId: folder.id,
@@ -120,10 +121,10 @@ export const FolderBody = ({ folder }: FolderBodyProps) => {
};
useEffect(() => {
- radar.markEntryAsOpened(workspace.userId, folder.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, folder.id);
const interval = setInterval(() => {
- radar.markEntryAsOpened(workspace.userId, folder.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, folder.id);
}, 60000);
return () => clearInterval(interval);
diff --git a/apps/desktop/src/renderer/components/folders/folder-container.tsx b/apps/desktop/src/renderer/components/folders/folder-container.tsx
index 116345f9..40f1b547 100644
--- a/apps/desktop/src/renderer/components/folders/folder-container.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-container.tsx
@@ -16,7 +16,8 @@ export const FolderContainer = ({ folderId }: FolderContainerProps) => {
const { data: entry, isPending: isPendingEntry } = useQuery({
type: 'entry_get',
entryId: folderId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const folder = entry as FolderEntry;
@@ -26,7 +27,8 @@ export const FolderContainer = ({ folderId }: FolderContainerProps) => {
{
type: 'entry_get',
entryId: folder?.rootId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: folderExists,
diff --git a/apps/desktop/src/renderer/components/folders/folder-create-dialog.tsx b/apps/desktop/src/renderer/components/folders/folder-create-dialog.tsx
index 3a8f6880..ecee4df9 100644
--- a/apps/desktop/src/renderer/components/folders/folder-create-dialog.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-create-dialog.tsx
@@ -56,7 +56,8 @@ export const FolderCreateDialog = ({
parentId: spaceId,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
generateIndex: true,
},
onSuccess(output) {
diff --git a/apps/desktop/src/renderer/components/folders/folder-delete-dialog.tsx b/apps/desktop/src/renderer/components/folders/folder-delete-dialog.tsx
index 14d0437c..fd5db097 100644
--- a/apps/desktop/src/renderer/components/folders/folder-delete-dialog.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-delete-dialog.tsx
@@ -48,7 +48,8 @@ export const FolderDeleteDialog = ({
input: {
type: 'folder_delete',
folderId: entryId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/folders/folder-files.tsx b/apps/desktop/src/renderer/components/folders/folder-files.tsx
index 77c8e788..947b8b24 100644
--- a/apps/desktop/src/renderer/components/folders/folder-files.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-files.tsx
@@ -26,7 +26,8 @@ export const FolderFiles = ({ id, name, layout }: FolderFilesProps) => {
length: lastPage,
}).map((_, i) => ({
type: 'file_list',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
parentId: id,
count: FILES_PER_PAGE,
page: i + 1,
diff --git a/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx b/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
index 3cd41538..c744f8c7 100644
--- a/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
@@ -59,7 +59,8 @@ export const FolderUpdateDialog = ({
folderId: folder.id,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx b/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx
index 610af1f7..449d63db 100644
--- a/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx
+++ b/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx
@@ -30,7 +30,8 @@ export const EntryBreadcrumb = ({ entry }: EntryBreadcrumbProps) => {
{
type: 'entry_tree_get',
entryId: entry.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: entry.type !== 'chat',
diff --git a/apps/desktop/src/renderer/components/layouts/layout-sidebar-chats.tsx b/apps/desktop/src/renderer/components/layouts/layout-sidebar-chats.tsx
index 982d4b2b..ee99cd17 100644
--- a/apps/desktop/src/renderer/components/layouts/layout-sidebar-chats.tsx
+++ b/apps/desktop/src/renderer/components/layouts/layout-sidebar-chats.tsx
@@ -9,8 +9,8 @@ export const LayoutSidebarChats = () => {
const { data } = useQuery({
type: 'chat_list',
- userId: workspace.userId,
- parentId: workspace.id,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
page: 0,
count: 100,
});
diff --git a/apps/desktop/src/renderer/components/layouts/layout-sidebar-header.tsx b/apps/desktop/src/renderer/components/layouts/layout-sidebar-header.tsx
index 77b347a1..673f3b57 100644
--- a/apps/desktop/src/renderer/components/layouts/layout-sidebar-header.tsx
+++ b/apps/desktop/src/renderer/components/layouts/layout-sidebar-header.tsx
@@ -32,7 +32,7 @@ export const LayoutSidebarHeader = () => {
const workspaces = data ?? [];
const otherWorkspaces = workspaces.filter((w) => w.id !== workspace.id);
const otherWorkspaceStates = otherWorkspaces.map((w) =>
- radar.getWorkspaceState(w.userId)
+ radar.getWorkspaceState(w.accountId, w.id)
);
const importantCount = otherWorkspaceStates.reduce(
(acc, curr) => acc + curr.importantCount,
@@ -100,7 +100,8 @@ export const LayoutSidebarHeader = () => {
<DropdownMenuLabel className="mb-1">Workspaces</DropdownMenuLabel>
{workspaces.map((workspaceItem) => {
const workspaceState = radar.getWorkspaceState(
- workspaceItem.userId
+ workspaceItem.accountId,
+ workspaceItem.id
);
return (
<DropdownMenuItem
diff --git a/apps/desktop/src/renderer/components/layouts/layout-sidebar-spaces.tsx b/apps/desktop/src/renderer/components/layouts/layout-sidebar-spaces.tsx
index a986fca8..1d2c5baf 100644
--- a/apps/desktop/src/renderer/components/layouts/layout-sidebar-spaces.tsx
+++ b/apps/desktop/src/renderer/components/layouts/layout-sidebar-spaces.tsx
@@ -10,7 +10,8 @@ export const LayoutSidebarSpaces = () => {
const { data } = useQuery({
type: 'space_list',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
parentId: workspace.id,
page: 0,
count: 100,
diff --git a/apps/desktop/src/renderer/components/messages/message-actions.tsx b/apps/desktop/src/renderer/components/messages/message-actions.tsx
index d9e25794..1f2eb3a1 100644
--- a/apps/desktop/src/renderer/components/messages/message-actions.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-actions.tsx
@@ -47,7 +47,8 @@ export const MessageActions = ({ message }: MessageActionsProps) => {
input: {
type: 'message_reaction_create',
messageId: message.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
reaction,
rootId: conversation.rootId,
},
@@ -91,7 +92,8 @@ export const MessageActions = ({ message }: MessageActionsProps) => {
input: {
type: 'message_reaction_create',
messageId: message.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
reaction,
rootId: conversation.rootId,
},
diff --git a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
index 3b9e5a0f..3aa5a2de 100644
--- a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
@@ -15,8 +15,9 @@ export const MessageAuthorAvatar = ({
const workspace = useWorkspace();
const { data } = useQuery({
type: 'user_get',
- id: message.createdBy,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: message.createdBy,
});
if (!data) {
diff --git a/apps/desktop/src/renderer/components/messages/message-author-name.tsx b/apps/desktop/src/renderer/components/messages/message-author-name.tsx
index aef47ff0..1c70e921 100644
--- a/apps/desktop/src/renderer/components/messages/message-author-name.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-author-name.tsx
@@ -15,8 +15,9 @@ export const MessageAuthorName = ({
const workspace = useWorkspace();
const { data } = useQuery({
type: 'user_get',
- id: message.createdBy,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: message.createdBy,
});
if (!data) {
diff --git a/apps/desktop/src/renderer/components/messages/message-create.tsx b/apps/desktop/src/renderer/components/messages/message-create.tsx
index 0a3cdb15..b514b0cb 100644
--- a/apps/desktop/src/renderer/components/messages/message-create.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-create.tsx
@@ -68,7 +68,8 @@ export const MessageCreate = React.forwardRef<MessageCreateRefProps>(
type: 'message_create',
conversationId: conversation.id,
content: content,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
referenceId: replyTo?.id,
rootId: conversation.rootId,
},
@@ -175,7 +176,8 @@ export const MessageCreate = React.forwardRef<MessageCreateRefProps>(
<div className="max-h-72 flex-grow overflow-y-auto">
{conversation.canCreateMessage ? (
<MessageEditor
- userId={workspace.userId}
+ accountId={workspace.accountId}
+ workspaceId={workspace.id}
ref={messageEditorRef}
conversationId={conversation.id}
onChange={setContent}
diff --git a/apps/desktop/src/renderer/components/messages/message-delete-button.tsx b/apps/desktop/src/renderer/components/messages/message-delete-button.tsx
index 3e1e1c00..c6abf9aa 100644
--- a/apps/desktop/src/renderer/components/messages/message-delete-button.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-delete-button.tsx
@@ -51,7 +51,8 @@ export const MessageDeleteButton = ({ id }: MessageDeleteButtonProps) => {
input: {
type: 'message_delete',
messageId: id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
setShowDeleteModal(false);
diff --git a/apps/desktop/src/renderer/components/messages/message-editor.tsx b/apps/desktop/src/renderer/components/messages/message-editor.tsx
index 62bbf16f..ddffebfe 100644
--- a/apps/desktop/src/renderer/components/messages/message-editor.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-editor.tsx
@@ -29,7 +29,8 @@ import { EditorBubbleMenu } from '@/renderer/editor/menu/bubble-menu';
import { FileMetadata } from '@/shared/types/files';
interface MessageEditorProps {
- userId: string;
+ accountId: string;
+ workspaceId: string;
conversationId: string;
onChange?: (content: JSONContent) => void;
onSubmit: () => void;
@@ -69,7 +70,8 @@ export const MessageEditor = React.forwardRef<
LinkMark,
DropcursorExtension,
FilePlaceholderNode.configure({
- userId: props.userId,
+ accountId: props.accountId,
+ workspaceId: props.workspaceId,
}),
FileNode,
],
diff --git a/apps/desktop/src/renderer/components/messages/message-list.tsx b/apps/desktop/src/renderer/components/messages/message-list.tsx
index 93189201..b1d65053 100644
--- a/apps/desktop/src/renderer/components/messages/message-list.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-list.tsx
@@ -22,7 +22,8 @@ export const MessageList = () => {
}).map((_, i) => ({
type: 'message_list',
conversationId: conversation.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
page: i + 1,
count: MESSAGES_PER_PAGE,
}));
diff --git a/apps/desktop/src/renderer/components/messages/message-reactions.tsx b/apps/desktop/src/renderer/components/messages/message-reactions.tsx
index 352a2ca5..309eabd1 100644
--- a/apps/desktop/src/renderer/components/messages/message-reactions.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reactions.tsx
@@ -17,7 +17,8 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {
const { data } = useQuery({
type: 'message_reactions_get',
messageId: message.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const reactionCounts = data ?? [];
@@ -57,7 +58,8 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {
input: {
type: 'message_reaction_delete',
messageId: message.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
rootId: message.rootId,
reaction: reaction.reaction,
},
@@ -74,7 +76,8 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {
input: {
type: 'message_reaction_create',
messageId: message.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
rootId: message.rootId,
reaction: reaction.reaction,
},
diff --git a/apps/desktop/src/renderer/components/messages/message-reference.tsx b/apps/desktop/src/renderer/components/messages/message-reference.tsx
index 04a8c98a..d2d2db60 100644
--- a/apps/desktop/src/renderer/components/messages/message-reference.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reference.tsx
@@ -13,7 +13,8 @@ export const MessageReference = ({ messageId }: MessageReferenceProps) => {
const { data, isPending } = useQuery({
type: 'message_get',
messageId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
if (isPending) {
diff --git a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
index d2458022..31e2111c 100644
--- a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
@@ -16,8 +16,9 @@ export const MessageReplyBanner = ({
const workspace = useWorkspace();
const { data } = useQuery({
type: 'user_get',
- id: message.createdBy,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: message.createdBy,
});
if (!data) {
diff --git a/apps/desktop/src/renderer/components/messages/message.tsx b/apps/desktop/src/renderer/components/messages/message.tsx
index 43bf1c93..681d5413 100644
--- a/apps/desktop/src/renderer/components/messages/message.tsx
+++ b/apps/desktop/src/renderer/components/messages/message.tsx
@@ -61,7 +61,11 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
rootMargin="50px"
onChange={(inView) => {
if (inView) {
- radar.markMessageAsSeen(workspace.userId, message.id);
+ radar.markMessageAsSeen(
+ workspace.accountId,
+ workspace.id,
+ message.id
+ );
}
}}
>
diff --git a/apps/desktop/src/renderer/components/pages/page-body.tsx b/apps/desktop/src/renderer/components/pages/page-body.tsx
index 4a827998..483a246c 100644
--- a/apps/desktop/src/renderer/components/pages/page-body.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-body.tsx
@@ -25,7 +25,8 @@ export const PageBody = ({ page, role }: PageBodyProps) => {
mutate({
input: {
type: 'page_content_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
pageId: page.id,
before,
after,
@@ -43,10 +44,10 @@ export const PageBody = ({ page, role }: PageBodyProps) => {
);
useEffect(() => {
- radar.markEntryAsOpened(workspace.userId, page.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, page.id);
const interval = setInterval(() => {
- radar.markEntryAsOpened(workspace.userId, page.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, page.id);
}, 60000);
return () => clearInterval(interval);
diff --git a/apps/desktop/src/renderer/components/pages/page-container.tsx b/apps/desktop/src/renderer/components/pages/page-container.tsx
index 805f2666..cabe1b99 100644
--- a/apps/desktop/src/renderer/components/pages/page-container.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-container.tsx
@@ -16,7 +16,8 @@ export const PageContainer = ({ pageId }: PageContainerProps) => {
const { data: entry, isPending: isPendingEntry } = useQuery({
type: 'entry_get',
entryId: pageId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const page = entry as PageEntry;
@@ -26,7 +27,8 @@ export const PageContainer = ({ pageId }: PageContainerProps) => {
{
type: 'entry_get',
entryId: page?.rootId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: pageExists,
diff --git a/apps/desktop/src/renderer/components/pages/page-create-dialog.tsx b/apps/desktop/src/renderer/components/pages/page-create-dialog.tsx
index a60c2b49..b6de5dfa 100644
--- a/apps/desktop/src/renderer/components/pages/page-create-dialog.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-create-dialog.tsx
@@ -56,7 +56,8 @@ export const PageCreateDialog = ({
parentId: spaceId,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
generateIndex: true,
},
onSuccess(output) {
diff --git a/apps/desktop/src/renderer/components/pages/page-delete-dialog.tsx b/apps/desktop/src/renderer/components/pages/page-delete-dialog.tsx
index 69aa9997..3906fd11 100644
--- a/apps/desktop/src/renderer/components/pages/page-delete-dialog.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-delete-dialog.tsx
@@ -48,7 +48,8 @@ export const PageDeleteDialog = ({
input: {
type: 'page_delete',
pageId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx b/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
index ae93284a..5c4199dd 100644
--- a/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
@@ -59,7 +59,8 @@ export const PageUpdateDialog = ({
pageId: page.id,
name: values.name,
avatar: values.avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/records/record-avatar.tsx b/apps/desktop/src/renderer/components/records/record-avatar.tsx
index 840cdf4c..63ccf03a 100644
--- a/apps/desktop/src/renderer/components/records/record-avatar.tsx
+++ b/apps/desktop/src/renderer/components/records/record-avatar.tsx
@@ -36,7 +36,8 @@ export const RecordAvatar = () => {
type: 'record_avatar_update',
recordId: record.id,
avatar,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
diff --git a/apps/desktop/src/renderer/components/records/record-body.tsx b/apps/desktop/src/renderer/components/records/record-body.tsx
index dc1940da..ba4d09a7 100644
--- a/apps/desktop/src/renderer/components/records/record-body.tsx
+++ b/apps/desktop/src/renderer/components/records/record-body.tsx
@@ -37,7 +37,8 @@ export const RecordBody = ({ record, database, role }: RecordBodyProps) => {
mutate({
input: {
type: 'record_content_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
recordId: record.id,
before,
after,
@@ -55,10 +56,10 @@ export const RecordBody = ({ record, database, role }: RecordBodyProps) => {
);
useEffect(() => {
- radar.markEntryAsOpened(workspace.userId, record.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, record.id);
const interval = setInterval(() => {
- radar.markEntryAsOpened(workspace.userId, record.id);
+ radar.markEntryAsOpened(workspace.accountId, workspace.id, record.id);
}, 60000);
return () => clearInterval(interval);
diff --git a/apps/desktop/src/renderer/components/records/record-container.tsx b/apps/desktop/src/renderer/components/records/record-container.tsx
index 23685903..54d1f001 100644
--- a/apps/desktop/src/renderer/components/records/record-container.tsx
+++ b/apps/desktop/src/renderer/components/records/record-container.tsx
@@ -16,7 +16,8 @@ export const RecordContainer = ({ recordId }: RecordContainerProps) => {
const { data: entry, isPending: isPendingEntry } = useQuery({
type: 'entry_get',
entryId: recordId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
const record = entry as RecordEntry;
@@ -26,7 +27,8 @@ export const RecordContainer = ({ recordId }: RecordContainerProps) => {
{
type: 'entry_get',
entryId: record?.rootId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: recordExists,
@@ -37,7 +39,8 @@ export const RecordContainer = ({ recordId }: RecordContainerProps) => {
{
type: 'entry_get',
entryId: record?.attributes.databaseId ?? '',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
{
enabled: recordExists,
diff --git a/apps/desktop/src/renderer/components/records/record-delete-dialog.tsx b/apps/desktop/src/renderer/components/records/record-delete-dialog.tsx
index dafb5cd2..a15ebe25 100644
--- a/apps/desktop/src/renderer/components/records/record-delete-dialog.tsx
+++ b/apps/desktop/src/renderer/components/records/record-delete-dialog.tsx
@@ -48,7 +48,8 @@ export const RecordDeleteDialog = ({
input: {
type: 'record_delete',
recordId: entryId,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onSuccess() {
onOpenChange(false);
diff --git a/apps/desktop/src/renderer/components/records/record-name.tsx b/apps/desktop/src/renderer/components/records/record-name.tsx
index a19b276b..9d4e18a9 100644
--- a/apps/desktop/src/renderer/components/records/record-name.tsx
+++ b/apps/desktop/src/renderer/components/records/record-name.tsx
@@ -42,7 +42,8 @@ export const RecordName = () => {
type: 'record_name_update',
recordId: record.id,
name: value,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
diff --git a/apps/desktop/src/renderer/components/records/record-provider.tsx b/apps/desktop/src/renderer/components/records/record-provider.tsx
index ce11e2f9..61a56ad8 100644
--- a/apps/desktop/src/renderer/components/records/record-provider.tsx
+++ b/apps/desktop/src/renderer/components/records/record-provider.tsx
@@ -40,7 +40,8 @@ export const RecordProvider = ({
recordId: record.id,
fieldId: field.id,
value,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
@@ -57,7 +58,8 @@ export const RecordProvider = ({
type: 'record_field_value_delete',
recordId: record.id,
fieldId: field.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
},
onError(error) {
toast({
diff --git a/apps/desktop/src/renderer/components/records/record-search.tsx b/apps/desktop/src/renderer/components/records/record-search.tsx
index 12f9f056..84342597 100644
--- a/apps/desktop/src/renderer/components/records/record-search.tsx
+++ b/apps/desktop/src/renderer/components/records/record-search.tsx
@@ -30,7 +30,8 @@ export const RecordSearch = ({
const { data } = useQuery({
type: 'record_search',
searchQuery: query,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
exclude,
databaseId,
});
diff --git a/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx b/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
index 26b5a4f7..60b7098a 100644
--- a/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
@@ -48,8 +48,9 @@ export const RecordCollaboratorValue = ({
const results = useQueries(
collaboratorIds.map((id) => ({
type: 'user_get',
- id,
- userId: workspace.userId,
+ userId: id,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
}))
);
diff --git a/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx b/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx
index 29fa2b38..e1193bca 100644
--- a/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx
@@ -14,8 +14,9 @@ export const RecordCreatedByValue = ({ field }: RecordCreatedByValueProps) => {
const record = useRecord();
const { data } = useQuery({
type: 'user_get',
- id: record.createdBy,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: record.createdBy,
});
const createdBy = data
diff --git a/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx b/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx
index b18b4b40..6bcdfb08 100644
--- a/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx
@@ -50,7 +50,8 @@ export const RecordRelationValue = ({
relationIds.map((id) => ({
type: 'entry_get',
entryId: id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
}))
);
diff --git a/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx b/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx
index 0e662fc2..4c484dd7 100644
--- a/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx
@@ -17,8 +17,9 @@ export const RecordUpdatedByValue = ({ field }: RecordUpdatedByValueProps) => {
const { data } = useQuery(
{
type: 'user_get',
- id: record.updatedBy!,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: record.updatedBy!,
},
{
enabled: !!record.updatedBy,
diff --git a/apps/desktop/src/renderer/components/spaces/space-create-dialog.tsx b/apps/desktop/src/renderer/components/spaces/space-create-dialog.tsx
index 0ab42cc5..a0afe49f 100644
--- a/apps/desktop/src/renderer/components/spaces/space-create-dialog.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-create-dialog.tsx
@@ -70,7 +70,7 @@ export const SpaceCreateDialog = ({
type: 'space_create',
name: values.name,
description: values.description,
- userId: workspace.userId,
+ accountId: workspace.accountId,
workspaceId: workspace.id,
},
onSuccess() {
diff --git a/apps/desktop/src/renderer/components/spaces/space-delete-form.tsx b/apps/desktop/src/renderer/components/spaces/space-delete-form.tsx
index 868493b0..7442f4d5 100644
--- a/apps/desktop/src/renderer/components/spaces/space-delete-form.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-delete-form.tsx
@@ -30,7 +30,8 @@ export const SpaceDeleteForm = ({ id }: SpaceDeleteFormProps) => {
mutate({
input: {
type: 'space_delete',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
spaceId: id,
},
onSuccess() {
diff --git a/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx b/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx
index 99f02f2f..0f8556da 100644
--- a/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx
@@ -50,7 +50,8 @@ export const SpaceSidebarItem = ({ space }: SpaceSidebarItemProps) => {
const { data } = useQuery({
type: 'entry_children_get',
entryId: space.id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
types: ['page', 'channel', 'database', 'folder'],
});
diff --git a/apps/desktop/src/renderer/components/spaces/space-update-form.tsx b/apps/desktop/src/renderer/components/spaces/space-update-form.tsx
index 20ae5092..6ba70286 100644
--- a/apps/desktop/src/renderer/components/spaces/space-update-form.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-update-form.tsx
@@ -50,7 +50,8 @@ export const SpaceUpdateForm = ({ space }: SpaceUpdateFormProps) => {
updateSpace({
input: {
type: 'space_update',
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
id: space.id,
name: values.name,
description: values.description,
diff --git a/apps/desktop/src/renderer/components/users/user-search.tsx b/apps/desktop/src/renderer/components/users/user-search.tsx
index 532094c7..599688c1 100644
--- a/apps/desktop/src/renderer/components/users/user-search.tsx
+++ b/apps/desktop/src/renderer/components/users/user-search.tsx
@@ -25,7 +25,8 @@ export const UserSearch = ({ exclude, onSelect }: UserSearchProps) => {
const { data } = useQuery({
type: 'user_search',
searchQuery: query,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
exclude,
});
diff --git a/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx b/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx
index f2594f87..dbad9664 100644
--- a/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx
+++ b/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx
@@ -84,7 +84,8 @@ export const WorkspaceUserInvite = ({
input: {
type: 'users_invite',
emails: emails,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
role: 'collaborator',
},
onSuccess() {
diff --git a/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx b/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx
index d360baf4..ba320a6a 100644
--- a/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx
+++ b/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx
@@ -103,9 +103,10 @@ export const WorkspaceUserRoleDropdown = ({
mutate({
input: {
type: 'user_role_update',
- userToUpdateId: userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ userId: userId,
role: role.value,
- userId: workspace.userId,
},
onError(error) {
toast({
diff --git a/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx b/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx
index a9441f72..28e99400 100644
--- a/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx
+++ b/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx
@@ -24,7 +24,8 @@ export const WorkspaceUsers = () => {
type: 'user_list',
page: i + 1,
count: USERS_PER_PAGE,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
}));
const result = useQueries(inputs);
diff --git a/apps/desktop/src/renderer/contexts/radar.ts b/apps/desktop/src/renderer/contexts/radar.ts
index 1485ffec..bc5c11e3 100644
--- a/apps/desktop/src/renderer/contexts/radar.ts
+++ b/apps/desktop/src/renderer/contexts/radar.ts
@@ -9,14 +9,45 @@ import {
interface RadarContext {
getAccountState: (accountId: string) => AccountReadState;
- getWorkspaceState: (userId: string) => WorkspaceReadState;
- getChatState: (userId: string, entryId: string) => ChatReadState;
- getChannelState: (userId: string, entryIdId: string) => ChannelReadState;
- markMessageAsSeen: (userId: string, messageId: string) => void;
- markFileAsSeen: (userId: string, fileId: string) => void;
- markFileAsOpened: (userId: string, fileId: string) => void;
- markEntryAsSeen: (userId: string, entryId: string) => void;
- markEntryAsOpened: (userId: string, entryId: string) => void;
+ getWorkspaceState: (
+ accountId: string,
+ workspaceId: string
+ ) => WorkspaceReadState;
+ getChatState: (
+ accountId: string,
+ workspaceId: string,
+ entryId: string
+ ) => ChatReadState;
+ getChannelState: (
+ accountId: string,
+ workspaceId: string,
+ entryId: string
+ ) => ChannelReadState;
+ markMessageAsSeen: (
+ accountId: string,
+ workspaceId: string,
+ messageId: string
+ ) => void;
+ markFileAsSeen: (
+ accountId: string,
+ workspaceId: string,
+ fileId: string
+ ) => void;
+ markFileAsOpened: (
+ accountId: string,
+ workspaceId: string,
+ fileId: string
+ ) => void;
+ markEntryAsSeen: (
+ accountId: string,
+ workspaceId: string,
+ entryId: string
+ ) => void;
+ markEntryAsOpened: (
+ accountId: string,
+ workspaceId: string,
+ entryId: string
+ ) => void;
}
export const RadarContext = createContext<RadarContext>({} as RadarContext);
diff --git a/apps/desktop/src/renderer/editor/commands/file.tsx b/apps/desktop/src/renderer/editor/commands/file.tsx
index 32fd6181..57682fcf 100644
--- a/apps/desktop/src/renderer/editor/commands/file.tsx
+++ b/apps/desktop/src/renderer/editor/commands/file.tsx
@@ -32,11 +32,12 @@ export const FileCommand: EditorCommand = {
return;
}
- const { userId, documentId, rootId } = context;
+ const { accountId, workspaceId, documentId, rootId } = context;
const output = await window.colanode.executeMutation({
type: 'file_create',
filePath,
- userId,
+ accountId,
+ workspaceId,
parentId: documentId,
rootId,
entryId: documentId,
diff --git a/apps/desktop/src/renderer/editor/commands/folder.tsx b/apps/desktop/src/renderer/editor/commands/folder.tsx
index 0d33e549..630972d9 100644
--- a/apps/desktop/src/renderer/editor/commands/folder.tsx
+++ b/apps/desktop/src/renderer/editor/commands/folder.tsx
@@ -14,12 +14,13 @@ export const FolderCommand: EditorCommand = {
return;
}
- const { userId, documentId } = context;
+ const { accountId, workspaceId, documentId } = context;
const output = await window.colanode.executeMutation({
type: 'folder_create',
name: 'Untitled',
avatar: null,
- userId,
+ accountId,
+ workspaceId,
parentId: documentId,
generateIndex: false,
});
diff --git a/apps/desktop/src/renderer/editor/commands/page.tsx b/apps/desktop/src/renderer/editor/commands/page.tsx
index fa0af377..1b9ff8d6 100644
--- a/apps/desktop/src/renderer/editor/commands/page.tsx
+++ b/apps/desktop/src/renderer/editor/commands/page.tsx
@@ -14,11 +14,12 @@ export const PageCommand: EditorCommand = {
return;
}
- const { userId, documentId } = context;
+ const { accountId, workspaceId, documentId } = context;
const output = await window.colanode.executeMutation({
type: 'page_create',
name: 'Untitled',
- userId,
+ accountId,
+ workspaceId,
parentId: documentId,
generateIndex: false,
});
diff --git a/apps/desktop/src/renderer/editor/extensions/file-placeholder.tsx b/apps/desktop/src/renderer/editor/extensions/file-placeholder.tsx
index 663af3db..1fc594fa 100644
--- a/apps/desktop/src/renderer/editor/extensions/file-placeholder.tsx
+++ b/apps/desktop/src/renderer/editor/extensions/file-placeholder.tsx
@@ -16,7 +16,8 @@ declare module '@tiptap/core' {
}
interface FilePlaceholderOptions {
- userId: string;
+ accountId: string;
+ workspaceId: string;
}
export const FilePlaceholderNode = Node.create<FilePlaceholderOptions>({
@@ -98,7 +99,8 @@ export const FilePlaceholderNode = Node.create<FilePlaceholderOptions>({
type: 'file_save_temp',
name: file.name,
buffer,
- userId: options.userId,
+ accountId: options.accountId,
+ workspaceId: options.workspaceId,
});
if (!fileSaveResult.success) {
@@ -145,8 +147,6 @@ export const FilePlaceholderNode = Node.create<FilePlaceholderOptions>({
return false;
}
- console.log('files dropped', files);
-
(async () => {
for (const file of files) {
const buffer = await file.arrayBuffer();
@@ -154,7 +154,8 @@ export const FilePlaceholderNode = Node.create<FilePlaceholderOptions>({
type: 'file_save_temp',
name: file.name,
buffer,
- userId: options.userId,
+ accountId: options.accountId,
+ workspaceId: options.workspaceId,
});
if (!fileSaveResult.success) {
diff --git a/apps/desktop/src/renderer/editor/extensions/file.tsx b/apps/desktop/src/renderer/editor/extensions/file.tsx
index dc3fa49e..5e95700f 100644
--- a/apps/desktop/src/renderer/editor/extensions/file.tsx
+++ b/apps/desktop/src/renderer/editor/extensions/file.tsx
@@ -53,7 +53,8 @@ export const FileNode = Node.create<FileNodeOptions>({
entryId: options.context.documentId,
rootId: options.context.rootId,
filePath: path,
- userId: options.context.userId,
+ accountId: options.context.accountId,
+ workspaceId: options.context.workspaceId,
parentId: options.context.documentId,
});
@@ -110,7 +111,8 @@ export const FileNode = Node.create<FileNodeOptions>({
type: 'file_save_temp',
name: file.name,
buffer,
- userId: options.context.userId,
+ accountId: options.context.accountId,
+ workspaceId: options.context.workspaceId,
});
if (!fileSaveResult.success) {
@@ -148,7 +150,8 @@ export const FileNode = Node.create<FileNodeOptions>({
type: 'file_save_temp',
name: file.name,
buffer,
- userId: options.context.userId,
+ accountId: options.context.accountId,
+ workspaceId: options.context.workspaceId,
});
if (!fileSaveResult.success) {
diff --git a/apps/desktop/src/renderer/editor/views/folder.tsx b/apps/desktop/src/renderer/editor/views/folder.tsx
index dbf48667..64e3cd44 100644
--- a/apps/desktop/src/renderer/editor/views/folder.tsx
+++ b/apps/desktop/src/renderer/editor/views/folder.tsx
@@ -12,7 +12,8 @@ export const FolderNodeView = ({ node }: NodeViewProps) => {
const { data } = useQuery({
type: 'entry_get',
entryId: id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
if (!id) {
diff --git a/apps/desktop/src/renderer/editor/views/page.tsx b/apps/desktop/src/renderer/editor/views/page.tsx
index 862a1388..d459f8d1 100644
--- a/apps/desktop/src/renderer/editor/views/page.tsx
+++ b/apps/desktop/src/renderer/editor/views/page.tsx
@@ -12,7 +12,8 @@ export const PageNodeView = ({ node }: NodeViewProps) => {
const { data } = useQuery({
type: 'entry_get',
entryId: id,
- userId: workspace.userId,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
});
if (!id) {
diff --git a/apps/desktop/src/renderer/hooks/user-records-query.tsx b/apps/desktop/src/renderer/hooks/user-records-query.tsx
index f18d60c7..fa9a92f3 100644
--- a/apps/desktop/src/renderer/hooks/user-records-query.tsx
+++ b/apps/desktop/src/renderer/hooks/user-records-query.tsx
@@ -22,6 +22,8 @@ export const useRecordsQuery = (
length: lastPage,
}).map((_, i) => ({
type: 'record_list',
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
databaseId: database.id,
filters: filters,
sorts: sorts,
diff --git a/apps/desktop/src/renderer/radar-provider.tsx b/apps/desktop/src/renderer/radar-provider.tsx
index a8546dd9..5ce6fdc7 100644
--- a/apps/desktop/src/renderer/radar-provider.tsx
+++ b/apps/desktop/src/renderer/radar-provider.tsx
@@ -15,16 +15,20 @@ export const RadarProvider = ({ children }: RadarProviderProps) => {
<RadarContext.Provider
value={{
getAccountState: (accountId) => {
- const workspaceStates = Object.values(radarData).filter(
- (state) => state.accountId === accountId
- );
+ const accountState = radarData[accountId];
+ if (!accountState) {
+ return {
+ importantCount: 0,
+ hasUnseenChanges: false,
+ };
+ }
- const importantCount = workspaceStates.reduce(
+ const importantCount = Object.values(accountState).reduce(
(acc, state) => acc + state.importantCount,
0
);
- const hasUnseenChanges = workspaceStates.some(
+ const hasUnseenChanges = Object.values(accountState).some(
(state) => state.hasUnseenChanges
);
@@ -33,8 +37,8 @@ export const RadarProvider = ({ children }: RadarProviderProps) => {
hasUnseenChanges,
};
},
- getWorkspaceState: (userId) => {
- const workspaceState = radarData[userId];
+ getWorkspaceState: (accountId, workspaceId) => {
+ const workspaceState = radarData[accountId]?.[workspaceId];
if (workspaceState) {
return {
hasUnseenChanges: workspaceState.hasUnseenChanges,
@@ -48,8 +52,8 @@ export const RadarProvider = ({ children }: RadarProviderProps) => {
hasUnseenChanges: false,
};
},
- getChatState: (userId, entryId) => {
- const workspaceState = radarData[userId];
+ getChatState: (accountId, workspaceId, entryId) => {
+ const workspaceState = radarData[accountId]?.[workspaceId];
if (workspaceState) {
const chatState = workspaceState.nodeStates[entryId];
if (chatState && chatState.type === 'chat') {
@@ -64,8 +68,8 @@ export const RadarProvider = ({ children }: RadarProviderProps) => {
mentionsCount: 0,
};
},
- getChannelState: (userId, entryId) => {
- const workspaceState = radarData[userId];
+ getChannelState: (accountId, workspaceId, entryId) => {
+ const workspaceState = radarData[accountId]?.[workspaceId];
if (workspaceState) {
const channelState = workspaceState.nodeStates[entryId];
if (channelState && channelState.type === 'channel') {
@@ -80,39 +84,44 @@ export const RadarProvider = ({ children }: RadarProviderProps) => {
mentionsCount: 0,
};
},
- markMessageAsSeen: (userId, messageId) => {
+ markMessageAsSeen: (accountId, workspaceId, messageId) => {
window.colanode.executeMutation({
type: 'message_mark_seen',
messageId,
- userId,
+ accountId,
+ workspaceId,
});
},
- markFileAsSeen: (userId, fileId) => {
+ markFileAsSeen: (accountId, workspaceId, fileId) => {
window.colanode.executeMutation({
type: 'file_mark_seen',
fileId,
- userId,
+ accountId,
+ workspaceId,
});
},
- markFileAsOpened: (userId, fileId) => {
+ markFileAsOpened: (accountId, workspaceId, fileId) => {
window.colanode.executeMutation({
type: 'file_mark_opened',
fileId,
- userId,
+ accountId,
+ workspaceId,
});
},
- markEntryAsSeen: (userId, entryId) => {
+ markEntryAsSeen: (accountId, workspaceId, entryId) => {
window.colanode.executeMutation({
type: 'entry_mark_seen',
entryId,
- userId,
+ accountId,
+ workspaceId,
});
},
- markEntryAsOpened: (userId, entryId) => {
+ markEntryAsOpened: (accountId, workspaceId, entryId) => {
window.colanode.executeMutation({
type: 'entry_mark_opened',
entryId,
- userId,
+ accountId,
+ workspaceId,
});
},
}}
diff --git a/apps/desktop/src/shared/commands/file-open.ts b/apps/desktop/src/shared/commands/file-open.ts
index 0dc6598b..0b36e63f 100644
--- a/apps/desktop/src/shared/commands/file-open.ts
+++ b/apps/desktop/src/shared/commands/file-open.ts
@@ -1,6 +1,7 @@
export type FileOpenCommandInput = {
type: 'file_open';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileId: string;
extension: string;
};
diff --git a/apps/desktop/src/shared/commands/index.ts b/apps/desktop/src/shared/commands/index.ts
index 7978459e..f52cd732 100644
--- a/apps/desktop/src/shared/commands/index.ts
+++ b/apps/desktop/src/shared/commands/index.ts
@@ -2,3 +2,18 @@
export interface CommandMap {}
export type CommandInput = CommandMap[keyof CommandMap]['input'];
+
+export class CommandError extends Error {
+ constructor(
+ public code: CommandErrorCode,
+ message: string
+ ) {
+ super(message);
+ }
+}
+
+export enum CommandErrorCode {
+ Unknown = 'unknown',
+ AccountNotFound = 'account_not_found',
+ WorkspaceNotFound = 'workspace_not_found',
+}
diff --git a/apps/desktop/src/shared/lib/event-loop.ts b/apps/desktop/src/shared/lib/event-loop.ts
new file mode 100644
index 00000000..65d38470
--- /dev/null
+++ b/apps/desktop/src/shared/lib/event-loop.ts
@@ -0,0 +1,67 @@
+type EventLoopStatus = 'idle' | 'scheduled' | 'processing';
+
+export class EventLoop {
+ private readonly interval: number;
+ private readonly debounce: number;
+ private readonly callback: () => void;
+
+ private timeout: NodeJS.Timeout | null;
+ private status: EventLoopStatus = 'idle';
+ private triggered: boolean = false;
+
+ constructor(interval: number, debounce: number, callback: () => void) {
+ this.interval = interval;
+ this.debounce = debounce;
+
+ this.timeout = null;
+ this.callback = callback;
+ }
+
+ public start(): void {
+ if (this.status !== 'idle') {
+ return;
+ }
+
+ this.status = 'scheduled';
+ this.timeout = setTimeout(() => {
+ this.execute();
+ }, this.debounce);
+ }
+
+ public stop(): void {
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ this.timeout = null;
+ }
+
+ this.status = 'idle';
+ }
+
+ public trigger(): void {
+ if (this.status === 'processing') {
+ this.triggered = true;
+ return;
+ }
+
+ this.stop();
+ this.start();
+ }
+
+ private execute(): void {
+ if (this.status !== 'scheduled') {
+ return;
+ }
+
+ this.status = 'processing';
+
+ this.callback();
+
+ const timeout = this.triggered ? this.debounce : this.interval;
+ this.timeout = setTimeout(() => {
+ this.execute();
+ }, timeout);
+
+ this.status = 'scheduled';
+ this.triggered = false;
+ }
+}
diff --git a/apps/desktop/src/shared/lib/http-client.ts b/apps/desktop/src/shared/lib/http-client.ts
deleted file mode 100644
index f7a82675..00000000
--- a/apps/desktop/src/shared/lib/http-client.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import axios, {
- AxiosError,
- AxiosInstance,
- AxiosRequestConfig,
- AxiosResponse,
- isAxiosError,
-} from 'axios';
-
-import { serverService } from '@/main/services/server-service';
-import { BackoffCalculator } from '@/shared/lib/backoff-calculator';
-
-interface HttpClientRequestConfig extends AxiosRequestConfig {
- domain: string;
- token?: string | null;
-}
-
-class HttpClient {
- private readonly backoffs: Map<string, BackoffCalculator> = new Map();
-
- constructor() {}
-
- private async request<T>(
- method: 'get' | 'post' | 'put' | 'delete',
- path: string,
- config: HttpClientRequestConfig
- ): Promise<AxiosResponse<T>> {
- if (this.backoffs.has(config.domain)) {
- const backoff = this.backoffs.get(config.domain);
- if (!backoff?.canRetry()) {
- throw new Error(`Backoff in progress for key: ${config.domain}`);
- }
- }
-
- try {
- const axiosInstance = this.buildAxiosInstance(config);
- const response = await axiosInstance.request<T>({
- method,
- url: path,
- ...config,
- });
-
- // Reset backoff if successful
- if (this.backoffs.has(config.domain)) {
- this.backoffs.get(config.domain)?.reset();
- }
-
- return response;
- } catch (error) {
- // If error is related to server availability, increase backoff
- if (isAxiosError(error) && this.isServerError(error)) {
- if (!this.backoffs.has(config.domain)) {
- this.backoffs.set(config.domain, new BackoffCalculator());
- }
-
- const backoff = this.backoffs.get(config.domain);
- backoff?.increaseError();
- }
-
- throw error;
- }
- }
-
- private isServerError(error: AxiosError): boolean {
- if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
- return true;
- }
- const status = error.response?.status ?? 0;
- return status >= 500 && status < 600;
- }
-
- private buildAxiosInstance(config: HttpClientRequestConfig): AxiosInstance {
- const baseURL = serverService.buildApiBaseUrl(config.domain);
- const instance = axios.create({ baseURL });
-
- if (config.token) {
- instance.defaults.headers.common['Authorization'] =
- `Bearer ${config.token}`;
- }
-
- return instance;
- }
-
- public async get<T>(
- path: string,
- config: HttpClientRequestConfig
- ): Promise<AxiosResponse<T>> {
- return this.request<T>('get', path, config);
- }
-
- public async post<T>(
- path: string,
- data: unknown,
- config: HttpClientRequestConfig
- ): Promise<AxiosResponse<T>> {
- return this.request<T>('post', path, {
- ...config,
- data,
- });
- }
-
- public async put<T>(
- path: string,
- data: unknown,
- config: HttpClientRequestConfig
- ): Promise<AxiosResponse<T>> {
- return this.request<T>('put', path, {
- ...config,
- data,
- });
- }
-
- public async delete<T>(
- path: string,
- config: HttpClientRequestConfig
- ): Promise<AxiosResponse<T>> {
- return this.request<T>('delete', path, config);
- }
-}
-
-export const httpClient = new HttpClient();
diff --git a/apps/desktop/src/shared/mutations/channels/channel-create.ts b/apps/desktop/src/shared/mutations/channels/channel-create.ts
index 02e8ee60..f52f69f5 100644
--- a/apps/desktop/src/shared/mutations/channels/channel-create.ts
+++ b/apps/desktop/src/shared/mutations/channels/channel-create.ts
@@ -1,6 +1,7 @@
export type ChannelCreateMutationInput = {
type: 'channel_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
spaceId: string;
name: string;
avatar?: string | null;
diff --git a/apps/desktop/src/shared/mutations/channels/channel-delete.ts b/apps/desktop/src/shared/mutations/channels/channel-delete.ts
index 784a2388..99995882 100644
--- a/apps/desktop/src/shared/mutations/channels/channel-delete.ts
+++ b/apps/desktop/src/shared/mutations/channels/channel-delete.ts
@@ -1,6 +1,7 @@
export type ChannelDeleteMutationInput = {
type: 'channel_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
channelId: string;
};
diff --git a/apps/desktop/src/shared/mutations/channels/channel-update.ts b/apps/desktop/src/shared/mutations/channels/channel-update.ts
index 8e62c0fd..6fce3d33 100644
--- a/apps/desktop/src/shared/mutations/channels/channel-update.ts
+++ b/apps/desktop/src/shared/mutations/channels/channel-update.ts
@@ -1,6 +1,7 @@
export type ChannelUpdateMutationInput = {
type: 'channel_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
channelId: string;
name: string;
avatar?: string | null;
diff --git a/apps/desktop/src/shared/mutations/chats/chat-create.ts b/apps/desktop/src/shared/mutations/chats/chat-create.ts
index cbb7ae22..eea0119f 100644
--- a/apps/desktop/src/shared/mutations/chats/chat-create.ts
+++ b/apps/desktop/src/shared/mutations/chats/chat-create.ts
@@ -1,8 +1,8 @@
export type ChatCreateMutationInput = {
type: 'chat_create';
+ accountId: string;
workspaceId: string;
userId: string;
- otherUserId: string;
};
export type ChatCreateMutationOutput = {
diff --git a/apps/desktop/src/shared/mutations/databases/database-create.ts b/apps/desktop/src/shared/mutations/databases/database-create.ts
index 1ad5fdf1..2f8af8d3 100644
--- a/apps/desktop/src/shared/mutations/databases/database-create.ts
+++ b/apps/desktop/src/shared/mutations/databases/database-create.ts
@@ -1,6 +1,7 @@
export type DatabaseCreateMutationInput = {
type: 'database_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
spaceId: string;
name: string;
avatar?: string | null;
diff --git a/apps/desktop/src/shared/mutations/databases/database-delete.ts b/apps/desktop/src/shared/mutations/databases/database-delete.ts
index 8b33030c..91f4c0a0 100644
--- a/apps/desktop/src/shared/mutations/databases/database-delete.ts
+++ b/apps/desktop/src/shared/mutations/databases/database-delete.ts
@@ -1,6 +1,7 @@
export type DatabaseDeleteMutationInput = {
type: 'database_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
};
diff --git a/apps/desktop/src/shared/mutations/databases/database-update.ts b/apps/desktop/src/shared/mutations/databases/database-update.ts
index 58236f38..df3bc50a 100644
--- a/apps/desktop/src/shared/mutations/databases/database-update.ts
+++ b/apps/desktop/src/shared/mutations/databases/database-update.ts
@@ -1,6 +1,7 @@
export type DatabaseUpdateMutationInput = {
type: 'database_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
name: string;
avatar?: string | null;
diff --git a/apps/desktop/src/shared/mutations/databases/field-create.ts b/apps/desktop/src/shared/mutations/databases/field-create.ts
index 552ff415..80d8a1e7 100644
--- a/apps/desktop/src/shared/mutations/databases/field-create.ts
+++ b/apps/desktop/src/shared/mutations/databases/field-create.ts
@@ -2,11 +2,12 @@ import { FieldType } from '@colanode/core';
export type FieldCreateMutationInput = {
type: 'field_create';
+ accountId: string;
+ workspaceId: string;
databaseId: string;
name: string;
fieldType: FieldType;
relationDatabaseId?: string | null;
- userId: string;
};
export type FieldCreateMutationOutput = {
diff --git a/apps/desktop/src/shared/mutations/databases/field-delete.ts b/apps/desktop/src/shared/mutations/databases/field-delete.ts
index b0dc24a8..a93a6b5f 100644
--- a/apps/desktop/src/shared/mutations/databases/field-delete.ts
+++ b/apps/desktop/src/shared/mutations/databases/field-delete.ts
@@ -1,8 +1,9 @@
export type FieldDeleteMutationInput = {
type: 'field_delete';
+ accountId: string;
+ workspaceId: string;
databaseId: string;
fieldId: string;
- userId: string;
};
export type FieldDeleteMutationOutput = {
diff --git a/apps/desktop/src/shared/mutations/databases/field-name-update.ts b/apps/desktop/src/shared/mutations/databases/field-name-update.ts
index c72b5e9c..534b65e9 100644
--- a/apps/desktop/src/shared/mutations/databases/field-name-update.ts
+++ b/apps/desktop/src/shared/mutations/databases/field-name-update.ts
@@ -1,9 +1,10 @@
export type FieldNameUpdateMutationInput = {
type: 'field_name_update';
+ accountId: string;
+ workspaceId: string;
databaseId: string;
fieldId: string;
name: string;
- userId: string;
};
export type FieldNameUpdateMutationOutput = {
diff --git a/apps/desktop/src/shared/mutations/databases/select-option-create.ts b/apps/desktop/src/shared/mutations/databases/select-option-create.ts
index a2c58fc6..465417f3 100644
--- a/apps/desktop/src/shared/mutations/databases/select-option-create.ts
+++ b/apps/desktop/src/shared/mutations/databases/select-option-create.ts
@@ -1,6 +1,7 @@
export type SelectOptionCreateMutationInput = {
type: 'select_option_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
fieldId: string;
name: string;
diff --git a/apps/desktop/src/shared/mutations/databases/select-option-delete.ts b/apps/desktop/src/shared/mutations/databases/select-option-delete.ts
index 6147b07b..1983b675 100644
--- a/apps/desktop/src/shared/mutations/databases/select-option-delete.ts
+++ b/apps/desktop/src/shared/mutations/databases/select-option-delete.ts
@@ -1,6 +1,7 @@
export type SelectOptionDeleteMutationInput = {
type: 'select_option_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
fieldId: string;
optionId: string;
diff --git a/apps/desktop/src/shared/mutations/databases/select-option-update.ts b/apps/desktop/src/shared/mutations/databases/select-option-update.ts
index cb56422f..1fc0d792 100644
--- a/apps/desktop/src/shared/mutations/databases/select-option-update.ts
+++ b/apps/desktop/src/shared/mutations/databases/select-option-update.ts
@@ -1,6 +1,7 @@
export type SelectOptionUpdateMutationInput = {
type: 'select_option_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
fieldId: string;
optionId: string;
diff --git a/apps/desktop/src/shared/mutations/databases/view-create.ts b/apps/desktop/src/shared/mutations/databases/view-create.ts
index 0a6f548d..4e489f90 100644
--- a/apps/desktop/src/shared/mutations/databases/view-create.ts
+++ b/apps/desktop/src/shared/mutations/databases/view-create.ts
@@ -1,6 +1,7 @@
export type ViewCreateMutationInput = {
type: 'view_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
viewType: 'table' | 'board' | 'calendar';
name: string;
diff --git a/apps/desktop/src/shared/mutations/databases/view-delete.ts b/apps/desktop/src/shared/mutations/databases/view-delete.ts
index d257d9c4..542700fa 100644
--- a/apps/desktop/src/shared/mutations/databases/view-delete.ts
+++ b/apps/desktop/src/shared/mutations/databases/view-delete.ts
@@ -1,6 +1,7 @@
export type ViewDeleteMutationInput = {
type: 'view_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
viewId: string;
};
diff --git a/apps/desktop/src/shared/mutations/databases/view-name-update.ts b/apps/desktop/src/shared/mutations/databases/view-name-update.ts
index e3ac6d18..816e1823 100644
--- a/apps/desktop/src/shared/mutations/databases/view-name-update.ts
+++ b/apps/desktop/src/shared/mutations/databases/view-name-update.ts
@@ -1,9 +1,10 @@
export type ViewNameUpdateMutationInput = {
type: 'view_name_update';
+ accountId: string;
+ workspaceId: string;
databaseId: string;
viewId: string;
name: string;
- userId: string;
};
export type ViewNameUpdateMutationOutput = {
diff --git a/apps/desktop/src/shared/mutations/databases/view-update.ts b/apps/desktop/src/shared/mutations/databases/view-update.ts
index 75b07240..15e391f8 100644
--- a/apps/desktop/src/shared/mutations/databases/view-update.ts
+++ b/apps/desktop/src/shared/mutations/databases/view-update.ts
@@ -2,7 +2,8 @@ import { ViewAttributes } from '@colanode/core';
export type ViewUpdateMutationInput = {
type: 'view_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
view: ViewAttributes;
};
diff --git a/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.ts
index 11282a87..05282a3c 100644
--- a/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.ts
+++ b/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.ts
@@ -1,6 +1,7 @@
export type EntryCollaboratorCreateMutationInput = {
type: 'entry_collaborator_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryId: string;
collaboratorIds: string[];
role: string;
diff --git a/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.ts
index 2ce36c86..92cd1cbc 100644
--- a/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.ts
+++ b/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.ts
@@ -1,6 +1,7 @@
export type EntryCollaboratorDeleteMutationInput = {
type: 'entry_collaborator_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryId: string;
collaboratorId: string;
};
diff --git a/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.ts
index 3607d438..6cb6caa1 100644
--- a/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.ts
+++ b/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.ts
@@ -1,6 +1,7 @@
export type EntryCollaboratorUpdateMutationInput = {
type: 'entry_collaborator_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryId: string;
collaboratorId: string;
role: string;
diff --git a/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts b/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts
index 0da4d82a..13991542 100644
--- a/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts
+++ b/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts
@@ -1,6 +1,7 @@
export type EntryMarkOpenedMutationInput = {
type: 'entry_mark_opened';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryId: string;
};
diff --git a/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts b/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts
index 361b576a..60a467b0 100644
--- a/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts
+++ b/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts
@@ -1,6 +1,7 @@
export type EntryMarkSeenMutationInput = {
type: 'entry_mark_seen';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryId: string;
};
diff --git a/apps/desktop/src/shared/mutations/files/file-create.ts b/apps/desktop/src/shared/mutations/files/file-create.ts
index 8eedf386..9e070c5b 100644
--- a/apps/desktop/src/shared/mutations/files/file-create.ts
+++ b/apps/desktop/src/shared/mutations/files/file-create.ts
@@ -1,6 +1,7 @@
export type FileCreateMutationInput = {
type: 'file_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
parentId: string;
entryId: string;
rootId: string;
diff --git a/apps/desktop/src/shared/mutations/files/file-delete.ts b/apps/desktop/src/shared/mutations/files/file-delete.ts
index 1c03cda7..bbcde2ab 100644
--- a/apps/desktop/src/shared/mutations/files/file-delete.ts
+++ b/apps/desktop/src/shared/mutations/files/file-delete.ts
@@ -1,6 +1,7 @@
export type FileDeleteMutationInput = {
type: 'file_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileId: string;
};
diff --git a/apps/desktop/src/shared/mutations/files/file-download.ts b/apps/desktop/src/shared/mutations/files/file-download.ts
index 0e89cf65..60b2221b 100644
--- a/apps/desktop/src/shared/mutations/files/file-download.ts
+++ b/apps/desktop/src/shared/mutations/files/file-download.ts
@@ -1,6 +1,7 @@
export type FileDownloadMutationInput = {
type: 'file_download';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileId: string;
};
diff --git a/apps/desktop/src/shared/mutations/files/file-mark-opened.ts b/apps/desktop/src/shared/mutations/files/file-mark-opened.ts
index c8ae6eb1..57e6e25d 100644
--- a/apps/desktop/src/shared/mutations/files/file-mark-opened.ts
+++ b/apps/desktop/src/shared/mutations/files/file-mark-opened.ts
@@ -1,6 +1,7 @@
export type FileMarkOpenedMutationInput = {
type: 'file_mark_opened';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileId: string;
};
diff --git a/apps/desktop/src/shared/mutations/files/file-mark-seen.ts b/apps/desktop/src/shared/mutations/files/file-mark-seen.ts
index 31a7ab80..530b4288 100644
--- a/apps/desktop/src/shared/mutations/files/file-mark-seen.ts
+++ b/apps/desktop/src/shared/mutations/files/file-mark-seen.ts
@@ -1,6 +1,7 @@
export type FileMarkSeenMutationInput = {
type: 'file_mark_seen';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileId: string;
};
diff --git a/apps/desktop/src/shared/mutations/files/file-save-temp.ts b/apps/desktop/src/shared/mutations/files/file-save-temp.ts
index 9a270c56..1928e759 100644
--- a/apps/desktop/src/shared/mutations/files/file-save-temp.ts
+++ b/apps/desktop/src/shared/mutations/files/file-save-temp.ts
@@ -1,6 +1,7 @@
export type FileSaveTempMutationInput = {
type: 'file_save_temp';
- userId: string;
+ accountId: string;
+ workspaceId: string;
name: string;
buffer: ArrayBuffer;
};
diff --git a/apps/desktop/src/shared/mutations/folders/folder-create.ts b/apps/desktop/src/shared/mutations/folders/folder-create.ts
index 582c0408..02d4fcf8 100644
--- a/apps/desktop/src/shared/mutations/folders/folder-create.ts
+++ b/apps/desktop/src/shared/mutations/folders/folder-create.ts
@@ -1,6 +1,7 @@
export type FolderCreateMutationInput = {
type: 'folder_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
parentId: string;
name: string;
avatar?: string | null;
diff --git a/apps/desktop/src/shared/mutations/folders/folder-delete.ts b/apps/desktop/src/shared/mutations/folders/folder-delete.ts
index 4b22245e..5d7f1bd5 100644
--- a/apps/desktop/src/shared/mutations/folders/folder-delete.ts
+++ b/apps/desktop/src/shared/mutations/folders/folder-delete.ts
@@ -1,6 +1,7 @@
export type FolderDeleteMutationInput = {
type: 'folder_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
folderId: string;
};
diff --git a/apps/desktop/src/shared/mutations/folders/folder-update.ts b/apps/desktop/src/shared/mutations/folders/folder-update.ts
index 250a215e..b82791f7 100644
--- a/apps/desktop/src/shared/mutations/folders/folder-update.ts
+++ b/apps/desktop/src/shared/mutations/folders/folder-update.ts
@@ -1,6 +1,7 @@
export type FolderUpdateMutationInput = {
type: 'folder_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
folderId: string;
name: string;
avatar?: string | null;
diff --git a/apps/desktop/src/shared/mutations/messages/message-create.ts b/apps/desktop/src/shared/mutations/messages/message-create.ts
index 4bc5b8d3..d822da3d 100644
--- a/apps/desktop/src/shared/mutations/messages/message-create.ts
+++ b/apps/desktop/src/shared/mutations/messages/message-create.ts
@@ -2,7 +2,8 @@ import { JSONContent } from '@tiptap/core';
export type MessageCreateMutationInput = {
type: 'message_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
conversationId: string;
rootId: string;
content: JSONContent;
diff --git a/apps/desktop/src/shared/mutations/messages/message-delete.ts b/apps/desktop/src/shared/mutations/messages/message-delete.ts
index 428578ce..2e962b73 100644
--- a/apps/desktop/src/shared/mutations/messages/message-delete.ts
+++ b/apps/desktop/src/shared/mutations/messages/message-delete.ts
@@ -1,6 +1,7 @@
export type MessageDeleteMutationInput = {
type: 'message_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
messageId: string;
};
diff --git a/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts b/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts
index 9baac3d0..35394992 100644
--- a/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts
+++ b/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts
@@ -1,6 +1,7 @@
export type MessageMarkSeenMutationInput = {
type: 'message_mark_seen';
- userId: string;
+ accountId: string;
+ workspaceId: string;
messageId: string;
};
diff --git a/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts b/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts
index 6c341708..aac06ffc 100644
--- a/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts
+++ b/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts
@@ -1,6 +1,7 @@
export type MessageReactionCreateMutationInput = {
type: 'message_reaction_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
messageId: string;
rootId: string;
reaction: string;
diff --git a/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts b/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts
index 51dbdc22..9b40b336 100644
--- a/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts
+++ b/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts
@@ -1,6 +1,7 @@
export type MessageReactionDeleteMutationInput = {
type: 'message_reaction_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
messageId: string;
rootId: string;
reaction: string;
diff --git a/apps/desktop/src/shared/mutations/pages/page-content-update.ts b/apps/desktop/src/shared/mutations/pages/page-content-update.ts
index 609f766c..6fbbe508 100644
--- a/apps/desktop/src/shared/mutations/pages/page-content-update.ts
+++ b/apps/desktop/src/shared/mutations/pages/page-content-update.ts
@@ -2,7 +2,8 @@ import { JSONContent } from '@tiptap/core';
export type PageContentUpdateMutationInput = {
type: 'page_content_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
pageId: string;
before: JSONContent;
after: JSONContent;
diff --git a/apps/desktop/src/shared/mutations/pages/page-create.ts b/apps/desktop/src/shared/mutations/pages/page-create.ts
index ae7e871a..e50dcf6e 100644
--- a/apps/desktop/src/shared/mutations/pages/page-create.ts
+++ b/apps/desktop/src/shared/mutations/pages/page-create.ts
@@ -1,6 +1,7 @@
export type PageCreateMutationInput = {
type: 'page_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
parentId: string;
avatar?: string | null;
name: string;
diff --git a/apps/desktop/src/shared/mutations/pages/page-delete.ts b/apps/desktop/src/shared/mutations/pages/page-delete.ts
index 7da4e8ac..a6181197 100644
--- a/apps/desktop/src/shared/mutations/pages/page-delete.ts
+++ b/apps/desktop/src/shared/mutations/pages/page-delete.ts
@@ -1,6 +1,7 @@
export type PageDeleteMutationInput = {
type: 'page_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
pageId: string;
};
diff --git a/apps/desktop/src/shared/mutations/pages/page-update.ts b/apps/desktop/src/shared/mutations/pages/page-update.ts
index 49c90009..39a7bfac 100644
--- a/apps/desktop/src/shared/mutations/pages/page-update.ts
+++ b/apps/desktop/src/shared/mutations/pages/page-update.ts
@@ -1,6 +1,7 @@
export type PageUpdateMutationInput = {
type: 'page_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
pageId: string;
avatar?: string | null;
name: string;
diff --git a/apps/desktop/src/shared/mutations/records/record-avatar-update.ts b/apps/desktop/src/shared/mutations/records/record-avatar-update.ts
index 5163bcc1..4ffd03ac 100644
--- a/apps/desktop/src/shared/mutations/records/record-avatar-update.ts
+++ b/apps/desktop/src/shared/mutations/records/record-avatar-update.ts
@@ -1,6 +1,7 @@
export type RecordAvatarUpdateMutationInput = {
type: 'record_avatar_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
recordId: string;
avatar: string;
};
diff --git a/apps/desktop/src/shared/mutations/records/record-content-update.ts b/apps/desktop/src/shared/mutations/records/record-content-update.ts
index aa1d8116..5587d115 100644
--- a/apps/desktop/src/shared/mutations/records/record-content-update.ts
+++ b/apps/desktop/src/shared/mutations/records/record-content-update.ts
@@ -2,7 +2,8 @@ import { JSONContent } from '@tiptap/core';
export type RecordContentUpdateMutationInput = {
type: 'record_content_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
recordId: string;
before: JSONContent;
after: JSONContent;
diff --git a/apps/desktop/src/shared/mutations/records/record-create.ts b/apps/desktop/src/shared/mutations/records/record-create.ts
index 749cc4d5..d2c99dd2 100644
--- a/apps/desktop/src/shared/mutations/records/record-create.ts
+++ b/apps/desktop/src/shared/mutations/records/record-create.ts
@@ -2,7 +2,8 @@ import { FieldValue } from '@colanode/core';
export type RecordCreateMutationInput = {
type: 'record_create';
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
name?: string;
fields?: Record<string, FieldValue>;
diff --git a/apps/desktop/src/shared/mutations/records/record-delete.ts b/apps/desktop/src/shared/mutations/records/record-delete.ts
index d53d599a..cb1cd512 100644
--- a/apps/desktop/src/shared/mutations/records/record-delete.ts
+++ b/apps/desktop/src/shared/mutations/records/record-delete.ts
@@ -1,6 +1,7 @@
export type RecordDeleteMutationInput = {
type: 'record_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
recordId: string;
};
diff --git a/apps/desktop/src/shared/mutations/records/record-field-value-delete.ts b/apps/desktop/src/shared/mutations/records/record-field-value-delete.ts
index af34f08e..f0278629 100644
--- a/apps/desktop/src/shared/mutations/records/record-field-value-delete.ts
+++ b/apps/desktop/src/shared/mutations/records/record-field-value-delete.ts
@@ -1,6 +1,7 @@
export type RecordFieldValueDeleteMutationInput = {
type: 'record_field_value_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
recordId: string;
fieldId: string;
};
diff --git a/apps/desktop/src/shared/mutations/records/record-field-value-set.ts b/apps/desktop/src/shared/mutations/records/record-field-value-set.ts
index 3ac350f7..0aa67b46 100644
--- a/apps/desktop/src/shared/mutations/records/record-field-value-set.ts
+++ b/apps/desktop/src/shared/mutations/records/record-field-value-set.ts
@@ -2,7 +2,8 @@ import { FieldValue } from '@colanode/core';
export type RecordFieldValueSetMutationInput = {
type: 'record_field_value_set';
- userId: string;
+ accountId: string;
+ workspaceId: string;
recordId: string;
fieldId: string;
value: FieldValue;
diff --git a/apps/desktop/src/shared/mutations/records/record-name-update.ts b/apps/desktop/src/shared/mutations/records/record-name-update.ts
index 242fa168..1c843c89 100644
--- a/apps/desktop/src/shared/mutations/records/record-name-update.ts
+++ b/apps/desktop/src/shared/mutations/records/record-name-update.ts
@@ -1,6 +1,7 @@
export type RecordNameUpdateMutationInput = {
type: 'record_name_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
recordId: string;
name: string;
};
diff --git a/apps/desktop/src/shared/mutations/spaces/space-create.ts b/apps/desktop/src/shared/mutations/spaces/space-create.ts
index 40ccee11..4795d5cf 100644
--- a/apps/desktop/src/shared/mutations/spaces/space-create.ts
+++ b/apps/desktop/src/shared/mutations/spaces/space-create.ts
@@ -1,6 +1,6 @@
export type SpaceCreateMutationInput = {
type: 'space_create';
- userId: string;
+ accountId: string;
workspaceId: string;
name: string;
description: string;
diff --git a/apps/desktop/src/shared/mutations/spaces/space-delete.ts b/apps/desktop/src/shared/mutations/spaces/space-delete.ts
index 7d69ebff..9f0d012f 100644
--- a/apps/desktop/src/shared/mutations/spaces/space-delete.ts
+++ b/apps/desktop/src/shared/mutations/spaces/space-delete.ts
@@ -1,6 +1,7 @@
export type SpaceDeleteMutationInput = {
type: 'space_delete';
- userId: string;
+ accountId: string;
+ workspaceId: string;
spaceId: string;
};
diff --git a/apps/desktop/src/shared/mutations/spaces/space-update.ts b/apps/desktop/src/shared/mutations/spaces/space-update.ts
index f33a2b49..1dbff337 100644
--- a/apps/desktop/src/shared/mutations/spaces/space-update.ts
+++ b/apps/desktop/src/shared/mutations/spaces/space-update.ts
@@ -1,6 +1,7 @@
export type SpaceUpdateMutationInput = {
type: 'space_update';
- userId: string;
+ accountId: string;
+ workspaceId: string;
id: string;
name: string;
description: string;
diff --git a/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts b/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
index 949ce9aa..8407d43b 100644
--- a/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
+++ b/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
@@ -1,8 +1,9 @@
export type UserRoleUpdateMutationInput = {
type: 'user_role_update';
- userToUpdateId: string;
- role: string;
+ accountId: string;
+ workspaceId: string;
userId: string;
+ role: string;
};
export type UserRoleUpdateMutationOutput = {
diff --git a/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts b/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts
index e2e3df35..9a33f2dc 100644
--- a/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts
+++ b/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts
@@ -2,8 +2,9 @@ import { WorkspaceRole } from '@colanode/core';
export type UsersInviteMutationInput = {
type: 'users_invite';
+ accountId: string;
+ workspaceId: string;
emails: string[];
- userId: string;
role: WorkspaceRole;
};
diff --git a/apps/desktop/src/shared/queries/chats/chat-list.ts b/apps/desktop/src/shared/queries/chats/chat-list.ts
index 56ff2712..a9030076 100644
--- a/apps/desktop/src/shared/queries/chats/chat-list.ts
+++ b/apps/desktop/src/shared/queries/chats/chat-list.ts
@@ -4,7 +4,8 @@ export type ChatListQueryInput = {
type: 'chat_list';
page: number;
count: number;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/databases/database-list.ts b/apps/desktop/src/shared/queries/databases/database-list.ts
index 8fa52701..a88346a1 100644
--- a/apps/desktop/src/shared/queries/databases/database-list.ts
+++ b/apps/desktop/src/shared/queries/databases/database-list.ts
@@ -2,7 +2,8 @@ import { DatabaseEntry } from '@colanode/core';
export type DatabaseListQueryInput = {
type: 'database_list';
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/entries/entry-children-get.ts b/apps/desktop/src/shared/queries/entries/entry-children-get.ts
index e778772c..34549459 100644
--- a/apps/desktop/src/shared/queries/entries/entry-children-get.ts
+++ b/apps/desktop/src/shared/queries/entries/entry-children-get.ts
@@ -3,7 +3,8 @@ import { Entry, EntryType } from '@colanode/core';
export type EntryChildrenGetQueryInput = {
type: 'entry_children_get';
entryId: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
types?: EntryType[];
};
diff --git a/apps/desktop/src/shared/queries/entries/entry-get.ts b/apps/desktop/src/shared/queries/entries/entry-get.ts
index d0c26e63..933a880f 100644
--- a/apps/desktop/src/shared/queries/entries/entry-get.ts
+++ b/apps/desktop/src/shared/queries/entries/entry-get.ts
@@ -3,7 +3,8 @@ import { Entry } from '@colanode/core';
export type EntryGetQueryInput = {
type: 'entry_get';
entryId: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/entries/entry-tree-get.ts b/apps/desktop/src/shared/queries/entries/entry-tree-get.ts
index 54817115..f11b6889 100644
--- a/apps/desktop/src/shared/queries/entries/entry-tree-get.ts
+++ b/apps/desktop/src/shared/queries/entries/entry-tree-get.ts
@@ -3,7 +3,8 @@ import { Entry } from '@colanode/core';
export type EntryTreeGetQueryInput = {
type: 'entry_tree_get';
entryId: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/files/file-get.ts b/apps/desktop/src/shared/queries/files/file-get.ts
index e5b9243e..46220bb2 100644
--- a/apps/desktop/src/shared/queries/files/file-get.ts
+++ b/apps/desktop/src/shared/queries/files/file-get.ts
@@ -3,7 +3,8 @@ import { FileWithState } from '@/shared/types/files';
export type FileGetQueryInput = {
type: 'file_get';
id: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/files/file-list.ts b/apps/desktop/src/shared/queries/files/file-list.ts
index 80a4da32..b33533bc 100644
--- a/apps/desktop/src/shared/queries/files/file-list.ts
+++ b/apps/desktop/src/shared/queries/files/file-list.ts
@@ -5,7 +5,8 @@ export type FileListQueryInput = {
parentId: string;
page: number;
count: number;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/index.ts b/apps/desktop/src/shared/queries/index.ts
index c7c88a78..cadd1a0a 100644
--- a/apps/desktop/src/shared/queries/index.ts
+++ b/apps/desktop/src/shared/queries/index.ts
@@ -2,3 +2,18 @@
export interface QueryMap {}
export type QueryInput = QueryMap[keyof QueryMap]['input'];
+
+export class QueryError extends Error {
+ constructor(
+ public code: QueryErrorCode,
+ message: string
+ ) {
+ super(message);
+ }
+}
+
+export enum QueryErrorCode {
+ Unknown = 'unknown',
+ AccountNotFound = 'account_not_found',
+ WorkspaceNotFound = 'workspace_not_found',
+}
diff --git a/apps/desktop/src/shared/queries/interactions/radar-data-get.ts b/apps/desktop/src/shared/queries/interactions/radar-data-get.ts
index 25ccf6ee..d1652b9f 100644
--- a/apps/desktop/src/shared/queries/interactions/radar-data-get.ts
+++ b/apps/desktop/src/shared/queries/interactions/radar-data-get.ts
@@ -4,11 +4,16 @@ export type RadarDataGetQueryInput = {
type: 'radar_data_get';
};
+export type RadarDataGetQueryOutput = Record<
+ string,
+ Record<string, WorkspaceRadarData>
+>;
+
declare module '@/shared/queries' {
interface QueryMap {
radar_data_get: {
input: RadarDataGetQueryInput;
- output: Record<string, WorkspaceRadarData>;
+ output: RadarDataGetQueryOutput;
};
}
}
diff --git a/apps/desktop/src/shared/queries/messages/message-get.ts b/apps/desktop/src/shared/queries/messages/message-get.ts
index 0f7a6ea7..6f1907c7 100644
--- a/apps/desktop/src/shared/queries/messages/message-get.ts
+++ b/apps/desktop/src/shared/queries/messages/message-get.ts
@@ -3,7 +3,8 @@ import { MessageNode } from '@/shared/types/messages';
export type MessageGetQueryInput = {
type: 'message_get';
messageId: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/messages/message-list.ts b/apps/desktop/src/shared/queries/messages/message-list.ts
index 7eac8c77..901ad758 100644
--- a/apps/desktop/src/shared/queries/messages/message-list.ts
+++ b/apps/desktop/src/shared/queries/messages/message-list.ts
@@ -5,7 +5,8 @@ export type MessageListQueryInput = {
conversationId: string;
page: number;
count: number;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/messages/message-reactions-get.ts b/apps/desktop/src/shared/queries/messages/message-reactions-get.ts
index a49cc1bd..c8ff6367 100644
--- a/apps/desktop/src/shared/queries/messages/message-reactions-get.ts
+++ b/apps/desktop/src/shared/queries/messages/message-reactions-get.ts
@@ -3,7 +3,8 @@ import { MessageReactionsCount } from '@/shared/types/messages';
export type MessageReactionsGetQueryInput = {
type: 'message_reactions_get';
messageId: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/records/record-list.ts b/apps/desktop/src/shared/queries/records/record-list.ts
index c4b6d7ce..f854ff1a 100644
--- a/apps/desktop/src/shared/queries/records/record-list.ts
+++ b/apps/desktop/src/shared/queries/records/record-list.ts
@@ -11,7 +11,8 @@ export type RecordListQueryInput = {
sorts: ViewSortAttributes[];
page: number;
count: number;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/records/record-search.ts b/apps/desktop/src/shared/queries/records/record-search.ts
index ea4696df..d660bef4 100644
--- a/apps/desktop/src/shared/queries/records/record-search.ts
+++ b/apps/desktop/src/shared/queries/records/record-search.ts
@@ -3,7 +3,8 @@ import { RecordEntry } from '@colanode/core';
export type RecordSearchQueryInput = {
type: 'record_search';
searchQuery: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
databaseId: string;
exclude?: string[];
};
diff --git a/apps/desktop/src/shared/queries/spaces/space-list.ts b/apps/desktop/src/shared/queries/spaces/space-list.ts
index 4825c04f..c00d1406 100644
--- a/apps/desktop/src/shared/queries/spaces/space-list.ts
+++ b/apps/desktop/src/shared/queries/spaces/space-list.ts
@@ -4,7 +4,8 @@ export type SpaceListQueryInput = {
type: 'space_list';
page: number;
count: number;
- userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/users/user-get.ts b/apps/desktop/src/shared/queries/users/user-get.ts
index a196dd21..6ed82e0a 100644
--- a/apps/desktop/src/shared/queries/users/user-get.ts
+++ b/apps/desktop/src/shared/queries/users/user-get.ts
@@ -2,8 +2,9 @@ import { User } from '@/shared/types/users';
export type UserGetQueryInput = {
type: 'user_get';
- id: string;
userId: string;
+ accountId: string;
+ workspaceId: string;
};
declare module '@/shared/queries' {
diff --git a/apps/desktop/src/shared/queries/users/user-list.ts b/apps/desktop/src/shared/queries/users/user-list.ts
index 4125b843..1aad5104 100644
--- a/apps/desktop/src/shared/queries/users/user-list.ts
+++ b/apps/desktop/src/shared/queries/users/user-list.ts
@@ -2,7 +2,8 @@ import { User } from '@/shared/types/users';
export type UserListQueryInput = {
type: 'user_list';
- userId: string;
+ accountId: string;
+ workspaceId: string;
page: number;
count: number;
};
diff --git a/apps/desktop/src/shared/queries/users/user-search.ts b/apps/desktop/src/shared/queries/users/user-search.ts
index 87d1bfb6..75792b91 100644
--- a/apps/desktop/src/shared/queries/users/user-search.ts
+++ b/apps/desktop/src/shared/queries/users/user-search.ts
@@ -3,7 +3,8 @@ import { User } from '@/shared/types/users';
export type UserSearchQueryInput = {
type: 'user_search';
searchQuery: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
exclude?: string[];
};
diff --git a/apps/desktop/src/shared/types/editor.ts b/apps/desktop/src/shared/types/editor.ts
index dc25f47e..46a6535c 100644
--- a/apps/desktop/src/shared/types/editor.ts
+++ b/apps/desktop/src/shared/types/editor.ts
@@ -9,7 +9,8 @@ export type EditorCommandProps = {
export type EditorContext = {
documentId: string;
- userId: string;
+ accountId: string;
+ workspaceId: string;
rootId: string;
};
diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.ts
index 2bf7c04d..20065460 100644
--- a/apps/desktop/src/shared/types/events.ts
+++ b/apps/desktop/src/shared/types/events.ts
@@ -14,121 +14,141 @@ import { File, FileInteraction, FileState } from '@/shared/types/files';
export type UserCreatedEvent = {
type: 'user_created';
- userId: string;
+ accountId: string;
+ workspaceId: string;
user: User;
};
export type UserUpdatedEvent = {
type: 'user_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
user: User;
};
export type UserDeletedEvent = {
type: 'user_deleted';
- userId: string;
+ accountId: string;
+ workspaceId: string;
user: User;
};
export type EntryCreatedEvent = {
type: 'entry_created';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entry: Entry;
};
export type EntryUpdatedEvent = {
type: 'entry_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entry: Entry;
};
export type EntryDeletedEvent = {
type: 'entry_deleted';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entry: Entry;
};
export type EntryInteractionUpdatedEvent = {
type: 'entry_interaction_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryInteraction: EntryInteraction;
};
export type MessageCreatedEvent = {
type: 'message_created';
- userId: string;
+ accountId: string;
+ workspaceId: string;
message: MessageNode;
};
export type MessageUpdatedEvent = {
type: 'message_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
message: MessageNode;
};
export type MessageDeletedEvent = {
type: 'message_deleted';
- userId: string;
+ accountId: string;
+ workspaceId: string;
message: MessageNode;
};
export type MessageReactionCreatedEvent = {
type: 'message_reaction_created';
- userId: string;
+ accountId: string;
+ workspaceId: string;
messageReaction: MessageReaction;
};
export type MessageReactionDeletedEvent = {
type: 'message_reaction_deleted';
- userId: string;
+ accountId: string;
+ workspaceId: string;
messageReaction: MessageReaction;
};
export type MessageInteractionUpdatedEvent = {
type: 'message_interaction_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
messageInteraction: MessageInteraction;
};
export type FileCreatedEvent = {
type: 'file_created';
- userId: string;
+ accountId: string;
+ workspaceId: string;
file: File;
};
export type FileUpdatedEvent = {
type: 'file_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
file: File;
};
export type FileDeletedEvent = {
type: 'file_deleted';
- userId: string;
+ accountId: string;
+ workspaceId: string;
file: File;
};
export type FileStateCreatedEvent = {
type: 'file_state_created';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileState: FileState;
};
export type FileStateUpdatedEvent = {
type: 'file_state_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileState: FileState;
};
export type FileStateDeletedEvent = {
type: 'file_state_deleted';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileState: FileState;
};
export type FileInteractionUpdatedEvent = {
type: 'file_interaction_updated';
- userId: string;
+ accountId: string;
+ workspaceId: string;
fileInteraction: FileInteraction;
};
@@ -182,20 +202,17 @@ export type RadarDataUpdatedEvent = {
type: 'radar_data_updated';
};
-export type MutationCreatedEvent = {
- type: 'mutation_created';
- userId: string;
-};
-
export type CollaborationCreatedEvent = {
type: 'collaboration_created';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryId: string;
};
export type CollaborationDeletedEvent = {
type: 'collaboration_deleted';
- userId: string;
+ accountId: string;
+ workspaceId: string;
entryId: string;
};
@@ -205,11 +222,6 @@ export type ServerAvailabilityChangedEvent = {
isAvailable: boolean;
};
-export type SocketConnectionOpenedEvent = {
- type: 'socket_connection_opened';
- accountId: string;
-};
-
export type Event =
| UserCreatedEvent
| UserUpdatedEvent
@@ -241,8 +253,6 @@ export type Event =
| FileInteractionUpdatedEvent
| QueryResultUpdatedEvent
| RadarDataUpdatedEvent
- | MutationCreatedEvent
| ServerAvailabilityChangedEvent
- | SocketConnectionOpenedEvent
| CollaborationCreatedEvent
| CollaborationDeletedEvent;
diff --git a/apps/desktop/src/shared/types/workspaces.ts b/apps/desktop/src/shared/types/workspaces.ts
index 444d10ab..5d546faa 100644
--- a/apps/desktop/src/shared/types/workspaces.ts
+++ b/apps/desktop/src/shared/types/workspaces.ts
@@ -9,12 +9,3 @@ export type Workspace = {
role: WorkspaceRole;
userId: string;
};
-
-export type WorkspaceCredentials = {
- workspaceId: string;
- accountId: string;
- userId: string;
- token: string;
- serverDomain: string;
- serverAttributes: string;
-};
diff --git a/apps/server/tsup.config.ts b/apps/server/tsup.config.ts
index e70bacb0..732c4e0d 100644
--- a/apps/server/tsup.config.ts
+++ b/apps/server/tsup.config.ts
@@ -17,8 +17,6 @@ const copyTemplates = async () => {
await fs.copyFile(path.join(srcDir, file), path.join(destDir, file));
}
-
- console.log('Templates copied to dist/templates');
};
export default defineConfig({
diff --git a/package-lock.json b/package-lock.json
index 9031296a..cf7ee78d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -15,7 +15,8 @@
],
"dependencies": {
"debug": "^4.3.7",
- "lodash-es": "^4.17.21"
+ "lodash-es": "^4.17.21",
+ "ms": "^2.1.3"
},
"devDependencies": {
"@types/debug": "^4.1.12",
diff --git a/package.json b/package.json
index 482ad456..7d6111eb 100644
--- a/package.json
+++ b/package.json
@@ -41,6 +41,7 @@
},
"dependencies": {
"debug": "^4.3.7",
- "lodash-es": "^4.17.21"
+ "lodash-es": "^4.17.21",
+ "ms": "^2.1.3"
}
}
diff --git a/packages/core/src/types/sockets.ts b/packages/core/src/types/sockets.ts
index a018b684..caac34d0 100644
--- a/packages/core/src/types/sockets.ts
+++ b/packages/core/src/types/sockets.ts
@@ -2,8 +2,8 @@ import { SynchronizerInput, SynchronizerMap } from '../synchronizers';
export type SynchronizerInputMessage = {
type: 'synchronizer_input';
- userId: string;
id: string;
+ userId: string;
input: SynchronizerInput;
cursor: string;
};