diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 00000000..658d357c --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,55 @@ +name: Release +on: + push: + tags: + - "v*" + +permissions: + contents: write + +jobs: + build-and-release: + name: Build and release + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7.0.1 + + - name: Install pnpm + uses: pnpm/action-setup@v6.0.10 + with: + version: 11.24.0 + run_install: false + + - name: Install Node.js + uses: actions/setup-node@v7.0.0 + with: + node-version: 24.20.0 + cache: pnpm + + - name: Install dependencies + run: pnpm install + + - name: Postinstall steps + run: pnpm svelte-kit sync + working-directory: apps/web + + - name: Build + run: pnpm build + working-directory: apps/web + + - name: Zip build output + # zip the *contents* of build/ (not the folder itself) so index.html + # ends up at the root of the archive + run: | + cd apps/web/build + zip -r "${{ github.workspace }}/ttu-reader-${{ github.ref_name }}.zip" . + + - name: Create release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release create "${{ github.ref_name }}" \ + "ttu-reader-${{ github.ref_name }}.zip" \ + --title "${{ github.ref_name }}" \ + --generate-notes diff --git a/README.md b/README.md index d3a2edb3..52f7204f 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,7 @@ Following export targets are available: | Zip File | Creates an offline archive of the selected data | | GDrive | Allows you to upload and download data to your GDrive account.
Requires a google login - the default session is valid for 50 minutes and requires a manual reauthentication/export afterwards if no custom credentials with a client secret are used.
You can revoke the app permissions any time in your [google security settings](https://myaccount.google.com/permissions) | | OneDrive | Allows you to upload and download data to your OneDrive account.
Requires a microsoft login - the default session is valid for 50 minutes and requires a manual reauthentication/export afterwards if no custom credentials with a client secret are used.
You can revoke the app permissions any time in your [microsoft account privacy settings](https://microsoft.com/consent)
| +| ttsu-sync-server | Allows you to upload and download data to a self hosted [ttsu-sync-server](https://github.com/Minnowo/ttsu-sync-server) instance.
Authenticates with a long lived API key instead of an OAuth login, so there is no reauthentication timeout | | Filesystem | Allows you to store and read data from a configured folder on your hard drive.
You have to grant permissions once per new opened tab.
Only available on desktop chromium browsers - some browser like Brave may need additional flags in the browser settings enabled in order to see/use this option | To export data select books in the manager and click/tap on the respective icon in the header. @@ -416,6 +417,17 @@ To create such custom credentials follow these steps for the hoster you want to 42. Create a new OneDrive source on AJATT Reader with the client id and/or client secret you just have created
+
+ ttsu-sync-server + +ttsu-sync-server is a open source self-hostable server. See the [ttsu-sync-server](https://github.com/Minnowo/ttsu-sync-server) repo for how to build, configure and run the server itself. + +45. Once the server is running, create a user and generate an API key +46. Under `Settings` > `Data` click the `+ Add` button to add a new remote data source +47. Choose `ttsu-sync-server` as the source +48. Enter the server's base URL (e.g. `http://127.0.0.1:8080`) in the "Client ID" field and the API key you generated in the "Client Secret" field. The username is not used by the server, only the API key +
+
You may find following additional controls for storage source settings: @@ -571,3 +583,23 @@ pnpm build ### External Hoster In case you want to use external hoster like GDrive for data import/export follow the steps described in [Storage Sources](#storage-sources) + + +# Dev + +1. Have [Node.js](https://nodejs.org/) and [Yarn](https://classic.yarnpkg.com/) installed +```sh +git clone +``` +2. Install the dependencies +```sh +yarn +``` + +3. Start the dev server: +```sh +yarn dev --host 0.0.0.0 +``` + + + diff --git a/apps/web/src/lib/components/book-card/book-manager-header.svelte b/apps/web/src/lib/components/book-card/book-manager-header.svelte index c60e130f..9dc3a4a7 100644 --- a/apps/web/src/lib/components/book-card/book-manager-header.svelte +++ b/apps/web/src/lib/components/book-card/book-manager-header.svelte @@ -27,6 +27,7 @@ fileCountData$, fsStorageSource$, gDriveStorageSource$, + ttsuSyncServerStorageSource$, isOnline$, oneDriveStorageSource$ } from '$lib/data/store'; @@ -137,6 +138,19 @@ requiresConnectivity: false } ] + : []), + ...(isStorageSourceAvailable( + StorageKey.TTSU_SYNC_SERVER, + $ttsuSyncServerStorageSource$, + window + ) + ? [ + { + label: 'ttsu-sync-server', + key: StorageKey.TTSU_SYNC_SERVER, + requiresConnectivity: true + } + ] : []) ); } diff --git a/apps/web/src/lib/components/book-export/book-export-dialog.svelte b/apps/web/src/lib/components/book-export/book-export-dialog.svelte index 92ecbb46..6d41b6af 100644 --- a/apps/web/src/lib/components/book-export/book-export-dialog.svelte +++ b/apps/web/src/lib/components/book-export/book-export-dialog.svelte @@ -15,7 +15,8 @@ gDriveStorageSource$, lastExportedTarget$, lastExportedTypes$, - oneDriveStorageSource$ + oneDriveStorageSource$, + ttsuSyncServerStorageSource$ } from '$lib/data/store'; import { executeReplicate$ } from '$lib/functions/replication/replication-progress'; import { createEventDispatcher } from 'svelte'; @@ -46,6 +47,19 @@ : []), ...(isStorageSourceAvailable(StorageKey.FS, $fsStorageSource$, window) ? [{ ...getStorageIconData(StorageKey.FS), source: StorageKey.FS, label: 'Filesystem' }] + : []), + ...(isStorageSourceAvailable( + StorageKey.TTSU_SYNC_SERVER, + $ttsuSyncServerStorageSource$, + window + ) + ? [ + { + ...getStorageIconData(StorageKey.TTSU_SYNC_SERVER), + source: StorageKey.TTSU_SYNC_SERVER, + label: 'ttsu-sync-server' + } + ] : []) ].filter((icon) => icon.source !== $storageSource$); } diff --git a/apps/web/src/lib/components/log-report-dialog.svelte b/apps/web/src/lib/components/log-report-dialog.svelte index 97cbcc2b..01037a14 100644 --- a/apps/web/src/lib/components/log-report-dialog.svelte +++ b/apps/web/src/lib/components/log-report-dialog.svelte @@ -49,6 +49,7 @@ showExternalPlaceholder$, gDriveStorageSource$, oneDriveStorageSource$, + ttsuSyncServerStorageSource$, fsStorageSource$, syncTarget$, keepLocalStatisticsOnDeletion$, @@ -148,6 +149,9 @@ gDriveStorageSource$.getValue() === StorageSourceDefault.GDRIVE_DEFAULT, oneDriveStorageSource: oneDriveStorageSource$.getValue() === StorageSourceDefault.ONEDRIVE_DEFAULT, + ttsuSyncServerStorageSource: + ttsuSyncServerStorageSource$.getValue() === + StorageSourceDefault.TTSU_SYNC_SERVER_DEFAULT, fsStorageSource: !!fsStorageSource$.getValue(), syncTarget: !!syncTarget$.getValue(), keepLocalStatisticsOnDeletion: keepLocalStatisticsOnDeletion$.getValue(), diff --git a/apps/web/src/lib/components/settings/settings-storage-source-list.svelte b/apps/web/src/lib/components/settings/settings-storage-source-list.svelte index cca614f2..98560a9d 100644 --- a/apps/web/src/lib/components/settings/settings-storage-source-list.svelte +++ b/apps/web/src/lib/components/settings/settings-storage-source-list.svelte @@ -37,6 +37,7 @@ gDriveStorageSource$, isOnline$, oneDriveStorageSource$, + ttsuSyncServerStorageSource$, syncTarget$ } from '$lib/data/store'; import { AutoReplicationType } from '$lib/functions/replication/replication-options'; @@ -73,6 +74,9 @@ case StorageKey.ONEDRIVE: configuredIsSourceDefault = name === $oneDriveStorageSource$; break; + case StorageKey.TTSU_SYNC_SERVER: + configuredIsSourceDefault = name === $ttsuSyncServerStorageSource$; + break; case StorageKey.FS: configuredIsSourceDefault = name === $fsStorageSource$; break; @@ -258,7 +262,12 @@ {@const storageSourceIsSourceDefault = isStorageSourceDefault( storageSource.name, storageSource.type, - [$gDriveStorageSource$, $oneDriveStorageSource$, $fsStorageSource$] + [ + $gDriveStorageSource$, + $oneDriveStorageSource$, + $ttsuSyncServerStorageSource$, + $fsStorageSource$ + ] )}
diff --git a/apps/web/src/lib/components/settings/settings-storage-source.svelte b/apps/web/src/lib/components/settings/settings-storage-source.svelte index 58d93a3e..d0b58544 100644 --- a/apps/web/src/lib/components/settings/settings-storage-source.svelte +++ b/apps/web/src/lib/components/settings/settings-storage-source.svelte @@ -56,7 +56,8 @@ let storageSourceEncryptionDisabled = configuredEncryptionDisabled || false; let storageSourceTypes = [ { key: StorageKey.GDRIVE, label: 'GDrive' }, - { key: StorageKey.ONEDRIVE, label: 'OneDrive' } + { key: StorageKey.ONEDRIVE, label: 'OneDrive' }, + { key: StorageKey.TTSU_SYNC_SERVER, label: 'ttsu-sync-server' } ]; $: if (browser && 'showDirectoryPicker' in window) { diff --git a/apps/web/src/lib/components/storage-unlock.svelte b/apps/web/src/lib/components/storage-unlock.svelte index 451a60b4..a8cfb775 100644 --- a/apps/web/src/lib/components/storage-unlock.svelte +++ b/apps/web/src/lib/components/storage-unlock.svelte @@ -52,7 +52,9 @@ onMount(() => { skipKeyDownListener$.next(true); - if (passwordElm) { passwordElm.focus() } + if (passwordElm) { + passwordElm.focus(); + } return () => skipKeyDownListener$.next(false); }); @@ -63,7 +65,17 @@
{description}
{action}
{#if requiresSecret} - {if (evt.key === 'Enter') {unlock()}}}/> + { + if (evt.key === 'Enter') { + unlock(); + } + }} + /> {/if}
{error}
diff --git a/apps/web/src/lib/data/storage/handler/api-handler.ts b/apps/web/src/lib/data/storage/handler/api-handler.ts index 00644e9b..fb66f923 100644 --- a/apps/web/src/lib/data/storage/handler/api-handler.ts +++ b/apps/web/src/lib/data/storage/handler/api-handler.ts @@ -21,7 +21,6 @@ import { type ExternalFile } from '$lib/data/storage/handler/base-handler'; import { getStorageHandler } from '$lib/data/storage/storage-handler-factory'; -import { StorageOAuthManager } from '$lib/data/storage/storage-oauth-manager'; import { StorageKey } from '$lib/data/storage/storage-types'; import { database } from '$lib/data/store'; import { @@ -33,8 +32,9 @@ import { ReplicationSaveBehavior } from '$lib/functions/replication/replication- import { replicationProgress$ } from '$lib/functions/replication/replication-progress'; import { mergeStatistics, updateStatisticToStore } from '$lib/functions/statistic-util'; import pLimit from 'p-limit'; +import { AuthType, type StorageAuthManager } from '../storage-auth-manager'; -interface RequestOptions { +export interface RequestOptions { method?: string; headers?: Record; body?: XMLHttpRequestBodyInit | null | undefined; @@ -74,7 +74,7 @@ export abstract class ApiStorageHandler extends BaseStorageHandler { protected abstract executeDelete(id: string): Promise; - protected authManager: StorageOAuthManager; + protected authManager: StorageAuthManager; protected rootId = ''; @@ -82,9 +82,9 @@ export abstract class ApiStorageHandler extends BaseStorageHandler { protected titleToFiles = new Map(); - constructor(storageType: StorageKey, window: Window, refreshEndpoint: string) { + constructor(storageType: StorageKey, window: Window, authManager: StorageAuthManager) { super(window, storageType); - this.authManager = new StorageOAuthManager(this.storageType, refreshEndpoint); + this.authManager = authManager; } updateSettings( @@ -707,7 +707,15 @@ export abstract class ApiStorageHandler extends BaseStorageHandler { } if (token) { - xhr.setRequestHeader('Authorization', `Bearer ${token}`); + switch (this.authManager.getAuthType()) { + case AuthType.BASIC: + xhr.setRequestHeader('Authorization', `Basic ${token}`); + break; + + case AuthType.OAUTH: + xhr.setRequestHeader('Authorization', `Bearer ${token}`); + break; + } } xhr.send(options.body || null); diff --git a/apps/web/src/lib/data/storage/handler/gdrive-handler.ts b/apps/web/src/lib/data/storage/handler/gdrive-handler.ts index 49345995..58f8a380 100644 --- a/apps/web/src/lib/data/storage/handler/gdrive-handler.ts +++ b/apps/web/src/lib/data/storage/handler/gdrive-handler.ts @@ -11,6 +11,7 @@ import { BaseStorageHandler, type ExternalFile } from '$lib/data/storage/handler import { StorageKey } from '$lib/data/storage/storage-types'; import { database, gDriveStorageSource$ } from '$lib/data/store'; import pLimit from 'p-limit'; +import { StorageOAuthManager } from '../storage-oauth-manager'; interface GDriveFile extends ExternalFile { thumbnailLink?: string; @@ -23,7 +24,11 @@ export class GDriveStorageHandler extends ApiStorageHandler { private baseUploadApiUrl = 'https://www.googleapis.com/upload/drive/v3/files'; constructor(window: Window) { - super(StorageKey.GDRIVE, window, gDriveRefreshEndpoint); + super( + StorageKey.GDRIVE, + window, + new StorageOAuthManager(StorageKey.GDRIVE, gDriveRefreshEndpoint) + ); } setInternalSettings(storageSourceName: string) { diff --git a/apps/web/src/lib/data/storage/handler/onedrive-handler.ts b/apps/web/src/lib/data/storage/handler/onedrive-handler.ts index b2411c12..a15ee7c7 100644 --- a/apps/web/src/lib/data/storage/handler/onedrive-handler.ts +++ b/apps/web/src/lib/data/storage/handler/onedrive-handler.ts @@ -11,6 +11,7 @@ import { BaseStorageHandler, type ExternalFile } from '$lib/data/storage/handler import { StorageKey } from '$lib/data/storage/storage-types'; import { database, oneDriveStorageSource$ } from '$lib/data/store'; import pLimit from 'p-limit'; +import { StorageOAuthManager } from '../storage-oauth-manager'; interface OneDriveFile extends ExternalFile { thumbnails?: ExternalThumbnail[]; @@ -54,7 +55,11 @@ export class OneDriveStorageHandler extends ApiStorageHandler { private baseEndpoint = 'https://graph.microsoft.com/v1.0/me/drive/items'; constructor(window: Window) { - super(StorageKey.ONEDRIVE, window, oneDriveTokenEndpoint); + super( + StorageKey.ONEDRIVE, + window, + new StorageOAuthManager(StorageKey.ONEDRIVE, oneDriveTokenEndpoint) + ); } setInternalSettings(storageSourceName: string) { diff --git a/apps/web/src/lib/data/storage/handler/ttsu-sync-server-handler.ts b/apps/web/src/lib/data/storage/handler/ttsu-sync-server-handler.ts new file mode 100644 index 00000000..ac4b9714 --- /dev/null +++ b/apps/web/src/lib/data/storage/handler/ttsu-sync-server-handler.ts @@ -0,0 +1,298 @@ +/** + * @license AGPL-3.0-or-later + * Copyright (c) 2026, Ajatt-Tools and contributors + * All rights reserved. + */ + +import { BaseStorageHandler, type ExternalFile } from './base-handler'; +import type { BookCardProps } from '$lib/components/book-card/book-card-props'; +import { ApiStorageHandler, type RequestOptions } from './api-handler'; +import { database, ttsuSyncServerStorageSource$ } from '$lib/data/store'; +import type { StorageKey } from '../storage-types'; +import { StorageTtsuAuthManager } from '../storage-ttsu-auth-manager'; + +interface TsuFile { + id: string; + parent: string; + name: string; + card: BookCardProps; +} + +export class TtsuSyncServerStorageHandler extends ApiStorageHandler { + private defaultServerRoot = 'http://127.0.0.1:8080'; + + private ttsuAuthManager: StorageTtsuAuthManager; + + constructor(storageType: StorageKey, window: Window) { + const ttsuAuthManager = new StorageTtsuAuthManager(); + + super(storageType, window, ttsuAuthManager); + this.ttsuAuthManager = ttsuAuthManager; + } + + private async reqAny( + path: string, + options: RequestOptions = {}, + typeToRetrieve: XMLHttpRequestResponseType = 'json', + progressBase?: number + ): Promise { + const serverRoot = ( + (await this.ttsuAuthManager.getServerUrl(this.storageSourceName, this.askForStorageUnlock)) || + this.defaultServerRoot + ) + .trim() + .replace(/\/+$/, ''); + + return super.request( + `${serverRoot}/${path}`, + options, + typeToRetrieve, + progressBase + ) as Promise; + } + + protected setInternalSettings(storageSourceName: string): void { + const newStorageSource = storageSourceName || ttsuSyncServerStorageSource$.getValue(); + + if (newStorageSource !== this.storageSourceName) { + this.clearData(); + } + + this.storageSourceName = newStorageSource; + } + + /** + * If there is a file/folder with the given name in the given folder, it's ID is gotten. + * Otherwise it is created and it's ID is gotten. + */ + protected async ensureTitle( + name = BaseStorageHandler.rootName, + parent = 'root', + readOnly = false + ): Promise { + if (name === BaseStorageHandler.rootName && this.rootId) { + return this.rootId; + } + + const externalId = this.titleToId.get(name); + + if (externalId) { + return externalId; + } + + const titleId = await this.reqAny<{ id: string }>('folder', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + name: name, + parent: parent, + readOnly: readOnly + }) + }); + + if (titleId) { + this.titleToId.set(name, titleId.id); + } + + if (titleId && name === BaseStorageHandler.rootName) { + this.rootId = titleId.id; + } + + if (!titleId && name === BaseStorageHandler.rootName) { + throw new Error('Root folder not found'); + } + + return titleId.id; + } + + /** + * Reads a files data. + */ + protected retrieve( + file: TsuFile, + typeToRetrieve: XMLHttpRequestResponseType, + progressBase?: number + ): Promise { + return this.reqAny( + `file/${file.id}`, + { + trackDownload: true, + method: 'GET' + }, + typeToRetrieve, + progressBase + ); + } + + /** + * Deletes a file or folder by ID. + */ + protected async executeDelete(id: string): Promise { + this.reqAny(`delete/${id}`, { + method: 'DELETE' + }); + } + /** + * Get a list of files and folders in the given folder. + */ + private async list(folderId: string) { + return this.reqAny(`list/${folderId}`, { + method: 'GET' + }); + } + + /** + * Uploads or renames a file. + * If an externalFile is given, the remote data is replaced (if data is present), and the file is renamed with the given name. + * If there is no externalFile, a new file will be created in the given folder. + */ + protected async upload( + folderId: string, + name: string, + files: ExternalFile[], + externalFile: ExternalFile | undefined, + data: Blob | string | undefined, + rootFilePrefix?: string, + progressBase?: number + ): Promise { + const form = new FormData(); + + if (externalFile) { + form.append('id', externalFile.id); + } else { + form.append('parent', folderId); + } + + form.append('name', name); + + if (data) { + if (data instanceof Blob) { + form.append('data', data); + } else { + const blob = new Blob([data], { type: 'text/plain' }); + form.append('data', blob); + } + } + + const response = await this.reqAny( + `file`, + { + method: 'POST', + body: form, + trackUpload: true + }, + 'json', + progressBase + ); + + this.updateAfterUpload( + response.id, + response.name, + files, + externalFile, + { + parents: [folderId] + }, + rootFilePrefix + ); + + return response; + } + + protected async getExternalFiles(remoteTitleId: string): Promise { + if ( + (!this.cacheStorageData || !this.dataListFetched) && + !this.titleToFiles.has(this.currentContext.title) + ) { + const externalFiles = await this.list(remoteTitleId); + if (externalFiles.length) { + await this.setTitleData(this.currentContext.title, externalFiles); + } + } + + return this.titleToFiles.get(this.currentContext.title) || []; + } + + protected async setRootFiles(): Promise { + if ((!this.cacheStorageData || !this.rootFileListFetched) && !this.rootFiles.size) { + const rootFiles = await this.list(this.rootId); + + for (const rootFile of rootFiles) { + this.setRootFile(rootFile.name, rootFile); + } + + this.rootFileListFetched = true; + } + } + + async getBookList(): Promise { + if (!this.dataListFetched) { + database.listLoading$.next(true); + + try { + await this.ensureTitle(); + + const bookFolders = await this.list(this.rootId); + + for (const folder of bookFolders) { + const bookFiles = await this.list(folder.id); + await this.setTitleData(folder.name, bookFiles); + } + + this.dataListFetched = true; + } catch (error) { + this.clearData(); + throw error; + } + } + + return [...this.titleToBookCard.values()]; + } + + private async setTitleData(title: string, files: TsuFile[]) { + if (!files.length) { + return; + } + + const bookCard: BookCardProps = { + id: BaseStorageHandler.getDummyId(), + title, + imagePath: '', + characters: 0, + lastBookModified: 0, + lastBookOpen: 0, + progress: 0, + lastBookmarkModified: 0, + isPlaceholder: false + }; + + for (let index = 0, { length } = files; index < length; index += 1) { + const file = files[index]; + + if (file.name.startsWith('bookdata_')) { + const { characters, lastBookModified, lastBookOpen } = BaseStorageHandler.getBookMetadata( + file.name + ); + + bookCard.characters = characters; + bookCard.lastBookModified = lastBookModified; + bookCard.lastBookOpen = lastBookOpen; + } else if (file.name.startsWith('progress_')) { + const { progress, lastBookmarkModified } = BaseStorageHandler.getProgressMetadata( + file.name + ); + + bookCard.progress = progress; + bookCard.lastBookmarkModified = lastBookmarkModified; + } else if (file.name.startsWith('cover_')) { + // doing this because we need auth to read from the server + bookCard.imagePath = (await this.reqAny(`file/${file.id}`, {}, 'blob')) as Blob; + } + } + + this.titleToFiles.set(title, files); + this.titleToBookCard.set(title, bookCard); + } +} diff --git a/apps/web/src/lib/data/storage/storage-auth-manager.ts b/apps/web/src/lib/data/storage/storage-auth-manager.ts new file mode 100644 index 00000000..867e7468 --- /dev/null +++ b/apps/web/src/lib/data/storage/storage-auth-manager.ts @@ -0,0 +1,33 @@ +/** + * @license AGPL-3.0-or-later + * Copyright (c) 2026, Ajatt-Tools and contributors + * All rights reserved. + */ + +import type { BooksDbStorageSource } from '../database/books-db/versions/books-db'; +import type { StorageUnlockAction } from './storage-source-manager'; + +export enum AuthType { + OAUTH = 'oauth', + BASIC = 'basic' +} + +export interface StorageAuthManager { + getAuthType(): AuthType; + + getToken( + window: Window, + storageSourceName: string, + askForStorageUnlock: boolean, + authWindow: Window + ): Promise; + + getToken( + window: Window, + storageSourceName: string, + askForStorageUnlock: boolean, + authWindow?: Window | null, + oldUnlockResult?: StorageUnlockAction, + oldStorageSource?: BooksDbStorageSource | undefined + ): Promise; +} diff --git a/apps/web/src/lib/data/storage/storage-handler-factory.ts b/apps/web/src/lib/data/storage/storage-handler-factory.ts index 4e964fd8..7f7f7b2c 100644 --- a/apps/web/src/lib/data/storage/storage-handler-factory.ts +++ b/apps/web/src/lib/data/storage/storage-handler-factory.ts @@ -14,11 +14,13 @@ import { GDriveStorageHandler } from '$lib/data/storage/handler/gdrive-handler'; import { MergeMode } from '$lib/data/merge-mode'; import { OneDriveStorageHandler } from '$lib/data/storage/handler/onedrive-handler'; import { ReplicationSaveBehavior } from '$lib/functions/replication/replication-options'; +import { TtsuSyncServerStorageHandler } from './handler/ttsu-sync-server-handler'; let backupStorageHandler: BackupStorageHandler; let browserStorageHandler: BrowserStorageHandler; let gDriveStorageHandler: GDriveStorageHandler; let oneDriveStorageHandler: OneDriveStorageHandler; +let ttsuSyncServerStorageHandler: TtsuSyncServerStorageHandler; let fsStorageHandler: FilesystemStorageHandler; export function getStorageHandler( @@ -151,6 +153,22 @@ export function getStorageHandler( ); return oneDriveStorageHandler; + case StorageKey.TTSU_SYNC_SERVER: + ttsuSyncServerStorageHandler = + ttsuSyncServerStorageHandler || + new TtsuSyncServerStorageHandler(StorageKey.TTSU_SYNC_SERVER, window); + ttsuSyncServerStorageHandler.updateSettings( + window, + isForBrowser, + saveBehavior, + statisticsMergeMode, + readingGoalsMergeMode, + cacheStorageData, + askForStorageUnlock, + storageSourceName + ); + + return ttsuSyncServerStorageHandler; case StorageKey.FS: fsStorageHandler = fsStorageHandler || new FilesystemStorageHandler(window, StorageKey.FS); fsStorageHandler.updateSettings( diff --git a/apps/web/src/lib/data/storage/storage-oauth-manager.ts b/apps/web/src/lib/data/storage/storage-oauth-manager.ts index a078c3d1..1cf28c77 100644 --- a/apps/web/src/lib/data/storage/storage-oauth-manager.ts +++ b/apps/web/src/lib/data/storage/storage-oauth-manager.ts @@ -30,6 +30,7 @@ import { StorageSourceDefault, StorageKey } from '$lib/data/storage/storage-type import { database } from '$lib/data/store'; import { convertAuthErrorResponse } from '$lib/functions/replication/error-handler'; import { isMobile } from '$lib/functions/utils'; +import { AuthType, type StorageAuthManager } from './storage-auth-manager'; interface OAuthTokenData { accessToken: string; @@ -40,7 +41,7 @@ interface OAuthTokenData { export const storageOAuthTokens = new Map(); -export class StorageOAuthManager { +export class StorageOAuthManager implements StorageAuthManager { private storageType: StorageKey; private refreshEndpoint; @@ -74,6 +75,10 @@ export class StorageOAuthManager { this.refreshEndpoint = refreshEndpoint; } + getAuthType() { + return AuthType.OAUTH; + } + async getToken( window: Window, storageSourceName: string, diff --git a/apps/web/src/lib/data/storage/storage-source-manager.ts b/apps/web/src/lib/data/storage/storage-source-manager.ts index d120cfb8..45d67e63 100644 --- a/apps/web/src/lib/data/storage/storage-source-manager.ts +++ b/apps/web/src/lib/data/storage/storage-source-manager.ts @@ -9,7 +9,12 @@ import { StorageSourceDefault, internalStorageSourceName } from '$lib/data/storage/storage-types'; -import { fsStorageSource$, gDriveStorageSource$, oneDriveStorageSource$ } from '$lib/data/store'; +import { + fsStorageSource$, + gDriveStorageSource$, + oneDriveStorageSource$, + ttsuSyncServerStorageSource$ +} from '$lib/data/store'; import type { BooksDbStorageSource } from '$lib/data/database/books-db/versions/books-db'; import StorageUnlock from '$lib/components/storage-unlock.svelte'; @@ -65,6 +70,7 @@ export function isAppDefault(name: string) { return ( name === StorageSourceDefault.GDRIVE_DEFAULT || name === StorageSourceDefault.ONEDRIVE_DEFAULT || + name === StorageSourceDefault.TTSU_SYNC_SERVER_DEFAULT || internalStorageSourceName.has(name) ); } @@ -77,6 +83,9 @@ export function setStorageSourceDefault(name: string, type: StorageKey) { case StorageKey.ONEDRIVE: oneDriveStorageSource$.next(name || StorageSourceDefault.ONEDRIVE_DEFAULT); break; + case StorageKey.TTSU_SYNC_SERVER: + ttsuSyncServerStorageSource$.next(name || StorageSourceDefault.TTSU_SYNC_SERVER_DEFAULT); + break; case StorageKey.FS: fsStorageSource$.next(name); break; diff --git a/apps/web/src/lib/data/storage/storage-ttsu-auth-manager.ts b/apps/web/src/lib/data/storage/storage-ttsu-auth-manager.ts new file mode 100644 index 00000000..8c795cc9 --- /dev/null +++ b/apps/web/src/lib/data/storage/storage-ttsu-auth-manager.ts @@ -0,0 +1,89 @@ +/** + * @license AGPL-3.0-or-later + * Copyright (c) 2026, Ajatt-Tools and contributors + * All rights reserved. + */ + +import { + unlockStorageData, + type StorageUnlockAction +} from '$lib/data/storage/storage-source-manager'; +import { database } from '$lib/data/store'; +import { AuthType, type StorageAuthManager } from './storage-auth-manager'; + +// Unlocking can prompt the user for a password, so results are cached per storage +// source across requests, the same way storageOAuthTokens caches OAuth tokens. +// Callers must invalidate an entry (see settings-storage-source(-list).svelte) +// whenever the underlying credentials, server URL, or storage source name change. +export const storageTtsuAuthTokens = new Map(); + +/** + * Auth for the ttsu-sync-server (https://github.com/Minnowo/ttsu-sync-server). + * The server ignores the Basic Auth username and treats the password as an API + * key, so the client ID field is repurposed here to hold the server URL. + */ +export class StorageTtsuAuthManager implements StorageAuthManager { + getAuthType(): AuthType { + return AuthType.BASIC; + } + + async getServerUrl( + storageSourceName: string, + askForStorageUnlock: boolean + ): Promise { + const unlockResult = await this.unlock(storageSourceName, askForStorageUnlock); + + return unlockResult?.clientId; + } + + async getToken( + _window: Window, + storageSourceName: string, + askForStorageUnlock: boolean, + _authWindow: Window + ): Promise { + const unlockResult = await this.unlock(storageSourceName, askForStorageUnlock); + + if (!unlockResult) { + throw new Error(`Unable to unlock required data`); + } + + return btoa(`ttsu-client:${unlockResult.clientSecret}`); + } + + private async unlock( + storageSourceName: string, + askForStorageUnlock: boolean + ): Promise { + const cached = storageTtsuAuthTokens.get(storageSourceName); + + if (cached) { + return cached; + } + + const db = await database.db; + const storageSource = await db.get('storageSource', storageSourceName); + + if (!storageSource) { + throw new Error(`No storage source with name ${storageSourceName} found`); + } + + const unlockResult = await unlockStorageData( + storageSource, + 'You are trying to access protected data', + askForStorageUnlock + ? { + action: `Enter the correct password for ${storageSourceName} and login to your account if required to proceed`, + encryptedData: storageSource.data, + forwardSecret: true + } + : undefined + ); + + if (unlockResult) { + storageTtsuAuthTokens.set(storageSourceName, unlockResult); + } + + return unlockResult; + } +} diff --git a/apps/web/src/lib/data/storage/storage-types.ts b/apps/web/src/lib/data/storage/storage-types.ts index 749e0371..11897621 100644 --- a/apps/web/src/lib/data/storage/storage-types.ts +++ b/apps/web/src/lib/data/storage/storage-types.ts @@ -9,7 +9,8 @@ export enum StorageKey { BROWSER = 'browser', FS = 'fs', GDRIVE = 'gdrive', - ONEDRIVE = 'onedrive' + ONEDRIVE = 'onedrive', + TTSU_SYNC_SERVER = 'ttsu-sync-server' } export enum StorageDataType { @@ -23,7 +24,8 @@ export enum StorageDataType { export enum StorageSourceDefault { GDRIVE_DEFAULT = 'ttu-gdrive-default', - ONEDRIVE_DEFAULT = 'ttu-onedrive-default' + ONEDRIVE_DEFAULT = 'ttu-onedrive-default', + TTSU_SYNC_SERVER_DEFAULT = 'ttu-ttsu-sync-server-default' } export enum InternalStorageSources { diff --git a/apps/web/src/lib/data/storage/storage-view.ts b/apps/web/src/lib/data/storage/storage-view.ts index 0a3780c8..1b04ff4e 100644 --- a/apps/web/src/lib/data/storage/storage-view.ts +++ b/apps/web/src/lib/data/storage/storage-view.ts @@ -55,6 +55,12 @@ export function isStorageSourceAvailable( oneDriveScope; break; + case StorageKey.TTSU_SYNC_SERVER: + hasValidEnvironment = + !!storageSourceManager && + storageSourceManager !== StorageSourceDefault.TTSU_SYNC_SERVER_DEFAULT; + break; + case StorageKey.FS: hasValidEnvironment = !!storageSourceManager && 'showDirectoryPicker' in window; break; diff --git a/apps/web/src/lib/data/store.ts b/apps/web/src/lib/data/store.ts index 55913f16..cb541bd6 100644 --- a/apps/web/src/lib/data/store.ts +++ b/apps/web/src/lib/data/store.ts @@ -238,6 +238,10 @@ export const oneDriveStorageSource$ = writableStringLocalStorageSubject()( 'oneDriveStorageSource', StorageSourceDefault.ONEDRIVE_DEFAULT ); +export const ttsuSyncServerStorageSource$ = writableStringLocalStorageSubject()( + 'ttsuSyncServerStorageSource', + StorageSourceDefault.TTSU_SYNC_SERVER_DEFAULT +); export const fsStorageSource$ = writableStringLocalStorageSubject()('fsStorageSource', ''); @@ -499,6 +503,7 @@ export const booklistSortOptions$ = writableObjectLocalStorageSubject