mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-02-14 21:27:20 +00:00
Merge remote-tracking branch 'refs/remotes/origin/feat/cloud-sync-saika'
Conflicts: package.json packages/data-center/src/datacenter.ts packages/data-center/src/provider/base.ts pnpm-lock.yaml
This commit is contained in:
@@ -1,241 +1,331 @@
|
||||
import { Workspaces } from './workspaces';
|
||||
import type { WorkspacesChangeEvent } from './workspaces';
|
||||
import { Workspace } from '@blocksuite/store';
|
||||
import { BaseProvider } from './provider/base';
|
||||
import { LocalProvider } from './provider/local/local';
|
||||
import { AffineProvider } from './provider';
|
||||
import assert from 'assert';
|
||||
import { getLogger } from './logger';
|
||||
import { BlockSchema } from '@blocksuite/blocks/models';
|
||||
import { Workspace, Signal } from '@blocksuite/store';
|
||||
|
||||
import { getLogger } from './index.js';
|
||||
import { getApis, Apis } from './apis/index.js';
|
||||
import {
|
||||
AffineProvider,
|
||||
BaseProvider,
|
||||
LocalProvider,
|
||||
SelfHostedProvider,
|
||||
} from './provider/index.js';
|
||||
|
||||
import { getKVConfigure } from './store.js';
|
||||
import { TauriIPCProvider } from './provider/tauri-ipc/index.js';
|
||||
|
||||
// load workspace's config
|
||||
type LoadConfig = {
|
||||
// use witch provider load data
|
||||
providerId?: string;
|
||||
// provider config
|
||||
config?: Record<string, any>;
|
||||
};
|
||||
|
||||
export type DataCenterSignals = DataCenter['signals'];
|
||||
type WorkspaceItem = {
|
||||
// provider id
|
||||
provider: string;
|
||||
// data exists locally
|
||||
locally: boolean;
|
||||
};
|
||||
type WorkspaceLoadEvent = WorkspaceItem & {
|
||||
workspace: string;
|
||||
};
|
||||
import { applyUpdate, encodeStateAsUpdate } from 'yjs';
|
||||
import { SelfHostedProvider } from './provider/selfhosted';
|
||||
import { TauriIPCProvider } from './provider/tauri-ipc';
|
||||
import { WorkspaceMeta } from './types';
|
||||
|
||||
/**
|
||||
* @class DataCenter
|
||||
* @classdesc DataCenter is a data center, it can manage different providers for business
|
||||
*/
|
||||
export class DataCenter {
|
||||
private readonly _apis: Apis;
|
||||
private readonly _providers = new Map<string, typeof BaseProvider>();
|
||||
private readonly _workspaces = new Map<string, Promise<BaseProvider>>();
|
||||
private readonly _config;
|
||||
private readonly _logger;
|
||||
private readonly _workspaces = new Workspaces();
|
||||
private readonly _logger = getLogger('dc');
|
||||
/**
|
||||
* A mainProvider must exist as the only data trustworthy source.
|
||||
*/
|
||||
private _mainProvider?: BaseProvider;
|
||||
providerMap: Map<string, BaseProvider> = new Map();
|
||||
|
||||
readonly signals = {
|
||||
listAdd: new Signal<WorkspaceLoadEvent>(),
|
||||
listRemove: new Signal<string>(),
|
||||
};
|
||||
constructor(debug: boolean) {
|
||||
this._logger.enabled = debug;
|
||||
}
|
||||
|
||||
static async init(debug: boolean): Promise<DataCenter> {
|
||||
const dc = new DataCenter(debug);
|
||||
dc.addProvider(AffineProvider);
|
||||
dc.addProvider(LocalProvider);
|
||||
// use ipc provider when client app's preload script inject the global flag.
|
||||
// TODO: switch different provider
|
||||
dc.registerProvider(
|
||||
new LocalProvider({
|
||||
logger: dc._logger,
|
||||
workspaces: dc._workspaces.createScope(),
|
||||
})
|
||||
);
|
||||
dc.registerProvider(
|
||||
new AffineProvider({
|
||||
logger: dc._logger,
|
||||
workspaces: dc._workspaces.createScope(),
|
||||
})
|
||||
);
|
||||
dc.registerProvider(
|
||||
new SelfHostedProvider({
|
||||
logger: dc._logger,
|
||||
workspaces: dc._workspaces.createScope(),
|
||||
})
|
||||
);
|
||||
if (typeof window !== 'undefined' && window.CLIENT_APP) {
|
||||
dc.addProvider(TauriIPCProvider);
|
||||
dc.registerProvider(
|
||||
new TauriIPCProvider({
|
||||
logger: dc._logger,
|
||||
workspaces: dc._workspaces.createScope(),
|
||||
})
|
||||
);
|
||||
}
|
||||
dc.addProvider(SelfHostedProvider);
|
||||
|
||||
return dc;
|
||||
}
|
||||
|
||||
private constructor(debug: boolean) {
|
||||
this._apis = getApis();
|
||||
this._config = getKVConfigure('sys');
|
||||
this._logger = getLogger('dc');
|
||||
this._logger.enabled = debug;
|
||||
|
||||
this.signals.listAdd.on(e => {
|
||||
this._config.set(`list:${e.workspace}`, {
|
||||
provider: e.provider,
|
||||
locally: e.locally,
|
||||
});
|
||||
});
|
||||
this.signals.listRemove.on(workspace => {
|
||||
this._config.delete(`list:${workspace}`);
|
||||
});
|
||||
}
|
||||
|
||||
get apis(): Readonly<Apis> {
|
||||
return this._apis;
|
||||
}
|
||||
|
||||
private addProvider(provider: typeof BaseProvider) {
|
||||
this._providers.set(provider.id, provider);
|
||||
}
|
||||
|
||||
private async _getProvider(
|
||||
id: string,
|
||||
providerId = 'local'
|
||||
): Promise<string> {
|
||||
const providerKey = `${id}:provider`;
|
||||
if (this._providers.has(providerId)) {
|
||||
await this._config.set(providerKey, providerId);
|
||||
return providerId;
|
||||
} else {
|
||||
const providerValue = await this._config.get(providerKey);
|
||||
if (providerValue) return providerValue;
|
||||
/**
|
||||
* Register provider.
|
||||
* We will automatically set the first provider to default provider.
|
||||
*/
|
||||
registerProvider(provider: BaseProvider) {
|
||||
if (!this._mainProvider) {
|
||||
this._mainProvider = provider;
|
||||
}
|
||||
throw Error(`Provider ${providerId} not found`);
|
||||
|
||||
provider.init();
|
||||
this.providerMap.set(provider.id, provider);
|
||||
}
|
||||
|
||||
private async _getWorkspace(
|
||||
id: string,
|
||||
params: LoadConfig
|
||||
): Promise<BaseProvider> {
|
||||
this._logger(`Init workspace ${id} with ${params.providerId}`);
|
||||
|
||||
const providerId = await this._getProvider(id, params.providerId);
|
||||
|
||||
// init workspace & register block schema
|
||||
const workspace = new Workspace({ room: id }).register(BlockSchema);
|
||||
|
||||
const Provider = this._providers.get(providerId);
|
||||
assert(Provider);
|
||||
|
||||
// initial configurator
|
||||
const config = getKVConfigure(`workspace:${id}`);
|
||||
// set workspace configs
|
||||
const values = Object.entries(params.config || {});
|
||||
if (values.length) await config.setMany(values);
|
||||
|
||||
// init data by provider
|
||||
const provider = new Provider();
|
||||
await provider.init({
|
||||
apis: this._apis,
|
||||
config,
|
||||
debug: this._logger.enabled,
|
||||
logger: this._logger.extend(`${Provider.id}:${id}`),
|
||||
signals: this.signals,
|
||||
workspace,
|
||||
});
|
||||
await provider.initData();
|
||||
this._logger(`Workspace ${id} loaded`);
|
||||
|
||||
return provider;
|
||||
setMainProvider(providerId: string) {
|
||||
this._mainProvider = this.providerMap.get(providerId);
|
||||
}
|
||||
|
||||
async auth(providerId: string, globalConfig?: Record<string, any>) {
|
||||
const Provider = this._providers.get(providerId);
|
||||
if (Provider) {
|
||||
// initial configurator
|
||||
const config = getKVConfigure(`provider:${providerId}`);
|
||||
// set workspace configs
|
||||
const values = Object.entries(globalConfig || {});
|
||||
if (values.length) await config.setMany(values);
|
||||
get providers() {
|
||||
return Array.from(this.providerMap.values());
|
||||
}
|
||||
|
||||
const logger = this._logger.extend(`auth:${providerId}`);
|
||||
logger.enabled = this._logger.enabled;
|
||||
await Provider.auth(config, logger, this.signals);
|
||||
}
|
||||
public get workspaces() {
|
||||
return this._workspaces.workspaces;
|
||||
}
|
||||
|
||||
public async refreshWorkspaces() {
|
||||
return Promise.allSettled(
|
||||
Object.values(this.providerMap).map(provider => provider.loadWorkspaces())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* load workspace data to memory
|
||||
* @param workspaceId workspace id
|
||||
* @param config.providerId provider id
|
||||
* @param config.config provider config
|
||||
* @returns Workspace instance
|
||||
* create new workspace , new workspace is a local workspace
|
||||
* @param {string} name workspace name
|
||||
* @returns {Promise<WS>}
|
||||
*/
|
||||
async load(
|
||||
workspaceId: string,
|
||||
params: LoadConfig = {}
|
||||
): Promise<Workspace | null> {
|
||||
if (workspaceId) {
|
||||
if (!this._workspaces.has(workspaceId)) {
|
||||
this._workspaces.set(
|
||||
workspaceId,
|
||||
this._getWorkspace(workspaceId, params)
|
||||
);
|
||||
}
|
||||
const workspace = this._workspaces.get(workspaceId);
|
||||
assert(workspace);
|
||||
return workspace.then(w => w.workspace);
|
||||
}
|
||||
return null;
|
||||
public async createWorkspace(workspaceMeta: WorkspaceMeta) {
|
||||
assert(
|
||||
this._mainProvider,
|
||||
'There is no provider. You should add provider first.'
|
||||
);
|
||||
|
||||
const workspace = await this._mainProvider.createWorkspace(workspaceMeta);
|
||||
return workspace;
|
||||
}
|
||||
|
||||
/**
|
||||
* destroy workspace's instance in memory
|
||||
* @param workspaceId workspace id
|
||||
* delete workspace by id
|
||||
* @param {string} workspaceId workspace id
|
||||
*/
|
||||
async destroy(workspaceId: string) {
|
||||
const provider = await this._workspaces.get(workspaceId);
|
||||
public async deleteWorkspace(workspaceId: string) {
|
||||
const workspaceInfo = this._workspaces.find(workspaceId);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
const provider = this.providerMap.get(workspaceInfo.provider);
|
||||
assert(provider, `Workspace exists, but we couldn't find its provider.`);
|
||||
await provider.deleteWorkspace(workspaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* get a new workspace only has room id
|
||||
* @param {string} workspaceId workspace id
|
||||
*/
|
||||
private _getWorkspace(workspaceId: string) {
|
||||
return new Workspace({
|
||||
room: workspaceId,
|
||||
}).register(BlockSchema);
|
||||
}
|
||||
|
||||
/**
|
||||
* login to all providers, it will default run all auth ,
|
||||
* maybe need a params to control which provider to auth
|
||||
*/
|
||||
public async login() {
|
||||
this.providers.forEach(p => {
|
||||
// TODO: may be add params of auth
|
||||
p.auth();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* logout from all providers
|
||||
*/
|
||||
public async logout() {
|
||||
this.providers.forEach(p => {
|
||||
p.logout();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* load workspace instance by id
|
||||
* @param {string} workspaceId workspace id
|
||||
* @returns {Promise<Workspace>}
|
||||
*/
|
||||
public async loadWorkspace(workspaceId: string) {
|
||||
const workspaceInfo = this._workspaces.find(workspaceId);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
const currentProvider = this.providerMap.get(workspaceInfo.provider);
|
||||
if (currentProvider) {
|
||||
currentProvider.closeWorkspace(workspaceId);
|
||||
}
|
||||
const provider = this.providerMap.get(workspaceInfo.provider);
|
||||
assert(provider, `provide '${workspaceInfo.provider}' is not registered`);
|
||||
this._logger(`Loading ${workspaceInfo.provider} workspace: `, workspaceId);
|
||||
|
||||
return await provider.warpWorkspace(this._getWorkspace(workspaceId));
|
||||
}
|
||||
|
||||
/**
|
||||
* get user info by provider id
|
||||
* @param {string} providerId the provider name of workspace
|
||||
* @returns {Promise<User>}
|
||||
*/
|
||||
public async getUserInfo(providerId = 'affine') {
|
||||
// XXX: maybe return all user info
|
||||
const provider = this.providerMap.get(providerId);
|
||||
assert(provider, `provide '${providerId}' is not registered`);
|
||||
return provider.getUserInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* listen workspaces list change
|
||||
* @param {Function} callback callback function
|
||||
*/
|
||||
public async onWorkspacesChange(
|
||||
callback: (workspaces: WorkspacesChangeEvent) => void
|
||||
) {
|
||||
this._workspaces.on('change', callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* change workspaces meta
|
||||
* @param {WorkspaceMeta} workspaceMeta workspace meta
|
||||
* @param {Workspace} workspace workspace instance
|
||||
*/
|
||||
public async resetWorkspaceMeta(
|
||||
{ name, avatar }: WorkspaceMeta,
|
||||
workspace: Workspace
|
||||
) {
|
||||
assert(workspace?.room, 'No workspace to set meta');
|
||||
const update: Partial<WorkspaceMeta> = {};
|
||||
if (name) {
|
||||
workspace.doc.meta.setName(name);
|
||||
update.name = name;
|
||||
}
|
||||
if (avatar) {
|
||||
workspace.doc.meta.setAvatar(avatar);
|
||||
update.avatar = avatar;
|
||||
}
|
||||
// may run for change workspace meta
|
||||
const workspaceInfo = this._workspaces.find(workspace.room);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
const provider = this.providerMap.get(workspaceInfo.provider);
|
||||
provider?.updateWorkspaceMeta(workspace.room, update);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* leave workspace by id
|
||||
* @param id workspace id
|
||||
*/
|
||||
public async leaveWorkspace(workspaceId: string) {
|
||||
const workspaceInfo = this._workspaces.find(workspaceId);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
const provider = this.providerMap.get(workspaceInfo.provider);
|
||||
if (provider) {
|
||||
this._workspaces.delete(workspaceId);
|
||||
await provider.destroy();
|
||||
await provider.closeWorkspace(workspaceId);
|
||||
await provider.leaveWorkspace(workspaceId);
|
||||
}
|
||||
}
|
||||
|
||||
public async setWorkspacePublish(workspaceId: string, isPublish: boolean) {
|
||||
const workspaceInfo = this._workspaces.find(workspaceId);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
const provider = this.providerMap.get(workspaceInfo.provider);
|
||||
if (provider) {
|
||||
await provider.publish(workspaceId, isPublish);
|
||||
}
|
||||
}
|
||||
|
||||
public async inviteMember(id: string, email: string) {
|
||||
const workspaceInfo = this._workspaces.find(id);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
const provider = this.providerMap.get(workspaceInfo.provider);
|
||||
if (provider) {
|
||||
await provider.invite(id, email);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* reload new workspace instance to memory to refresh config
|
||||
* @param workspaceId workspace id
|
||||
* @param config.providerId provider id
|
||||
* @param config.config provider config
|
||||
* @returns Workspace instance
|
||||
* remove the new member to the workspace
|
||||
* @param {number} permissionId permission id
|
||||
*/
|
||||
async reload(
|
||||
workspaceId: string,
|
||||
config: LoadConfig = {}
|
||||
): Promise<Workspace | null> {
|
||||
await this.destroy(workspaceId);
|
||||
return this.load(workspaceId, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* get workspace list,return a map of workspace id and data state
|
||||
* data state is also map, the key is the provider id, and the data exists locally when the value is true, otherwise it does not exist
|
||||
*/
|
||||
async list(): Promise<Record<string, Record<string, boolean>>> {
|
||||
const entries: [string, WorkspaceItem][] = await this._config.entries();
|
||||
return entries.reduce((acc, [k, i]) => {
|
||||
if (k.startsWith('list:')) {
|
||||
const key = k.slice(5);
|
||||
acc[key] = acc[key] || {};
|
||||
acc[key][i.provider] = i.locally;
|
||||
}
|
||||
return acc;
|
||||
}, {} as Record<string, Record<string, boolean>>);
|
||||
}
|
||||
|
||||
/**
|
||||
* delete local workspace's data
|
||||
* @param workspaceId workspace id
|
||||
*/
|
||||
async delete(workspaceId: string) {
|
||||
await this._config.delete(`${workspaceId}:provider`);
|
||||
const provider = await this._workspaces.get(workspaceId);
|
||||
public async removeMember(workspaceId: string, permissionId: number) {
|
||||
const workspaceInfo = this._workspaces.find(workspaceId);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
const provider = this.providerMap.get(workspaceInfo.provider);
|
||||
if (provider) {
|
||||
this._workspaces.delete(workspaceId);
|
||||
// clear workspace data implement by provider
|
||||
await provider.removeMember(permissionId);
|
||||
}
|
||||
}
|
||||
|
||||
private async _transWorkspaceProvider(
|
||||
workspace: Workspace,
|
||||
providerId: string
|
||||
) {
|
||||
assert(workspace.room, 'No workspace id');
|
||||
const workspaceInfo = this._workspaces.find(workspace.room);
|
||||
assert(workspaceInfo, 'Workspace not found');
|
||||
if (workspaceInfo.provider === providerId) {
|
||||
this._logger('Workspace provider is same');
|
||||
return;
|
||||
}
|
||||
const currentProvider = this.providerMap.get(workspaceInfo.provider);
|
||||
assert(currentProvider, 'Provider not found');
|
||||
const newProvider = this.providerMap.get(providerId);
|
||||
assert(newProvider, `provide '${providerId}' is not registered`);
|
||||
this._logger(`create ${providerId} workspace: `, workspaceInfo.name);
|
||||
const newWorkspace = await newProvider.createWorkspace({
|
||||
name: workspaceInfo.name,
|
||||
avatar: workspaceInfo.avatar,
|
||||
});
|
||||
assert(newWorkspace, 'Create workspace failed');
|
||||
this._logger(
|
||||
`update workspace data from ${workspaceInfo.provider} to ${providerId}`
|
||||
);
|
||||
applyUpdate(newWorkspace.doc, encodeStateAsUpdate(workspace.doc));
|
||||
assert(newWorkspace, 'Create workspace failed');
|
||||
await currentProvider.deleteWorkspace(workspace.room);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable workspace cloud
|
||||
* @param {string} id ID of workspace.
|
||||
*/
|
||||
public async enableWorkspaceCloud(workspace: Workspace) {
|
||||
assert(workspace?.room, 'No workspace to enable cloud');
|
||||
return await this._transWorkspaceProvider(workspace, 'affine');
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* clear all workspaces and data
|
||||
*/
|
||||
public async clear() {
|
||||
for (const provider of this.providerMap.values()) {
|
||||
await provider.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* clear all local workspace's data
|
||||
* Select a file to import the workspace
|
||||
* @param {File} file file of workspace.
|
||||
*/
|
||||
async clear() {
|
||||
const workspaces = await this.list();
|
||||
await Promise.all(Object.keys(workspaces).map(id => this.delete(id)));
|
||||
public async importWorkspace(file: File) {
|
||||
file;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a file ,and export it to local file system
|
||||
* @param {string} id ID of workspace.
|
||||
*/
|
||||
public async exportWorkspace(id: string) {
|
||||
id;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import debug from 'debug';
|
||||
import { DataCenter } from './datacenter.js';
|
||||
import { DataCenter } from './datacenter';
|
||||
|
||||
const _initializeDataCenter = () => {
|
||||
let _dataCenterInstance: Promise<DataCenter>;
|
||||
@@ -26,11 +25,6 @@ const _initializeDataCenter = () => {
|
||||
|
||||
export const getDataCenter = _initializeDataCenter();
|
||||
|
||||
export function getLogger(namespace: string) {
|
||||
const logger = debug(namespace);
|
||||
logger.log = console.log.bind(console);
|
||||
return logger;
|
||||
}
|
||||
|
||||
export type { AccessTokenMessage, Member, Workspace } from './apis';
|
||||
export { WorkspaceType } from './apis/index.js';
|
||||
export type { AccessTokenMessage } from './provider/affine/apis';
|
||||
export type { Workspace } from './types';
|
||||
export { getLogger } from './logger';
|
||||
|
||||
7
packages/data-center/src/logger.ts
Normal file
7
packages/data-center/src/logger.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import debug from 'debug';
|
||||
|
||||
export function getLogger(namespace: string) {
|
||||
const logger = debug(namespace);
|
||||
logger.log = console.log.bind(console);
|
||||
return logger;
|
||||
}
|
||||
280
packages/data-center/src/provider/affine/affine.ts
Normal file
280
packages/data-center/src/provider/affine/affine.ts
Normal file
@@ -0,0 +1,280 @@
|
||||
import {
|
||||
getWorkspaces,
|
||||
getWorkspaceDetail,
|
||||
WorkspaceDetail,
|
||||
downloadWorkspace,
|
||||
deleteWorkspace,
|
||||
leaveWorkspace,
|
||||
inviteMember,
|
||||
removeMember,
|
||||
createWorkspace,
|
||||
updateWorkspace,
|
||||
} from './apis/workspace';
|
||||
import { BaseProvider } from '../base';
|
||||
import type { ProviderConstructorParams } from '../base';
|
||||
import { User, Workspace as WS, WorkspaceMeta } from '../../types';
|
||||
import { Workspace } from '@blocksuite/store';
|
||||
import { BlockSchema } from '@blocksuite/blocks/models';
|
||||
import { applyUpdate } from 'yjs';
|
||||
import { token, Callback } from './apis';
|
||||
import { varStorage as storage } from 'lib0/storage';
|
||||
import assert from 'assert';
|
||||
import { getAuthorizer } from './apis/token';
|
||||
import { WebsocketProvider } from './sync';
|
||||
import { IndexedDBProvider } from '../indexeddb';
|
||||
import { getDefaultHeadImgBlob } from '../../utils';
|
||||
|
||||
export class AffineProvider extends BaseProvider {
|
||||
public id = 'affine';
|
||||
private _workspacesCache: Map<string, Workspace> = new Map();
|
||||
private _onTokenRefresh?: Callback = undefined;
|
||||
private readonly _authorizer = getAuthorizer();
|
||||
private _user: User | undefined = undefined;
|
||||
private _wsMap: Map<string, WebsocketProvider> = new Map();
|
||||
private _idbMap: Map<string, IndexedDBProvider> = new Map();
|
||||
|
||||
constructor(params: ProviderConstructorParams) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
override async init() {
|
||||
this._onTokenRefresh = () => {
|
||||
if (token.refresh) {
|
||||
storage.setItem('token', token.refresh);
|
||||
}
|
||||
};
|
||||
|
||||
token.onChange(this._onTokenRefresh);
|
||||
|
||||
// initial login token
|
||||
if (token.isExpired) {
|
||||
try {
|
||||
const refreshToken = storage.getItem('token');
|
||||
await token.refreshToken(refreshToken);
|
||||
|
||||
if (token.refresh) {
|
||||
storage.set('token', token.refresh);
|
||||
}
|
||||
|
||||
assert(token.isLogin);
|
||||
} catch (_) {
|
||||
// this._logger('Authorization failed, fallback to local mode');
|
||||
}
|
||||
} else {
|
||||
storage.setItem('token', token.refresh);
|
||||
}
|
||||
}
|
||||
|
||||
override async warpWorkspace(workspace: Workspace) {
|
||||
const { doc, room } = workspace;
|
||||
assert(room);
|
||||
this._initWorkspaceDb(workspace);
|
||||
const updates = await downloadWorkspace(room);
|
||||
if (updates) {
|
||||
await new Promise(resolve => {
|
||||
doc.once('update', resolve);
|
||||
applyUpdate(doc, new Uint8Array(updates));
|
||||
});
|
||||
}
|
||||
const ws = new WebsocketProvider('/', room, doc);
|
||||
this._wsMap.set(room, ws);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
// TODO: synced will also be triggered on reconnection after losing sync
|
||||
// There needs to be an event mechanism to emit the synchronization state to the upper layer
|
||||
assert(ws);
|
||||
ws.once('synced', () => resolve());
|
||||
ws.once('lost-connection', () => resolve());
|
||||
ws.once('connection-error', () => reject());
|
||||
});
|
||||
return workspace;
|
||||
}
|
||||
|
||||
override async loadWorkspaces() {
|
||||
if (!token.isLogin) {
|
||||
return [];
|
||||
}
|
||||
const workspacesList = await getWorkspaces();
|
||||
const workspaces: WS[] = workspacesList.map(w => {
|
||||
return {
|
||||
...w,
|
||||
memberCount: 0,
|
||||
name: '',
|
||||
provider: 'affine',
|
||||
};
|
||||
});
|
||||
const workspaceInstances = workspaces.map(({ id }) => {
|
||||
const workspace =
|
||||
this._workspacesCache.get(id) ||
|
||||
new Workspace({
|
||||
room: id,
|
||||
}).register(BlockSchema);
|
||||
this._workspacesCache.set(id, workspace);
|
||||
if (workspace) {
|
||||
return new Promise<Workspace>(resolve => {
|
||||
downloadWorkspace(id).then(data => {
|
||||
applyUpdate(workspace.doc, new Uint8Array(data));
|
||||
resolve(workspace);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
});
|
||||
|
||||
(await Promise.all(workspaceInstances)).forEach((workspace, i) => {
|
||||
if (workspace) {
|
||||
workspaces[i] = {
|
||||
...workspaces[i],
|
||||
name: workspace.doc.meta.name,
|
||||
avatar: workspace.doc.meta.avatar,
|
||||
};
|
||||
}
|
||||
});
|
||||
const getDetailList = workspacesList.map(w => {
|
||||
const { id } = w;
|
||||
return new Promise<{ id: string; detail: WorkspaceDetail | null }>(
|
||||
resolve => {
|
||||
getWorkspaceDetail({ id }).then(data => {
|
||||
resolve({ id, detail: data || null });
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
const ownerList = await Promise.all(getDetailList);
|
||||
(await Promise.all(ownerList)).forEach(detail => {
|
||||
if (detail) {
|
||||
const { id, detail: workspaceDetail } = detail;
|
||||
if (workspaceDetail) {
|
||||
const { owner, member_count } = workspaceDetail;
|
||||
const currentWorkspace = workspaces.find(w => w.id === id);
|
||||
if (currentWorkspace) {
|
||||
currentWorkspace.owner = {
|
||||
id: owner.id,
|
||||
name: owner.name,
|
||||
avatar: owner.avatar_url,
|
||||
email: owner.email,
|
||||
};
|
||||
currentWorkspace.memberCount = member_count;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
workspaces.forEach(workspace => {
|
||||
this._workspaces.add(workspace);
|
||||
});
|
||||
|
||||
return workspaces;
|
||||
}
|
||||
|
||||
override async auth() {
|
||||
const refreshToken = await storage.getItem('token');
|
||||
if (refreshToken) {
|
||||
await token.refreshToken(refreshToken);
|
||||
if (token.isLogin && !token.isExpired) {
|
||||
// login success
|
||||
return;
|
||||
}
|
||||
}
|
||||
const user = await this._authorizer[0]?.();
|
||||
assert(user);
|
||||
this._user = {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
avatar: user.avatar_url,
|
||||
email: user.email,
|
||||
};
|
||||
}
|
||||
|
||||
public override async getUserInfo(): Promise<User | undefined> {
|
||||
return this._user;
|
||||
}
|
||||
|
||||
public override async deleteWorkspace(id: string): Promise<void> {
|
||||
await this.closeWorkspace(id);
|
||||
IndexedDBProvider.delete(id);
|
||||
await deleteWorkspace({ id });
|
||||
this._workspaces.remove(id);
|
||||
}
|
||||
|
||||
public override async clear(): Promise<void> {
|
||||
for (const w of this._workspacesCache.values()) {
|
||||
if (w.room) {
|
||||
try {
|
||||
await this.deleteWorkspace(w.room);
|
||||
this._workspaces.remove(w.room);
|
||||
} catch (e) {
|
||||
this._logger('has a problem of delete workspace ', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
this._workspacesCache.clear();
|
||||
}
|
||||
|
||||
public override async closeWorkspace(id: string) {
|
||||
const idb = this._idbMap.get(id);
|
||||
idb?.destroy();
|
||||
const ws = this._wsMap.get(id);
|
||||
ws?.disconnect();
|
||||
}
|
||||
|
||||
public override async leaveWorkspace(id: string): Promise<void> {
|
||||
await leaveWorkspace({ id });
|
||||
}
|
||||
|
||||
public override async invite(id: string, email: string): Promise<void> {
|
||||
return await inviteMember({ id, email });
|
||||
}
|
||||
|
||||
public override async removeMember(permissionId: number): Promise<void> {
|
||||
return await removeMember({ permissionId });
|
||||
}
|
||||
|
||||
private async _initWorkspaceDb(workspace: Workspace) {
|
||||
assert(workspace.room);
|
||||
let idb = this._idbMap.get(workspace.room);
|
||||
idb?.destroy();
|
||||
idb = new IndexedDBProvider(workspace.room, workspace.doc);
|
||||
this._idbMap.set(workspace.room, idb);
|
||||
await idb.whenSynced;
|
||||
this._logger('Local data loaded');
|
||||
return idb;
|
||||
}
|
||||
|
||||
public override async createWorkspace(
|
||||
meta: WorkspaceMeta
|
||||
): Promise<Workspace | undefined> {
|
||||
assert(meta.name, 'Workspace name is required');
|
||||
if (!meta.avatar) {
|
||||
// set default avatar
|
||||
const blob = await getDefaultHeadImgBlob(meta.name);
|
||||
meta.avatar = (await this.setBlob(blob)) || '';
|
||||
}
|
||||
const { id } = await createWorkspace(meta as Required<WorkspaceMeta>);
|
||||
this._logger('Creating affine workspace');
|
||||
const nw = new Workspace({
|
||||
room: id,
|
||||
}).register(BlockSchema);
|
||||
nw.meta.setName(meta.name);
|
||||
nw.meta.setAvatar(meta.avatar);
|
||||
this._initWorkspaceDb(nw);
|
||||
|
||||
const workspaceInfo: WS = {
|
||||
name: meta.name,
|
||||
id,
|
||||
isPublish: false,
|
||||
avatar: '',
|
||||
owner: undefined,
|
||||
isLocal: true,
|
||||
memberCount: 1,
|
||||
provider: 'local',
|
||||
};
|
||||
|
||||
this._workspaces.add(workspaceInfo);
|
||||
return nw;
|
||||
}
|
||||
|
||||
public override async publish(id: string, isPublish: boolean): Promise<void> {
|
||||
await updateWorkspace({ id, public: isPublish });
|
||||
}
|
||||
}
|
||||
@@ -4,16 +4,24 @@ export type { Callback } from './token.js';
|
||||
import { getAuthorizer } from './token.js';
|
||||
import * as user from './user.js';
|
||||
import * as workspace from './workspace.js';
|
||||
import * as business from './business.js';
|
||||
|
||||
export type Apis = typeof user &
|
||||
typeof workspace & {
|
||||
business: typeof business;
|
||||
signInWithGoogle: ReturnType<typeof getAuthorizer>[0];
|
||||
onAuthStateChanged: ReturnType<typeof getAuthorizer>[1];
|
||||
};
|
||||
|
||||
export const getApis = (): Apis => {
|
||||
const [signInWithGoogle, onAuthStateChanged] = getAuthorizer();
|
||||
return { ...user, ...workspace, signInWithGoogle, onAuthStateChanged };
|
||||
return {
|
||||
...user,
|
||||
...workspace,
|
||||
business,
|
||||
signInWithGoogle,
|
||||
onAuthStateChanged,
|
||||
};
|
||||
};
|
||||
|
||||
export type { AccessTokenMessage } from './token';
|
||||
@@ -2,8 +2,8 @@ import { initializeApp } from 'firebase/app';
|
||||
import { getAuth, GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
|
||||
import type { User } from 'firebase/auth';
|
||||
|
||||
import { getLogger } from '../index.js';
|
||||
import { bareClient } from './request.js';
|
||||
import { getLogger } from '../../../logger';
|
||||
import { bareClient } from './request';
|
||||
|
||||
export interface AccessTokenMessage {
|
||||
create_at: number;
|
||||
@@ -168,14 +168,15 @@ export const getAuthorizer = () => {
|
||||
|
||||
const signInWithGoogle = async () => {
|
||||
const idToken = await getToken();
|
||||
let loginUser: AccessTokenMessage | null = null;
|
||||
if (idToken) {
|
||||
await token.initToken(idToken);
|
||||
loginUser = await token.initToken(idToken);
|
||||
} else {
|
||||
const user = await signInWithPopup(firebaseAuth, googleAuthProvider);
|
||||
const idToken = await user.user.getIdToken();
|
||||
await token.initToken(idToken);
|
||||
loginUser = await token.initToken(idToken);
|
||||
}
|
||||
return firebaseAuth.currentUser;
|
||||
return loginUser;
|
||||
};
|
||||
|
||||
const onAuthStateChanged = (callback: (user: User | null) => void) => {
|
||||
@@ -84,7 +84,7 @@ export interface CreateWorkspaceParams {
|
||||
|
||||
export async function createWorkspace(
|
||||
params: CreateWorkspaceParams
|
||||
): Promise<void> {
|
||||
): Promise<{ id: string }> {
|
||||
return client.post('api/workspace', { json: params }).json();
|
||||
}
|
||||
|
||||
@@ -1,175 +1 @@
|
||||
import assert from 'assert';
|
||||
import { applyUpdate, Doc } from 'yjs';
|
||||
|
||||
import type {
|
||||
ConfigStore,
|
||||
DataCenterSignals,
|
||||
InitialParams,
|
||||
Logger,
|
||||
} from '../index.js';
|
||||
import { token, Callback, getApis } from '../../apis/index.js';
|
||||
import { LocalProvider } from '../local/index.js';
|
||||
|
||||
import { WebsocketProvider } from './sync.js';
|
||||
import { IndexedDBProvider } from '../local/indexeddb.js';
|
||||
|
||||
export class AffineProvider extends LocalProvider {
|
||||
static id = 'affine';
|
||||
private _onTokenRefresh?: Callback = undefined;
|
||||
private _ws?: WebsocketProvider;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
async init(params: InitialParams) {
|
||||
super.init(params);
|
||||
|
||||
this._onTokenRefresh = () => {
|
||||
if (token.refresh) {
|
||||
this._config.set('token', token.refresh);
|
||||
}
|
||||
};
|
||||
assert(this._onTokenRefresh);
|
||||
|
||||
token.onChange(this._onTokenRefresh);
|
||||
|
||||
// initial login token
|
||||
if (token.isExpired) {
|
||||
try {
|
||||
const refreshToken = await this._config.get('token');
|
||||
await token.refreshToken(refreshToken);
|
||||
|
||||
if (token.refresh) {
|
||||
this._config.set('token', token.refresh);
|
||||
}
|
||||
|
||||
assert(token.isLogin);
|
||||
} catch (_) {
|
||||
this._logger('Authorization failed, fallback to local mode');
|
||||
}
|
||||
} else {
|
||||
this._config.set('token', token.refresh);
|
||||
}
|
||||
}
|
||||
|
||||
async destroy() {
|
||||
if (this._onTokenRefresh) {
|
||||
token.offChange(this._onTokenRefresh);
|
||||
}
|
||||
this._ws?.disconnect();
|
||||
}
|
||||
|
||||
async initData() {
|
||||
const databases = await indexedDB.databases();
|
||||
await super.initData(
|
||||
// set locally to true if exists a same name db
|
||||
databases
|
||||
.map(db => db.name)
|
||||
.filter(v => v)
|
||||
.includes(this._workspace.room)
|
||||
);
|
||||
|
||||
const workspace = this._workspace;
|
||||
const doc = workspace.doc;
|
||||
|
||||
this._logger(`Login: ${token.isLogin}`);
|
||||
|
||||
if (workspace.room && token.isLogin) {
|
||||
try {
|
||||
// init data from cloud
|
||||
await AffineProvider._initCloudDoc(
|
||||
workspace.room,
|
||||
doc,
|
||||
this._logger,
|
||||
this._signals
|
||||
);
|
||||
|
||||
// Wait for ws synchronization to complete, otherwise the data will be modified in reverse, which can be optimized later
|
||||
this._ws = new WebsocketProvider('/', workspace.room, doc);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
// TODO: synced will also be triggered on reconnection after losing sync
|
||||
// There needs to be an event mechanism to emit the synchronization state to the upper layer
|
||||
assert(this._ws);
|
||||
this._ws.once('synced', () => resolve());
|
||||
this._ws.once('lost-connection', () => resolve());
|
||||
this._ws.once('connection-error', () => reject());
|
||||
});
|
||||
this._signals.listAdd.emit({
|
||||
workspace: workspace.room,
|
||||
provider: this.id,
|
||||
locally: true,
|
||||
});
|
||||
} catch (e) {
|
||||
this._logger('Failed to init cloud workspace', e);
|
||||
}
|
||||
}
|
||||
|
||||
// if after update, the space:meta is empty
|
||||
// then we need to get map with doc
|
||||
// just a workaround for yjs
|
||||
doc.getMap('space:meta');
|
||||
}
|
||||
|
||||
private static async _initCloudDoc(
|
||||
workspace: string,
|
||||
doc: Doc,
|
||||
logger: Logger,
|
||||
signals: DataCenterSignals
|
||||
) {
|
||||
const apis = getApis();
|
||||
logger(`Loading ${workspace}...`);
|
||||
const updates = await apis.downloadWorkspace(workspace);
|
||||
if (updates) {
|
||||
await new Promise(resolve => {
|
||||
doc.once('update', resolve);
|
||||
applyUpdate(doc, new Uint8Array(updates));
|
||||
});
|
||||
logger(`Loaded: ${workspace}`);
|
||||
|
||||
// only add to list as online workspace
|
||||
signals.listAdd.emit({
|
||||
workspace,
|
||||
provider: this.id,
|
||||
// at this time we always download full workspace
|
||||
// but after we support sub doc, we can only download metadata
|
||||
locally: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
static async auth(
|
||||
config: Readonly<ConfigStore<string>>,
|
||||
logger: Logger,
|
||||
signals: DataCenterSignals
|
||||
) {
|
||||
const refreshToken = await config.get('token');
|
||||
if (refreshToken) {
|
||||
await token.refreshToken(refreshToken);
|
||||
if (token.isLogin && !token.isExpired) {
|
||||
logger('check login success');
|
||||
// login success
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
logger('start login');
|
||||
// login with google
|
||||
const apis = getApis();
|
||||
assert(apis.signInWithGoogle);
|
||||
const user = await apis.signInWithGoogle();
|
||||
assert(user);
|
||||
logger(`login success: ${user.displayName}`);
|
||||
|
||||
// TODO: refresh local workspace data
|
||||
const workspaces = await apis.getWorkspaces();
|
||||
await Promise.all(
|
||||
workspaces.map(async ({ id }) => {
|
||||
const doc = new Doc();
|
||||
const idb = new IndexedDBProvider(id, doc);
|
||||
await idb.whenSynced;
|
||||
await this._initCloudDoc(id, doc, logger, signals);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
export * from './affine';
|
||||
|
||||
@@ -1,82 +1,158 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import type { Workspace } from '@blocksuite/store';
|
||||
import { BlobStorage, Workspace } from '@blocksuite/store';
|
||||
import { Logger, User, Workspace as WS, WorkspaceMeta } from '../types';
|
||||
import type { WorkspacesScope } from '../workspaces';
|
||||
|
||||
import type { BlobURL } from '@blocksuite/store/dist/blob/types';
|
||||
import type {
|
||||
Apis,
|
||||
DataCenterSignals,
|
||||
Logger,
|
||||
InitialParams,
|
||||
ConfigStore,
|
||||
} from './index';
|
||||
const defaultLogger = () => {
|
||||
return;
|
||||
};
|
||||
|
||||
export interface ProviderConstructorParams {
|
||||
logger?: Logger;
|
||||
workspaces: WorkspacesScope;
|
||||
}
|
||||
|
||||
export class BaseProvider {
|
||||
static id = 'base';
|
||||
protected _apis!: Readonly<Apis>;
|
||||
protected _config!: Readonly<ConfigStore>;
|
||||
public readonly id: string = 'base';
|
||||
protected _workspaces!: WorkspacesScope;
|
||||
protected _logger!: Logger;
|
||||
protected _signals!: DataCenterSignals;
|
||||
protected _workspace!: Workspace;
|
||||
protected _blobs!: BlobStorage;
|
||||
|
||||
constructor() {
|
||||
// Nothing to do here
|
||||
}
|
||||
|
||||
get id(): string {
|
||||
return (this.constructor as any).id;
|
||||
}
|
||||
|
||||
async init(params: InitialParams) {
|
||||
this._apis = params.apis;
|
||||
this._config = params.config;
|
||||
this._logger = params.logger;
|
||||
this._signals = params.signals;
|
||||
this._workspace = params.workspace;
|
||||
this._logger.enabled = params.debug;
|
||||
}
|
||||
|
||||
async clear() {
|
||||
await this.destroy();
|
||||
await this._config.clear();
|
||||
}
|
||||
|
||||
async destroy() {
|
||||
// Nothing to do here
|
||||
}
|
||||
|
||||
async initData() {
|
||||
throw Error('Not implemented: initData');
|
||||
public constructor({ logger, workspaces }: ProviderConstructorParams) {
|
||||
this._logger = (logger || defaultLogger) as Logger;
|
||||
this._workspaces = workspaces;
|
||||
}
|
||||
|
||||
/**
|
||||
* should return a blob url
|
||||
* hook after provider registered
|
||||
*/
|
||||
async getBlob(_id: string): Promise<BlobURL | null> {
|
||||
throw Error('Not implemented: getBlob');
|
||||
public async init() {
|
||||
return;
|
||||
}
|
||||
|
||||
// should return a blob unique id
|
||||
async setBlob(_blob: Blob): Promise<string> {
|
||||
throw Error('Not implemented: setBlob');
|
||||
/**
|
||||
* auth provider
|
||||
*/
|
||||
public async auth() {
|
||||
return;
|
||||
}
|
||||
|
||||
get workspace() {
|
||||
return this._workspace;
|
||||
/**
|
||||
* logout provider
|
||||
*/
|
||||
public async logout() {
|
||||
return;
|
||||
}
|
||||
|
||||
static async auth(
|
||||
_config: Readonly<ConfigStore>,
|
||||
logger: Logger,
|
||||
_signals: DataCenterSignals
|
||||
) {
|
||||
logger("This provider doesn't require authentication");
|
||||
/**
|
||||
* warp workspace with provider functions
|
||||
* @param workspace
|
||||
* @returns
|
||||
*/
|
||||
public async warpWorkspace(workspace: Workspace): Promise<Workspace> {
|
||||
return workspace;
|
||||
}
|
||||
|
||||
// get workspace list,return a map of workspace id and boolean
|
||||
// if value is true, it exists locally, otherwise it does not exist locally
|
||||
static async list(
|
||||
_config: Readonly<ConfigStore>
|
||||
): Promise<Map<string, boolean> | undefined> {
|
||||
throw Error('Not implemented: list');
|
||||
/**
|
||||
* load workspaces
|
||||
**/
|
||||
public async loadWorkspaces(): Promise<WS[]> {
|
||||
throw new Error(`provider: ${this.id} loadWorkSpace Not implemented`);
|
||||
}
|
||||
|
||||
/**
|
||||
* get auth user info
|
||||
* @returns
|
||||
*/
|
||||
public async getUserInfo(): Promise<User | undefined> {
|
||||
return;
|
||||
}
|
||||
|
||||
async getBlob(id: string): Promise<string | null> {
|
||||
return await this._blobs.get(id);
|
||||
}
|
||||
|
||||
async setBlob(blob: Blob): Promise<string> {
|
||||
return await this._blobs.set(blob);
|
||||
}
|
||||
|
||||
/**
|
||||
* clear all local data in provider
|
||||
*/
|
||||
async clear() {
|
||||
this._blobs.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* delete workspace include all data
|
||||
* @param id workspace id
|
||||
*/
|
||||
public async deleteWorkspace(id: string): Promise<void> {
|
||||
id;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* leave workspace by workspace id
|
||||
* @param id workspace id
|
||||
*/
|
||||
public async leaveWorkspace(id: string): Promise<void> {
|
||||
id;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* close db link and websocket connection and other resources
|
||||
* @param id workspace id
|
||||
*/
|
||||
public async closeWorkspace(id: string) {
|
||||
id;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* invite workspace member
|
||||
* @param id workspace id
|
||||
*/
|
||||
public async invite(id: string, email: string): Promise<void> {
|
||||
id;
|
||||
email;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* remove workspace member by permission id
|
||||
* @param permissionId
|
||||
*/
|
||||
public async removeMember(permissionId: number): Promise<void> {
|
||||
permissionId;
|
||||
return;
|
||||
}
|
||||
|
||||
public async publish(id: string, isPublish: boolean): Promise<void> {
|
||||
id;
|
||||
isPublish;
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* change workspace meta by workspace id , work for cached list in different provider
|
||||
* @param id
|
||||
* @param meta
|
||||
* @returns
|
||||
*/
|
||||
public async updateWorkspaceMeta(
|
||||
id: string,
|
||||
meta: Partial<WorkspaceMeta>
|
||||
): Promise<void> {
|
||||
id;
|
||||
meta;
|
||||
return;
|
||||
}
|
||||
|
||||
public async createWorkspace(
|
||||
meta: WorkspaceMeta
|
||||
): Promise<Workspace | undefined> {
|
||||
meta;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1 @@
|
||||
import type { Workspace } from '@blocksuite/store';
|
||||
|
||||
import type { Apis } from '../apis';
|
||||
import type { DataCenterSignals } from '../datacenter';
|
||||
import type { getLogger } from '../index';
|
||||
import type { ConfigStore } from '../store';
|
||||
|
||||
export type Logger = ReturnType<typeof getLogger>;
|
||||
|
||||
export type InitialParams = {
|
||||
apis: Apis;
|
||||
config: Readonly<ConfigStore>;
|
||||
debug: boolean;
|
||||
logger: Logger;
|
||||
signals: DataCenterSignals;
|
||||
workspace: Workspace;
|
||||
};
|
||||
|
||||
export type { Apis, ConfigStore, DataCenterSignals, Workspace };
|
||||
export type { BaseProvider } from './base.js';
|
||||
export { AffineProvider } from './affine/index.js';
|
||||
export { LocalProvider } from './local/index.js';
|
||||
export { SelfHostedProvider } from './selfhosted/index.js';
|
||||
export * from './affine/affine';
|
||||
|
||||
@@ -196,4 +196,8 @@ export class IndexedDBProvider extends Observable<string> {
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
|
||||
static delete(name: string): Promise<void> {
|
||||
return idb.deleteDB(name);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +1 @@
|
||||
import type { BlobStorage } from '@blocksuite/store';
|
||||
import assert from 'assert';
|
||||
|
||||
import type { ConfigStore, InitialParams } from '../index.js';
|
||||
import { BaseProvider } from '../base.js';
|
||||
import { IndexedDBProvider } from './indexeddb.js';
|
||||
|
||||
export class LocalProvider extends BaseProvider {
|
||||
static id = 'local';
|
||||
private _blobs!: BlobStorage;
|
||||
private _idb?: IndexedDBProvider = undefined;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
async init(params: InitialParams) {
|
||||
super.init(params);
|
||||
|
||||
const blobs = await this._workspace.blobs;
|
||||
assert(blobs);
|
||||
this._blobs = blobs;
|
||||
}
|
||||
|
||||
async initData(locally = true) {
|
||||
assert(this._workspace.room);
|
||||
this._logger('Loading local data');
|
||||
this._idb = new IndexedDBProvider(
|
||||
this._workspace.room,
|
||||
this._workspace.doc
|
||||
);
|
||||
|
||||
await this._idb.whenSynced;
|
||||
this._logger('Local data loaded');
|
||||
|
||||
this._signals.listAdd.emit({
|
||||
workspace: this._workspace.room,
|
||||
provider: this.id,
|
||||
locally,
|
||||
});
|
||||
}
|
||||
|
||||
async clear() {
|
||||
assert(this._workspace.room);
|
||||
await super.clear();
|
||||
await this._blobs.clear();
|
||||
await this._idb?.clearData();
|
||||
this._signals.listRemove.emit(this._workspace.room);
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
super.destroy();
|
||||
await this._idb?.destroy();
|
||||
}
|
||||
|
||||
async getBlob(id: string): Promise<string | null> {
|
||||
return this._blobs.get(id);
|
||||
}
|
||||
|
||||
async setBlob(blob: Blob): Promise<string> {
|
||||
return this._blobs.set(blob);
|
||||
}
|
||||
|
||||
static async list(
|
||||
config: Readonly<ConfigStore<boolean>>
|
||||
): Promise<Map<string, boolean> | undefined> {
|
||||
const entries = await config.entries();
|
||||
return new Map(
|
||||
entries
|
||||
.filter(([key]) => key.startsWith('list:'))
|
||||
.map(([key, value]) => [key.slice(5), value])
|
||||
);
|
||||
}
|
||||
}
|
||||
export * from './local';
|
||||
|
||||
49
packages/data-center/src/provider/local/local.spec.ts
Normal file
49
packages/data-center/src/provider/local/local.spec.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Workspaces } from '../../workspaces';
|
||||
import { LocalProvider } from './local';
|
||||
import 'fake-indexeddb/auto';
|
||||
|
||||
describe('local provider', () => {
|
||||
const workspaces = new Workspaces();
|
||||
const provider = new LocalProvider({
|
||||
workspaces: workspaces.createScope(),
|
||||
});
|
||||
|
||||
const workspaceName = 'workspace-test';
|
||||
let workspaceId: string | undefined;
|
||||
|
||||
test('create workspace', async () => {
|
||||
const w = await provider.createWorkspace({
|
||||
name: workspaceName,
|
||||
avatar: 'avatar-url-test',
|
||||
});
|
||||
workspaceId = w?.room;
|
||||
|
||||
expect(workspaces.workspaces.length).toEqual(1);
|
||||
expect(workspaces.workspaces[0].name).toEqual(workspaceName);
|
||||
});
|
||||
|
||||
test('workspace list cache', async () => {
|
||||
const workspaces1 = new Workspaces();
|
||||
const provider1 = new LocalProvider({
|
||||
workspaces: workspaces1.createScope(),
|
||||
});
|
||||
await provider1.loadWorkspaces();
|
||||
expect(workspaces1.workspaces.length).toEqual(1);
|
||||
expect(workspaces1.workspaces[0].name).toEqual(workspaceName);
|
||||
expect(workspaces1.workspaces[0].id).toEqual(workspaceId);
|
||||
});
|
||||
|
||||
test('update workspace', async () => {
|
||||
await provider.updateWorkspaceMeta(workspaceId!, {
|
||||
name: '1111',
|
||||
});
|
||||
expect(workspaces.workspaces[0].name).toEqual('1111');
|
||||
});
|
||||
|
||||
test('delete workspace', async () => {
|
||||
expect(workspaces.workspaces.length).toEqual(1);
|
||||
await provider.deleteWorkspace(workspaces.workspaces[0].id);
|
||||
expect(workspaces.workspaces.length).toEqual(0);
|
||||
});
|
||||
});
|
||||
117
packages/data-center/src/provider/local/local.ts
Normal file
117
packages/data-center/src/provider/local/local.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { BaseProvider } from '../base';
|
||||
import type { ProviderConstructorParams } from '../base';
|
||||
import { varStorage as storage } from 'lib0/storage';
|
||||
import { Workspace as WS, WorkspaceMeta } from '../../types';
|
||||
import { Workspace, uuidv4 } from '@blocksuite/store';
|
||||
import { IndexedDBProvider } from '../indexeddb';
|
||||
import assert from 'assert';
|
||||
import { getDefaultHeadImgBlob } from '../../utils';
|
||||
|
||||
const WORKSPACE_KEY = 'workspaces';
|
||||
|
||||
export class LocalProvider extends BaseProvider {
|
||||
public id = 'local';
|
||||
private _idbMap: Map<string, IndexedDBProvider> = new Map();
|
||||
|
||||
constructor(params: ProviderConstructorParams) {
|
||||
super(params);
|
||||
this.loadWorkspaces();
|
||||
}
|
||||
|
||||
private _storeWorkspaces(workspaces: WS[]) {
|
||||
storage.setItem(WORKSPACE_KEY, JSON.stringify(workspaces));
|
||||
}
|
||||
|
||||
private async _initWorkspaceDb(workspace: Workspace) {
|
||||
assert(workspace.room);
|
||||
let idb = this._idbMap.get(workspace.room);
|
||||
idb?.destroy();
|
||||
idb = new IndexedDBProvider(workspace.room, workspace.doc);
|
||||
this._idbMap.set(workspace.room, idb);
|
||||
this._logger('Local data loaded');
|
||||
return idb;
|
||||
}
|
||||
|
||||
public override async warpWorkspace(
|
||||
workspace: Workspace
|
||||
): Promise<Workspace> {
|
||||
assert(workspace.room);
|
||||
await this._initWorkspaceDb(workspace);
|
||||
return workspace;
|
||||
}
|
||||
|
||||
override loadWorkspaces(): Promise<WS[]> {
|
||||
const workspaceStr = storage.getItem(WORKSPACE_KEY);
|
||||
let workspaces: WS[] = [];
|
||||
if (workspaceStr) {
|
||||
try {
|
||||
workspaces = JSON.parse(workspaceStr) as WS[];
|
||||
workspaces.forEach(workspace => {
|
||||
this._workspaces.add(workspace);
|
||||
});
|
||||
} catch (error) {
|
||||
this._logger(`Failed to parse workspaces from storage`);
|
||||
}
|
||||
}
|
||||
return Promise.resolve(workspaces);
|
||||
}
|
||||
|
||||
public override async deleteWorkspace(id: string): Promise<void> {
|
||||
const workspace = this._workspaces.get(id);
|
||||
if (workspace) {
|
||||
IndexedDBProvider.delete(id);
|
||||
this._workspaces.remove(id);
|
||||
this._storeWorkspaces(this._workspaces.list());
|
||||
} else {
|
||||
this._logger(`Failed to delete workspace ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
public override async updateWorkspaceMeta(
|
||||
id: string,
|
||||
meta: Partial<WorkspaceMeta>
|
||||
) {
|
||||
this._workspaces.update(id, meta);
|
||||
this._storeWorkspaces(this._workspaces.list());
|
||||
}
|
||||
|
||||
public override async createWorkspace(
|
||||
meta: WorkspaceMeta
|
||||
): Promise<Workspace | undefined> {
|
||||
assert(meta.name, 'Workspace name is required');
|
||||
if (!meta.avatar) {
|
||||
// set default avatar
|
||||
const blob = await getDefaultHeadImgBlob(meta.name);
|
||||
meta.avatar = (await this.setBlob(blob)) || '';
|
||||
}
|
||||
this._logger('Creating affine workspace');
|
||||
|
||||
const workspaceInfo: WS = {
|
||||
name: meta.name,
|
||||
id: uuidv4(),
|
||||
isPublish: false,
|
||||
avatar: '',
|
||||
owner: undefined,
|
||||
isLocal: true,
|
||||
memberCount: 1,
|
||||
provider: 'local',
|
||||
};
|
||||
|
||||
const workspace = new Workspace({ room: workspaceInfo.id });
|
||||
this._initWorkspaceDb(workspace);
|
||||
workspace.meta.setName(meta.name);
|
||||
workspace.meta.setAvatar(meta.avatar);
|
||||
|
||||
this._workspaces.add(workspaceInfo);
|
||||
this._storeWorkspaces(this._workspaces.list());
|
||||
|
||||
return workspace;
|
||||
}
|
||||
|
||||
public override async clear(): Promise<void> {
|
||||
const workspaces = await this.loadWorkspaces();
|
||||
workspaces.forEach(ws => IndexedDBProvider.delete(ws.id));
|
||||
this._storeWorkspaces([]);
|
||||
this._workspaces.clear();
|
||||
}
|
||||
}
|
||||
23
packages/data-center/src/types/index.ts
Normal file
23
packages/data-center/src/types/index.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { getLogger } from '../logger';
|
||||
|
||||
export type Workspace = {
|
||||
name: string;
|
||||
id: string;
|
||||
isPublish?: boolean;
|
||||
avatar?: string;
|
||||
owner?: User;
|
||||
isLocal?: boolean;
|
||||
memberCount: number;
|
||||
provider: string;
|
||||
};
|
||||
|
||||
export type User = {
|
||||
name: string;
|
||||
id: string;
|
||||
email: string;
|
||||
avatar: string;
|
||||
};
|
||||
|
||||
export type WorkspaceMeta = Pick<Workspace, 'name' | 'avatar'>;
|
||||
|
||||
export type Logger = ReturnType<typeof getLogger>;
|
||||
38
packages/data-center/src/utils/index.ts
Normal file
38
packages/data-center/src/utils/index.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
const DefaultHeadImgColors = [
|
||||
['#C6F2F3', '#0C6066'],
|
||||
['#FFF5AB', '#896406'],
|
||||
['#FFCCA7', '#8F4500'],
|
||||
['#FFCECE', '#AF1212'],
|
||||
['#E3DEFF', '#511AAB'],
|
||||
];
|
||||
|
||||
export async function getDefaultHeadImgBlob(
|
||||
workspaceName: string
|
||||
): Promise<Blob> {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.height = 100;
|
||||
canvas.width = 100;
|
||||
const ctx = canvas.getContext('2d');
|
||||
return new Promise<Blob>((resolve, reject) => {
|
||||
if (ctx) {
|
||||
const randomNumber = Math.floor(Math.random() * 5);
|
||||
const randomColor = DefaultHeadImgColors[randomNumber];
|
||||
ctx.fillStyle = randomColor[0];
|
||||
ctx.fillRect(0, 0, 100, 100);
|
||||
ctx.font = "600 50px 'PingFang SC', 'Microsoft Yahei'";
|
||||
ctx.fillStyle = randomColor[1];
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(workspaceName[0], 50, 50);
|
||||
canvas.toBlob(blob => {
|
||||
if (blob) {
|
||||
resolve(blob);
|
||||
} else {
|
||||
reject();
|
||||
}
|
||||
}, 'image/png');
|
||||
} else {
|
||||
reject();
|
||||
}
|
||||
});
|
||||
}
|
||||
2
packages/data-center/src/workspaces/index.ts
Normal file
2
packages/data-center/src/workspaces/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { Workspaces } from './workspaces';
|
||||
export type { WorkspacesScope, WorkspacesChangeEvent } from './workspaces';
|
||||
50
packages/data-center/src/workspaces/workspaces.spec.ts
Normal file
50
packages/data-center/src/workspaces/workspaces.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { Workspaces } from './workspaces';
|
||||
import type { WorkspacesChangeEvent } from './workspaces';
|
||||
|
||||
describe('workspaces observable', () => {
|
||||
const workspaces = new Workspaces();
|
||||
|
||||
const scope = workspaces.createScope();
|
||||
|
||||
test('add workspace', () => {
|
||||
workspaces.once('change', (event: WorkspacesChangeEvent) => {
|
||||
expect(event.added?.id).toEqual('123');
|
||||
});
|
||||
scope.add({
|
||||
id: '123',
|
||||
name: 'test',
|
||||
memberCount: 1,
|
||||
provider: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('list workspace', () => {
|
||||
const list = scope.list();
|
||||
expect(list.length).toEqual(1);
|
||||
expect(list[0].id).toEqual('123');
|
||||
});
|
||||
|
||||
test('get workspace', () => {
|
||||
expect(scope.get('123')?.id).toEqual('123');
|
||||
});
|
||||
|
||||
test('update workspace', () => {
|
||||
workspaces.once('change', (event: WorkspacesChangeEvent) => {
|
||||
expect(event.updated?.name).toEqual('demo');
|
||||
});
|
||||
scope.update('123', { name: 'demo' });
|
||||
});
|
||||
|
||||
test('get workspace form other scope', () => {
|
||||
const scope1 = workspaces.createScope();
|
||||
expect(scope1.get('123')).toBeFalsy();
|
||||
});
|
||||
|
||||
test('delete workspace', () => {
|
||||
workspaces.once('change', (event: WorkspacesChangeEvent) => {
|
||||
expect(event.deleted?.id).toEqual('123');
|
||||
});
|
||||
scope.remove('123');
|
||||
});
|
||||
});
|
||||
127
packages/data-center/src/workspaces/workspaces.ts
Normal file
127
packages/data-center/src/workspaces/workspaces.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { Observable } from 'lib0/observable';
|
||||
import type { Workspace, WorkspaceMeta } from '../types';
|
||||
|
||||
export interface WorkspacesScope {
|
||||
get: (workspaceId: string) => Workspace | undefined;
|
||||
list: () => Workspace[];
|
||||
add: (workspace: Workspace) => void;
|
||||
remove: (workspaceId: string) => boolean;
|
||||
clear: () => void;
|
||||
update: (workspaceId: string, workspaceMeta: Partial<WorkspaceMeta>) => void;
|
||||
}
|
||||
|
||||
export interface WorkspacesChangeEvent {
|
||||
added?: Workspace;
|
||||
deleted?: Workspace;
|
||||
updated?: Workspace;
|
||||
}
|
||||
|
||||
export class Workspaces extends Observable<'change'> {
|
||||
private _workspacesMap = new Map<string, Workspace>();
|
||||
|
||||
get workspaces(): Workspace[] {
|
||||
return Array.from(this._workspacesMap.values());
|
||||
}
|
||||
|
||||
find(workspaceId: string) {
|
||||
return this._workspacesMap.get(workspaceId);
|
||||
}
|
||||
|
||||
createScope(): WorkspacesScope {
|
||||
const scopedWorkspaceIds = new Set<string>();
|
||||
|
||||
const get = (workspaceId: string) => {
|
||||
if (!scopedWorkspaceIds.has(workspaceId)) {
|
||||
return;
|
||||
}
|
||||
return this._workspacesMap.get(workspaceId);
|
||||
};
|
||||
|
||||
const add = (workspace: Workspace) => {
|
||||
if (this._workspacesMap.has(workspace.id)) {
|
||||
throw new Error(`Duplicate workspace id.`);
|
||||
}
|
||||
this._workspacesMap.set(workspace.id, workspace);
|
||||
scopedWorkspaceIds.add(workspace.id);
|
||||
|
||||
this.emit('change', [
|
||||
{
|
||||
added: workspace,
|
||||
} as WorkspacesChangeEvent,
|
||||
]);
|
||||
};
|
||||
|
||||
const remove = (workspaceId: string) => {
|
||||
if (!scopedWorkspaceIds.has(workspaceId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const workspace = this._workspacesMap.get(workspaceId);
|
||||
if (workspace) {
|
||||
const ret = this._workspacesMap.delete(workspaceId);
|
||||
// If deletion failed, return.
|
||||
if (!ret) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
scopedWorkspaceIds.delete(workspaceId);
|
||||
|
||||
this.emit('change', [
|
||||
{
|
||||
deleted: workspace,
|
||||
} as WorkspacesChangeEvent,
|
||||
]);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const clear = () => {
|
||||
scopedWorkspaceIds.forEach(id => {
|
||||
remove(id);
|
||||
});
|
||||
};
|
||||
|
||||
const update = (
|
||||
workspaceId: string,
|
||||
workspaceMeta: Partial<WorkspaceMeta>
|
||||
) => {
|
||||
if (!scopedWorkspaceIds.has(workspaceId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const workspace = this._workspacesMap.get(workspaceId);
|
||||
if (!workspace) {
|
||||
return true;
|
||||
}
|
||||
|
||||
this._workspacesMap.set(workspaceId, { ...workspace, ...workspaceMeta });
|
||||
|
||||
this.emit('change', [
|
||||
{
|
||||
updated: this._workspacesMap.get(workspaceId),
|
||||
} as WorkspacesChangeEvent,
|
||||
]);
|
||||
};
|
||||
|
||||
// TODO: need to optimize
|
||||
const list = () => {
|
||||
const workspaces: Workspace[] = [];
|
||||
scopedWorkspaceIds.forEach(id => {
|
||||
const workspace = this._workspacesMap.get(id);
|
||||
if (workspace) {
|
||||
workspaces.push(workspace);
|
||||
}
|
||||
});
|
||||
return workspaces;
|
||||
};
|
||||
|
||||
return {
|
||||
get,
|
||||
list,
|
||||
add,
|
||||
remove,
|
||||
clear,
|
||||
update,
|
||||
};
|
||||
}
|
||||
}
|
||||
101
packages/data-center/src/workspaces/workspaces.ts.bak
Normal file
101
packages/data-center/src/workspaces/workspaces.ts.bak
Normal file
@@ -0,0 +1,101 @@
|
||||
import { Workspace as WS } from '../types';
|
||||
|
||||
import { Observable } from 'lib0/observable';
|
||||
import { uuidv4 } from '@blocksuite/store';
|
||||
import { DataCenter } from '../datacenter';
|
||||
|
||||
export class Workspaces extends Observable<string> {
|
||||
private _workspaces: WS[];
|
||||
private readonly _dc: DataCenter;
|
||||
|
||||
constructor(dc: DataCenter) {
|
||||
super();
|
||||
this._workspaces = [];
|
||||
this._dc = dc;
|
||||
}
|
||||
|
||||
public init() {
|
||||
this._loadWorkspaces();
|
||||
}
|
||||
|
||||
get workspaces() {
|
||||
return this._workspaces;
|
||||
}
|
||||
|
||||
/**
|
||||
* emit when workspaces changed
|
||||
* @param {(workspace: WS[]) => void} cb
|
||||
*/
|
||||
onWorkspacesChange(cb: (workspace: WS[]) => void) {
|
||||
this.on('change', cb);
|
||||
}
|
||||
|
||||
private async _loadWorkspaces() {
|
||||
const providers = this._dc.providers;
|
||||
let workspaces: WS[] = [];
|
||||
providers.forEach(async p => {
|
||||
const pWorkspaces = await p.loadWorkspaces();
|
||||
workspaces = [...workspaces, ...pWorkspaces];
|
||||
this._updateWorkspaces([...workspaces, ...pWorkspaces]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* focus load all workspaces list
|
||||
*/
|
||||
public async refreshWorkspaces() {
|
||||
this._loadWorkspaces();
|
||||
}
|
||||
|
||||
private _updateWorkspaces(workspaces: WS[]) {
|
||||
this._workspaces = workspaces;
|
||||
this.emit('change', this._workspaces);
|
||||
}
|
||||
|
||||
private _getDefaultWorkspace(name: string): WS {
|
||||
return {
|
||||
name,
|
||||
id: uuidv4(),
|
||||
isPublish: false,
|
||||
avatar: '',
|
||||
owner: undefined,
|
||||
isLocal: true,
|
||||
memberCount: 1,
|
||||
provider: 'local',
|
||||
};
|
||||
}
|
||||
|
||||
/** add a local workspaces */
|
||||
public addLocalWorkspace(name: string) {
|
||||
const workspace = this._getDefaultWorkspace(name);
|
||||
this._updateWorkspaces([...this._workspaces, workspace]);
|
||||
return workspace;
|
||||
}
|
||||
|
||||
/** delete a workspaces by id */
|
||||
public delete(id: string) {
|
||||
const index = this._workspaces.findIndex(w => w.id === id);
|
||||
if (index >= 0) {
|
||||
this._workspaces.splice(index, 1);
|
||||
this._updateWorkspaces(this._workspaces);
|
||||
}
|
||||
}
|
||||
|
||||
/** get workspace info by id */
|
||||
public getWorkspace(id: string) {
|
||||
return this._workspaces.find(w => w.id === id);
|
||||
}
|
||||
|
||||
/** check if workspace exists */
|
||||
public hasWorkspace(id: string) {
|
||||
return this._workspaces.some(w => w.id === id);
|
||||
}
|
||||
|
||||
public updateWorkspaceInfo(id: string, info: Partial<WS>) {
|
||||
const index = this._workspaces.findIndex(w => w.id === id);
|
||||
if (index >= 0) {
|
||||
this._workspaces[index] = { ...this._workspaces[index], ...info };
|
||||
this._updateWorkspaces(this._workspaces);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user