mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 01:12:16 +00:00
refactor(vacay, admin, doc-sync): async DB-touching methods; transactions through UnitOfWork
This commit is contained in:
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
|
||||
import crypto from 'crypto';
|
||||
import { DOCSYNC_SECRET_MASK, type DocsyncConnectionInput, type DocsyncLinkInput } from '@trek/shared';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { checkSsrf } from '../../utils/ssrfGuard';
|
||||
import { DocumentProviderRegistry } from './document-provider.registry';
|
||||
import type { DocumentConnectionRef, DocumentScopeRef, DocResult } from './document-provider';
|
||||
@@ -86,19 +87,20 @@ export class DocSyncConfigService {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly registry: DocumentProviderRegistry,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
// ── Provider metadata ──────────────────────────────────────────────────────
|
||||
|
||||
/** Only providers the instance admin switched on may be configured. */
|
||||
enabledProviderIds(): string[] {
|
||||
async enabledProviderIds(): Promise<string[]> {
|
||||
return this.db.connection
|
||||
.prepare('SELECT id FROM document_providers WHERE enabled = 1 ORDER BY sort_order')
|
||||
.all()
|
||||
.map((r) => (r as { id: string }).id);
|
||||
}
|
||||
|
||||
providerFields(providerId: string): ProviderFieldRow[] {
|
||||
async providerFields(providerId: string): Promise<ProviderFieldRow[]> {
|
||||
// Every column the form needs, not just the three the secret bookkeeping
|
||||
// uses: the client renders the field from this row, and a missing `label`
|
||||
// turns into a literal "docsync.undefined" on screen.
|
||||
@@ -110,8 +112,8 @@ export class DocSyncConfigService {
|
||||
.all(providerId) as ProviderFieldRow[];
|
||||
}
|
||||
|
||||
private secretKeys(providerId: string): string[] {
|
||||
return this.providerFields(providerId).filter((f) => f.secret === 1).map((f) => f.field_key);
|
||||
private async secretKeys(providerId: string): Promise<string[]> {
|
||||
return (await this.providerFields(providerId)).filter((f) => f.secret === 1).map((f) => f.field_key);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,7 +121,7 @@ export class DocSyncConfigService {
|
||||
* admin switching its provider off, and the client only gets names for the
|
||||
* providers that are still on, so without this it would show the raw id.
|
||||
*/
|
||||
private providerName(providerId: string): string {
|
||||
private async providerName(providerId: string): Promise<string> {
|
||||
const row = this.db.connection
|
||||
.prepare('SELECT name FROM document_providers WHERE id = ?')
|
||||
.get(providerId) as { name: string } | undefined;
|
||||
@@ -128,11 +130,11 @@ export class DocSyncConfigService {
|
||||
|
||||
// ── Connections ────────────────────────────────────────────────────────────
|
||||
|
||||
getConnection(id: number): ConnectionRow | undefined {
|
||||
async getConnection(id: number): Promise<ConnectionRow | undefined> {
|
||||
return this.db.connection.prepare('SELECT * FROM document_connections WHERE id = ?').get(id) as ConnectionRow | undefined;
|
||||
}
|
||||
|
||||
listConnections(tripId: number): ConnectionRow[] {
|
||||
async listConnections(tripId: number): Promise<ConnectionRow[]> {
|
||||
return this.db.connection
|
||||
.prepare('SELECT * FROM document_connections WHERE trip_id = ? ORDER BY id')
|
||||
.all(tripId) as ConnectionRow[];
|
||||
@@ -183,9 +185,9 @@ export class DocSyncConfigService {
|
||||
* caller's ref: a sync run holds its ref for minutes, and writing that
|
||||
* snapshot back would undo a password the owner changed in the meantime.
|
||||
*/
|
||||
saveEarnedSecret(connectionId: number, key: string, value: string | null): void {
|
||||
this.db.transaction(() => {
|
||||
const row = this.getConnection(connectionId);
|
||||
async saveEarnedSecret(connectionId: number, key: string, value: string | null): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
const row = await this.getConnection(connectionId);
|
||||
if (!row) return;
|
||||
const secrets = decryptSecrets(row.secrets);
|
||||
if (value === null) delete secrets[key];
|
||||
@@ -197,7 +199,7 @@ export class DocSyncConfigService {
|
||||
}
|
||||
|
||||
/** What a client may see: no secret values, only whether each one is set. */
|
||||
publicConnection(row: ConnectionRow): Record<string, unknown> {
|
||||
async publicConnection(row: ConnectionRow): Promise<Record<string, unknown>> {
|
||||
const ref = this.toRef(row);
|
||||
return {
|
||||
id: row.id,
|
||||
@@ -206,7 +208,7 @@ export class DocSyncConfigService {
|
||||
ownerUserId: row.owner_user_id,
|
||||
baseUrl: row.base_url,
|
||||
settings: ref.settings,
|
||||
secrets: maskSecrets(ref.secrets, this.secretKeys(row.provider_id)),
|
||||
secrets: maskSecrets(ref.secrets, await this.secretKeys(row.provider_id)),
|
||||
allowInsecureTls: row.allow_insecure_tls === 1,
|
||||
capabilities: row.capabilities ? safeParse(row.capabilities) : null,
|
||||
lastProbeAt: row.last_probe_at,
|
||||
@@ -266,7 +268,7 @@ export class DocSyncConfigService {
|
||||
const urlCheck = await this.validateBaseUrl(input.baseUrl);
|
||||
if (docFailed(urlCheck)) return { success: false, error: urlCheck.error };
|
||||
|
||||
const fields = this.providerFields(input.providerId);
|
||||
const fields = await this.providerFields(input.providerId);
|
||||
const secretKeys = fields.filter((f) => f.secret === 1).map((f) => f.field_key);
|
||||
const plainKeys = fields.filter((f) => f.secret !== 1).map((f) => f.field_key);
|
||||
|
||||
@@ -316,7 +318,7 @@ export class DocSyncConfigService {
|
||||
const settingsJson = JSON.stringify(settings);
|
||||
const insecure = input.allowInsecureTls ? 1 : 0;
|
||||
|
||||
const row = this.db.transaction(() => {
|
||||
const row = await this.uow.transactional(async () => {
|
||||
if (existing) {
|
||||
this.db.connection
|
||||
.prepare(
|
||||
@@ -326,7 +328,7 @@ export class DocSyncConfigService {
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.run(urlCheck.data.url, encrypted, settingsJson, insecure, ownerId, existing.id);
|
||||
return this.getConnection(existing.id) as ConnectionRow;
|
||||
return (await this.getConnection(existing.id)) as ConnectionRow;
|
||||
}
|
||||
const info = this.db.connection
|
||||
.prepare(
|
||||
@@ -334,13 +336,13 @@ export class DocSyncConfigService {
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(tripId, input.providerId, userId, urlCheck.data.url, encrypted, settingsJson, insecure);
|
||||
return this.getConnection(Number(info.lastInsertRowid)) as ConnectionRow;
|
||||
return (await this.getConnection(Number(info.lastInsertRowid))) as ConnectionRow;
|
||||
});
|
||||
|
||||
return { success: true, data: row };
|
||||
}
|
||||
|
||||
recordProbe(connectionId: number, state: 'ok' | 'failed', error: string | null, capabilities: unknown): void {
|
||||
async recordProbe(connectionId: number, state: 'ok' | 'failed', error: string | null, capabilities: unknown): Promise<void> {
|
||||
this.db.connection
|
||||
.prepare(
|
||||
`UPDATE document_connections
|
||||
@@ -356,23 +358,23 @@ export class DocSyncConfigService {
|
||||
* more: the same promise Dawarich's disconnect makes, and the only version
|
||||
* of this action that is safe to offer without a confirmation dialog.
|
||||
*/
|
||||
deleteConnection(id: number): void {
|
||||
async deleteConnection(id: number): Promise<void> {
|
||||
this.db.connection.prepare('DELETE FROM document_connections WHERE id = ?').run(id);
|
||||
}
|
||||
|
||||
// ── Trip bindings ──────────────────────────────────────────────────────────
|
||||
|
||||
listLinks(tripId: number): LinkRow[] {
|
||||
async listLinks(tripId: number): Promise<LinkRow[]> {
|
||||
return this.db.connection
|
||||
.prepare('SELECT * FROM trip_document_links WHERE trip_id = ? ORDER BY id')
|
||||
.all(tripId) as LinkRow[];
|
||||
}
|
||||
|
||||
getLink(id: number): LinkRow | undefined {
|
||||
async getLink(id: number): Promise<LinkRow | undefined> {
|
||||
return this.db.connection.prepare('SELECT * FROM trip_document_links WHERE id = ?').get(id) as LinkRow | undefined;
|
||||
}
|
||||
|
||||
getLinkByToken(token: string): LinkRow | undefined {
|
||||
async getLinkByToken(token: string): Promise<LinkRow | undefined> {
|
||||
return this.db.connection
|
||||
.prepare('SELECT * FROM trip_document_links WHERE webhook_token = ?')
|
||||
.get(token) as LinkRow | undefined;
|
||||
@@ -397,8 +399,8 @@ export class DocSyncConfigService {
|
||||
* still goes through the connection's own credential, so it cannot open
|
||||
* anything that credential could not open anyway.
|
||||
*/
|
||||
createLink(tripId: number, userId: number, input: DocsyncLinkInput): DocResult<LinkRow> {
|
||||
const conn = this.getConnection(input.connectionId);
|
||||
async createLink(tripId: number, userId: number, input: DocsyncLinkInput): Promise<DocResult<LinkRow>> {
|
||||
const conn = await this.getConnection(input.connectionId);
|
||||
if (!conn || conn.trip_id !== tripId) {
|
||||
return { success: false, error: { code: 'not_found', detail: 'connection not found for this trip' } };
|
||||
}
|
||||
@@ -436,18 +438,18 @@ export class DocSyncConfigService {
|
||||
String(encryptSecrets({ webhook: secret })),
|
||||
userId,
|
||||
);
|
||||
return { success: true, data: this.getLink(Number(info.lastInsertRowid)) as LinkRow };
|
||||
return { success: true, data: (await this.getLink(Number(info.lastInsertRowid))) as LinkRow };
|
||||
}
|
||||
|
||||
updateLink(id: number, patch: Partial<DocsyncLinkInput>): LinkRow | undefined {
|
||||
async updateLink(id: number, patch: Partial<DocsyncLinkInput>): Promise<LinkRow | undefined> {
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
// Sync automatically is the way back for an orphaned binding, but only once
|
||||
// the person whose credential it runs under is on the trip again. Until
|
||||
// then the switch stays off rather than handing that credential back.
|
||||
const current = patch.syncEnabled === true ? this.getLink(id) : undefined;
|
||||
const current = patch.syncEnabled === true ? await this.getLink(id) : undefined;
|
||||
if (current?.last_sync_state === 'orphaned') {
|
||||
if (this.ownerLeft(current.connection_id)) patch = { ...patch, syncEnabled: undefined };
|
||||
if (await this.ownerLeft(current.connection_id)) patch = { ...patch, syncEnabled: undefined };
|
||||
else sets.push("last_sync_state = 'never'");
|
||||
}
|
||||
if (patch.direction !== undefined) { sets.push('direction = ?'); values.push(patch.direction); }
|
||||
@@ -455,10 +457,10 @@ export class DocSyncConfigService {
|
||||
if (patch.conflictPolicy !== undefined) { sets.push('conflict_policy = ?'); values.push(patch.conflictPolicy); }
|
||||
if (patch.syncEnabled !== undefined) { sets.push('sync_enabled = ?'); values.push(patch.syncEnabled ? 1 : 0); }
|
||||
if (patch.remoteLabel !== undefined) { sets.push('remote_label = ?'); values.push(patch.remoteLabel); }
|
||||
if (sets.length === 0) return this.getLink(id);
|
||||
if (sets.length === 0) return await this.getLink(id);
|
||||
sets.push('updated_at = CURRENT_TIMESTAMP');
|
||||
this.db.connection.prepare(`UPDATE trip_document_links SET ${sets.join(', ')} WHERE id = ?`).run(...values, id);
|
||||
return this.getLink(id);
|
||||
return await this.getLink(id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -466,8 +468,8 @@ export class DocSyncConfigService {
|
||||
* document on either side. A user who wants that does it deliberately, in
|
||||
* the system that holds the file.
|
||||
*/
|
||||
deleteLink(id: number): void {
|
||||
this.db.transaction(() => {
|
||||
async deleteLink(id: number): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.connection.prepare('DELETE FROM document_sync_items WHERE link_id = ?').run(id);
|
||||
this.db.connection.prepare('DELETE FROM trip_document_links WHERE id = ?').run(id);
|
||||
});
|
||||
@@ -478,13 +480,13 @@ export class DocSyncConfigService {
|
||||
}
|
||||
|
||||
/** The masked view a client gets, with the webhook URL it may need to paste. */
|
||||
publicLink(link: LinkRow, webhookBaseUrl: string | null): Record<string, unknown> {
|
||||
async publicLink(link: LinkRow, webhookBaseUrl: string | null): Promise<Record<string, unknown>> {
|
||||
return {
|
||||
id: link.id,
|
||||
tripId: link.trip_id,
|
||||
connectionId: link.connection_id,
|
||||
providerId: link.provider_id,
|
||||
providerName: this.providerName(link.provider_id),
|
||||
providerName: await this.providerName(link.provider_id),
|
||||
scopeKey: link.remote_scope_key,
|
||||
remoteRootId: link.remote_root_id,
|
||||
remoteRootPath: link.remote_root_path,
|
||||
@@ -501,7 +503,7 @@ export class DocSyncConfigService {
|
||||
// subscribe on its own (Papra, and Nextcloud without admin rights). Not
|
||||
// for a provider that takes no webhook at all: an address with nowhere
|
||||
// to paste it only promises what the timer delivers anyway.
|
||||
webhookUrl: webhookBaseUrl && link.webhook_token && this.takesWebhook(link)
|
||||
webhookUrl: webhookBaseUrl && link.webhook_token && (await this.takesWebhook(link))
|
||||
? `${webhookBaseUrl}/api/docsync/webhook/${link.webhook_token}`
|
||||
: null,
|
||||
webhookSecret: link.webhook_secret ? DOCSYNC_SECRET_MASK : null,
|
||||
@@ -513,8 +515,8 @@ export class DocSyncConfigService {
|
||||
* recorded it. Unknown counts as yes: a connection that was never probed
|
||||
* still gets the address, and a stale answer costs nothing but a line.
|
||||
*/
|
||||
private takesWebhook(link: LinkRow): boolean {
|
||||
const recorded = this.getConnection(link.connection_id)?.capabilities;
|
||||
private async takesWebhook(link: LinkRow): Promise<boolean> {
|
||||
const recorded = (await this.getConnection(link.connection_id))?.capabilities;
|
||||
const caps = recorded ? safeParse(recorded) : null;
|
||||
return !(caps && typeof caps === 'object' && (caps as { push?: unknown }).push === 'none');
|
||||
}
|
||||
@@ -525,11 +527,11 @@ export class DocSyncConfigService {
|
||||
* marked; every path that starts a run asks here rather than reading the
|
||||
* mark alone.
|
||||
*/
|
||||
isOrphaned(link: LinkRow): boolean {
|
||||
return link.last_sync_state === 'orphaned' || this.ownerLeft(link.connection_id);
|
||||
async isOrphaned(link: LinkRow): Promise<boolean> {
|
||||
return link.last_sync_state === 'orphaned' || (await this.ownerLeft(link.connection_id));
|
||||
}
|
||||
|
||||
private ownerLeft(connectionId: number): boolean {
|
||||
private async ownerLeft(connectionId: number): Promise<boolean> {
|
||||
return !!this.db.connection
|
||||
.prepare(
|
||||
`SELECT 1 FROM document_connections c
|
||||
@@ -550,7 +552,7 @@ export class DocSyncConfigService {
|
||||
* and a binding that keeps using an ex-member's token is the kind of thing
|
||||
* nobody notices until it is a complaint.
|
||||
*/
|
||||
markOrphanedLinks(): number {
|
||||
async markOrphanedLinks(): Promise<number> {
|
||||
const info = this.db.connection
|
||||
.prepare(
|
||||
`UPDATE trip_document_links
|
||||
|
||||
@@ -74,7 +74,7 @@ export class DocSyncWebhookController implements OnModuleDestroy {
|
||||
@Public('A provider cannot hold a TREK session; the per-link token in the URL is the authentication, and the call can only ever trigger a sync run.')
|
||||
@HttpCode(200)
|
||||
async nudge(@Param('token') token: string, @Req() req: Request) {
|
||||
const link = this.config.getLinkByToken(token);
|
||||
const link = await this.config.getLinkByToken(token);
|
||||
// Always 200, even for an unknown token: a 404 here would let anyone probe
|
||||
// which tokens exist, and a provider that gets an error will retry anyway.
|
||||
if (!link || link.sync_enabled !== 1) return { received: true };
|
||||
@@ -115,7 +115,7 @@ export class DocSyncWebhookController implements OnModuleDestroy {
|
||||
const timer = setTimeout(() => {
|
||||
void (async () => {
|
||||
this.pending.delete(linkId);
|
||||
const fresh = reload();
|
||||
const fresh = await reload();
|
||||
if (!fresh || fresh.sync_enabled !== 1) return;
|
||||
if (!(await this.syncIsOn(fresh))) return;
|
||||
void this.sync.syncLink(fresh).then((res) => {
|
||||
|
||||
@@ -98,7 +98,7 @@ export class DocSyncController {
|
||||
* The 403 still says "owner": an admin never sees it, and to everybody who
|
||||
* does, the owner is the person to ask.
|
||||
*/
|
||||
private assertCanManage(tripId: string, user: User): void {
|
||||
private async assertCanManage(tripId: string, user: User): Promise<void> {
|
||||
if (user.role === 'admin') return;
|
||||
const trip = this.db.get<{ user_id: number }>('SELECT user_id FROM trips WHERE id = ?', tripId);
|
||||
if (!trip) throw new HttpException('Trip not found', 404);
|
||||
@@ -111,17 +111,19 @@ export class DocSyncController {
|
||||
|
||||
/** Which providers this instance has switched on, with their form fields. */
|
||||
@Get('providers')
|
||||
providers() {
|
||||
async providers() {
|
||||
const rows = this.db.connection
|
||||
.prepare('SELECT id, name, description, icon FROM document_providers WHERE enabled = 1 ORDER BY sort_order')
|
||||
.all() as Array<{ id: string; name: string; description: string | null; icon: string }>;
|
||||
return rows.map((p) => ({
|
||||
...p,
|
||||
// A provider row with no registered adapter would render a form that
|
||||
// cannot work, so it is reported rather than hidden.
|
||||
available: !!this.registry.get(p.id),
|
||||
fields: this.config.providerFields(p.id).map((f) => ({ ...f, secret: f.secret === 1, required: f.required === 1 })),
|
||||
}));
|
||||
return await Promise.all(
|
||||
rows.map(async (p) => ({
|
||||
...p,
|
||||
// A provider row with no registered adapter would render a form that
|
||||
// cannot work, so it is reported rather than hidden.
|
||||
available: !!this.registry.get(p.id),
|
||||
fields: (await this.config.providerFields(p.id)).map((f) => ({ ...f, secret: f.secret === 1, required: f.required === 1 })),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
@Get('status')
|
||||
@@ -132,8 +134,9 @@ export class DocSyncController {
|
||||
// ── Connections ────────────────────────────────────────────────────────────
|
||||
|
||||
@Get('connections')
|
||||
listConnections(@Param('tripId') tripId: string) {
|
||||
return this.config.listConnections(Number(tripId)).map((c) => this.config.publicConnection(c));
|
||||
async listConnections(@Param('tripId') tripId: string) {
|
||||
const rows = await this.config.listConnections(Number(tripId));
|
||||
return await Promise.all(rows.map((c) => this.config.publicConnection(c)));
|
||||
}
|
||||
|
||||
@Put('connections')
|
||||
@@ -143,8 +146,8 @@ export class DocSyncController {
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: DocsyncConnectionDto,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
if (!this.config.enabledProviderIds().includes(body.providerId)) {
|
||||
await this.assertCanManage(tripId, user);
|
||||
if (!(await this.config.enabledProviderIds()).includes(body.providerId)) {
|
||||
throw new HttpException(`Provider: "${body.providerId}" is not enabled, contact server administrator`, 400);
|
||||
}
|
||||
const res = await this.config.upsertConnection(Number(tripId), Number(user.id), body);
|
||||
@@ -164,7 +167,7 @@ export class DocSyncController {
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: DocsyncConnectionTestDto,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
await this.assertCanManage(tripId, user);
|
||||
const provider = this.registry.get(body.providerId);
|
||||
if (!provider) return { connected: false, error: 'unknown_provider' };
|
||||
|
||||
@@ -173,9 +176,9 @@ export class DocSyncController {
|
||||
|
||||
// Probing with the values on screen, merged over whatever is stored, so a
|
||||
// user testing an unchanged connection does not have to retype the secret.
|
||||
const existing = this.config
|
||||
.listConnections(Number(tripId))
|
||||
.find((c) => c.provider_id === body.providerId);
|
||||
const existing = (await this.config.listConnections(Number(tripId))).find(
|
||||
(c) => c.provider_id === body.providerId,
|
||||
);
|
||||
// Only for the address the credential was stored against. Merging it into a
|
||||
// probe of an arbitrary baseUrl turns this route into a way to have TREK
|
||||
// post a stored API token at a server of the caller's choosing, which is
|
||||
@@ -183,7 +186,7 @@ export class DocSyncController {
|
||||
// reach for. Same host, same scheme, same port, or the caller types it in.
|
||||
const sameTarget = !!existing && sameOrigin(existing.base_url, urlCheck.data.url);
|
||||
const stored = sameTarget && existing ? this.config.toRef(existing) : null;
|
||||
const fields = this.config.providerFields(body.providerId);
|
||||
const fields = await this.config.providerFields(body.providerId);
|
||||
const secrets: Record<string, string> = { ...(stored?.secrets ?? {}) };
|
||||
const settings: Record<string, string> = { ...(stored?.settings ?? {}) };
|
||||
for (const f of fields) {
|
||||
@@ -203,7 +206,7 @@ export class DocSyncController {
|
||||
allowInsecureTls: body.allowInsecureTls,
|
||||
});
|
||||
if (docFailed(res)) return { connected: false, error: res.error.code, detail: res.error.detail };
|
||||
if (existing) this.config.recordProbe(existing.id, 'ok', null, res.data.capabilities);
|
||||
if (existing) await this.config.recordProbe(existing.id, 'ok', null, res.data.capabilities);
|
||||
return { connected: true, account: res.data.account, capabilities: res.data.capabilities };
|
||||
}
|
||||
|
||||
@@ -214,15 +217,15 @@ export class DocSyncController {
|
||||
@Param('connectionId') connectionId: string,
|
||||
@CurrentUser() user: User,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
const conn = this.config.getConnection(Number(connectionId));
|
||||
await this.assertCanManage(tripId, user);
|
||||
const conn = await this.config.getConnection(Number(connectionId));
|
||||
if (!conn || conn.trip_id !== Number(tripId)) throw new HttpException('Connection not found', 404);
|
||||
// Its bindings go with it (ON DELETE CASCADE), so read them first. Every
|
||||
// subscription TREK registered for one of them is taken down while the
|
||||
// credential is still here to do it with, as unbinding one does: left
|
||||
// standing, a Paperless workflow or a Nextcloud listener keeps posting to
|
||||
// a token that answers nothing, for good.
|
||||
const unbound = this.config.listLinks(conn.trip_id).filter((l) => l.connection_id === conn.id);
|
||||
const unbound = (await this.config.listLinks(conn.trip_id)).filter((l) => l.connection_id === conn.id);
|
||||
const provider = this.registry.get(conn.provider_id);
|
||||
if (provider?.unregisterWebhook) {
|
||||
const ref = this.config.toRef(conn);
|
||||
@@ -230,7 +233,7 @@ export class DocSyncController {
|
||||
if (link.webhook_subscription_id) await provider.unregisterWebhook(ref, link.webhook_subscription_id);
|
||||
}
|
||||
}
|
||||
this.config.deleteConnection(conn.id);
|
||||
await this.config.deleteConnection(conn.id);
|
||||
for (const link of unbound) this.announceBinding(link);
|
||||
return { success: true };
|
||||
}
|
||||
@@ -245,8 +248,8 @@ export class DocSyncController {
|
||||
@CurrentUser() user: User,
|
||||
@Query('q') q?: string,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
const conn = this.config.getConnection(Number(connectionId));
|
||||
await this.assertCanManage(tripId, user);
|
||||
const conn = await this.config.getConnection(Number(connectionId));
|
||||
if (!conn || conn.trip_id !== Number(tripId)) throw new HttpException('Connection not found', 404);
|
||||
const provider = this.registry.get(conn.provider_id);
|
||||
if (!provider) throw new HttpException('Provider not available', 400);
|
||||
@@ -262,8 +265,8 @@ export class DocSyncController {
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: DocsyncScopeCreateDto,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
const conn = this.config.getConnection(Number(connectionId));
|
||||
await this.assertCanManage(tripId, user);
|
||||
const conn = await this.config.getConnection(Number(connectionId));
|
||||
if (!conn || conn.trip_id !== Number(tripId)) throw new HttpException('Connection not found', 404);
|
||||
const provider = this.registry.get(conn.provider_id);
|
||||
if (!provider) throw new HttpException('Provider not available', 400);
|
||||
@@ -275,9 +278,10 @@ export class DocSyncController {
|
||||
// ── Bindings ───────────────────────────────────────────────────────────────
|
||||
|
||||
@Get('links')
|
||||
listLinks(@Param('tripId') tripId: string, @Req() req: Request) {
|
||||
async listLinks(@Param('tripId') tripId: string, @Req() req: Request) {
|
||||
const base = publicOrigin(req);
|
||||
return this.config.listLinks(Number(tripId)).map((l) => this.config.publicLink(l, base));
|
||||
const rows = await this.config.listLinks(Number(tripId));
|
||||
return await Promise.all(rows.map((l) => this.config.publicLink(l, base)));
|
||||
}
|
||||
|
||||
@Post('links')
|
||||
@@ -288,8 +292,8 @@ export class DocSyncController {
|
||||
@Body() body: DocsyncLinkDto,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
const res = this.config.createLink(Number(tripId), Number(user.id), body);
|
||||
await this.assertCanManage(tripId, user);
|
||||
const res = await this.config.createLink(Number(tripId), Number(user.id), body);
|
||||
if (docFailed(res)) throw new HttpException(res.error.detail || res.error.code, 400);
|
||||
this.announceBinding(res.data);
|
||||
|
||||
@@ -297,7 +301,7 @@ export class DocSyncController {
|
||||
// not a failure of the binding (polling still carries it), so it is logged
|
||||
// rather than thrown at the user; the first run that follows would write
|
||||
// over anything put into the link state.
|
||||
const conn = this.config.getConnection(res.data.connection_id);
|
||||
const conn = await this.config.getConnection(res.data.connection_id);
|
||||
const provider = conn ? this.registry.get(conn.provider_id) : undefined;
|
||||
if (conn && provider?.registerWebhook) {
|
||||
const base = publicOrigin(req);
|
||||
@@ -323,23 +327,23 @@ export class DocSyncController {
|
||||
// A first run right away, so the user sees something happen instead of
|
||||
// waiting out a poll interval and wondering whether it worked.
|
||||
void this.sync.syncLink(res.data, { full: true });
|
||||
return this.config.publicLink(this.config.getLink(res.data.id) ?? res.data, publicOrigin(req));
|
||||
return await this.config.publicLink((await this.config.getLink(res.data.id)) ?? res.data, publicOrigin(req));
|
||||
}
|
||||
|
||||
@Patch('links/:linkId')
|
||||
@HttpCode(200)
|
||||
updateLink(
|
||||
async updateLink(
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('linkId') linkId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: DocsyncLinkUpdateDto,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
const link = this.config.getLink(Number(linkId));
|
||||
await this.assertCanManage(tripId, user);
|
||||
const link = await this.config.getLink(Number(linkId));
|
||||
if (!link || link.trip_id !== Number(tripId)) throw new HttpException('Link not found', 404);
|
||||
const updated = this.config.updateLink(link.id, body);
|
||||
return this.config.publicLink(updated ?? link, publicOrigin(req));
|
||||
const updated = await this.config.updateLink(link.id, body);
|
||||
return await this.config.publicLink(updated ?? link, publicOrigin(req));
|
||||
}
|
||||
|
||||
@Delete('links/:linkId')
|
||||
@@ -349,16 +353,16 @@ export class DocSyncController {
|
||||
@Param('linkId') linkId: string,
|
||||
@CurrentUser() user: User,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
const link = this.config.getLink(Number(linkId));
|
||||
await this.assertCanManage(tripId, user);
|
||||
const link = await this.config.getLink(Number(linkId));
|
||||
if (!link || link.trip_id !== Number(tripId)) throw new HttpException('Link not found', 404);
|
||||
|
||||
const conn = this.config.getConnection(link.connection_id);
|
||||
const conn = await this.config.getConnection(link.connection_id);
|
||||
const provider = conn ? this.registry.get(conn.provider_id) : undefined;
|
||||
if (conn && provider?.unregisterWebhook && link.webhook_subscription_id) {
|
||||
await provider.unregisterWebhook(this.config.toRef(conn), link.webhook_subscription_id);
|
||||
}
|
||||
this.config.deleteLink(link.id);
|
||||
await this.config.deleteLink(link.id);
|
||||
this.announceBinding(link);
|
||||
// Unbinding keeps both copies. Nothing is deleted anywhere.
|
||||
return { success: true, documentsKept: true };
|
||||
@@ -371,12 +375,12 @@ export class DocSyncController {
|
||||
@Param('linkId') linkId: string,
|
||||
@Body() body: DocsyncSyncNowDto,
|
||||
) {
|
||||
const link = this.config.getLink(Number(linkId));
|
||||
const link = await this.config.getLink(Number(linkId));
|
||||
if (!link || link.trip_id !== Number(tripId)) throw new HttpException('Link not found', 404);
|
||||
// An orphaned binding stays orphaned: its credential belongs to somebody who
|
||||
// is no longer on this trip. The run itself would stand down as well; this
|
||||
// says why, instead of answering with an empty run.
|
||||
if (this.config.isOrphaned(link)) {
|
||||
if (await this.config.isOrphaned(link)) {
|
||||
throw new HttpException({ error: 'This binding lost its owner and has to be reconnected' }, 409);
|
||||
}
|
||||
// Refused before the shelved rows are touched, so a binding an admin
|
||||
@@ -387,14 +391,14 @@ export class DocSyncController {
|
||||
}
|
||||
// A person asking for a run is also asking for the rows that gave up to be
|
||||
// tried once more; the scheduler gets no such reprieve.
|
||||
this.sync.retryShelvedItems(link.id);
|
||||
await this.sync.retryShelvedItems(link.id);
|
||||
return this.sync.syncLink(link, { full: body.full });
|
||||
}
|
||||
|
||||
// ── Documents and conflicts ────────────────────────────────────────────────
|
||||
|
||||
@Get('items')
|
||||
items(@Param('tripId') tripId: string, @Query('state') state?: string) {
|
||||
async items(@Param('tripId') tripId: string, @Query('state') state?: string) {
|
||||
const rows = state
|
||||
? this.db.connection
|
||||
.prepare(
|
||||
@@ -421,7 +425,7 @@ export class DocSyncController {
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: DocsyncResolveConflictDto,
|
||||
) {
|
||||
this.assertCanManage(tripId, user);
|
||||
await this.assertCanManage(tripId, user);
|
||||
const ok = await this.sync.resolveConflict(Number(itemId), body.keep, Number(tripId));
|
||||
if (!ok) throw new HttpException('Item is not in conflict', 400);
|
||||
return { success: true };
|
||||
|
||||
@@ -50,9 +50,9 @@ export class DocSyncJob implements OnApplicationBootstrap {
|
||||
/** When the last pass started; null until the first one, which is never skipped. */
|
||||
private lastRunAt: number | null = null;
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
if (!this.registrar.isEnabled()) return;
|
||||
logInfo(`Document sync: polling every ${this.intervalSeconds()}s`);
|
||||
logInfo(`Document sync: polling every ${await this.intervalSeconds()}s`);
|
||||
this.registrar.register('docsync', '* * * * *', () => this.tick());
|
||||
}
|
||||
|
||||
@@ -64,16 +64,16 @@ export class DocSyncJob implements OnApplicationBootstrap {
|
||||
* boundaries fall. Comparing against the last run keeps the setting's own
|
||||
* resolution; the cost of the extra wake-ups is one read of app_settings.
|
||||
*/
|
||||
private isDue(now: number): boolean {
|
||||
private async isDue(now: number): Promise<boolean> {
|
||||
// Null rather than 0: comparing against the epoch means "due" only once the
|
||||
// clock has passed the interval since 1970, which is true in production and
|
||||
// false for any test that picks a small timestamp, a difference that would
|
||||
// have hidden here rather than in the behaviour it is supposed to describe.
|
||||
if (this.lastRunAt === null) return true;
|
||||
return now - this.lastRunAt >= this.intervalSeconds() * 1000;
|
||||
return now - this.lastRunAt >= (await this.intervalSeconds()) * 1000;
|
||||
}
|
||||
|
||||
private intervalSeconds(): number {
|
||||
private async intervalSeconds(): Promise<number> {
|
||||
const raw = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', SETTING_POLL_INTERVAL)?.value;
|
||||
const parsed = Number.parseInt(raw || '', 10);
|
||||
if (!Number.isFinite(parsed)) return DEFAULT_POLL_INTERVAL_SECONDS;
|
||||
@@ -89,15 +89,15 @@ export class DocSyncJob implements OnApplicationBootstrap {
|
||||
if (killSwitch === 'false') return;
|
||||
|
||||
const now = Date.now();
|
||||
if (!this.isDue(now)) return;
|
||||
if (!(await this.isDue(now))) return;
|
||||
this.lastRunAt = now;
|
||||
|
||||
// Cheap, and it catches a binding whose owner left the trip through a
|
||||
// path that has no hook to attach to: a transfer, a direct DB edit.
|
||||
const orphaned = this.config.markOrphanedLinks();
|
||||
const orphaned = await this.config.markOrphanedLinks();
|
||||
if (orphaned > 0) logInfo(`Document sync: ${orphaned} link(s) orphaned, owner no longer on the trip`);
|
||||
|
||||
const links = this.sync.dueLinks();
|
||||
const links = await this.sync.dueLinks();
|
||||
for (const link of links) {
|
||||
// One failing provider must not stop the others: an unreachable NAS on
|
||||
// one trip is not a reason to skip a Paperless binding on another.
|
||||
|
||||
@@ -69,9 +69,9 @@ export class DocSyncMcp {
|
||||
})
|
||||
async listIssues({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
const links = this.config.listLinks(tripId);
|
||||
const links = await this.config.listLinks(tripId);
|
||||
if (links.length === 0) return ok({ configured: false, issues: [] });
|
||||
return ok({ configured: true, issues: this.sync.issues(tripId) });
|
||||
return ok({ configured: true, issues: await this.sync.issues(tripId) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -92,7 +92,7 @@ export class DocSyncMcp {
|
||||
})
|
||||
async syncNow({ tripId, full }: { tripId: number; full?: boolean }, ctx: McpContext) {
|
||||
if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
const links = this.config.listLinks(tripId);
|
||||
const links = await this.config.listLinks(tripId);
|
||||
if (links.length === 0) {
|
||||
return errorResult('This trip is not connected to a document store. Connect one in the trip\'s file manager first.');
|
||||
}
|
||||
@@ -101,7 +101,7 @@ export class DocSyncMcp {
|
||||
// An orphaned binding stays stopped, as it does on the REST route and for
|
||||
// the scheduler: its credential belongs to somebody who has left the trip,
|
||||
// and a run would use it anyway.
|
||||
if (this.config.isOrphaned(link)) {
|
||||
if (await this.config.isOrphaned(link)) {
|
||||
results.push({ linkId: link.id, provider: link.provider_id, state: 'orphaned', errorCode: 'orphaned' });
|
||||
continue;
|
||||
}
|
||||
@@ -116,7 +116,7 @@ export class DocSyncMcp {
|
||||
// that were shelved after too many failures. The REST route does the
|
||||
// same thing before its run; a tool that skipped it would answer "in
|
||||
// sync" while leaving them shelved.
|
||||
this.sync.retryShelvedItems(link.id);
|
||||
await this.sync.retryShelvedItems(link.id);
|
||||
results.push({ linkId: link.id, provider: link.provider_id, ...(await this.sync.syncLink(link, { full: full === true })) });
|
||||
}
|
||||
if (results.every((r) => r.errorCode === PROVIDER_DISABLED)) {
|
||||
|
||||
@@ -109,7 +109,7 @@ export class DocSyncService {
|
||||
* than stood down per run. It never runs, so it never gets a `last_sync_at`,
|
||||
* and twenty of them would sort first on every tick and take every slot.
|
||||
*/
|
||||
dueLinks(limit = 20): LinkRow[] {
|
||||
async dueLinks(limit = 20): Promise<LinkRow[]> {
|
||||
return this.db.connection
|
||||
.prepare(
|
||||
`SELECT * FROM trip_document_links
|
||||
@@ -137,7 +137,7 @@ export class DocSyncService {
|
||||
*/
|
||||
async isSwitchedOff(link: Pick<LinkRow, 'provider_id'>): Promise<boolean> {
|
||||
if (!(await this.addons.isAddonEnabled(ADDON_IDS.DOCUMENTS))) return true;
|
||||
return !this.config.enabledProviderIds().includes(link.provider_id);
|
||||
return !(await this.config.enabledProviderIds()).includes(link.provider_id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,7 +163,7 @@ export class DocSyncService {
|
||||
return await this.runLink(link, opts);
|
||||
} catch (err) {
|
||||
this.logger.error(`link ${link.id} failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
this.recordLinkFailure(link, 'unknown');
|
||||
await this.recordLinkFailure(link, 'unknown');
|
||||
return { state: 'failed', pulled: 0, pushed: 0, conflicts: 0, missing: 0, errorCode: 'unknown' };
|
||||
} finally {
|
||||
this.running.delete(link.id);
|
||||
@@ -182,17 +182,17 @@ export class DocSyncService {
|
||||
// An orphaned binding runs for nobody. Its credential belongs to somebody
|
||||
// who has left the trip, and a webhook or a resolved conflict reach this
|
||||
// without asking beforehand.
|
||||
if (this.config.isOrphaned(link)) {
|
||||
if (await this.config.isOrphaned(link)) {
|
||||
return { state: 'orphaned', pulled: 0, pushed: 0, conflicts: 0, missing: 0 };
|
||||
}
|
||||
const conn = this.config.getConnection(link.connection_id);
|
||||
const conn = await this.config.getConnection(link.connection_id);
|
||||
if (!conn) {
|
||||
this.recordLinkFailure(link, 'not_found');
|
||||
await this.recordLinkFailure(link, 'not_found');
|
||||
return { state: 'failed', pulled: 0, pushed: 0, conflicts: 0, missing: 0, errorCode: 'not_found' };
|
||||
}
|
||||
const provider = this.registry.get(link.provider_id);
|
||||
if (!provider) {
|
||||
this.recordLinkFailure(link, 'provider_error');
|
||||
await this.recordLinkFailure(link, 'provider_error');
|
||||
return { state: 'failed', pulled: 0, pushed: 0, conflicts: 0, missing: 0, errorCode: 'provider_error' };
|
||||
}
|
||||
|
||||
@@ -204,20 +204,20 @@ export class DocSyncService {
|
||||
const resolved = await provider.resolveScope(ref, scope);
|
||||
if (docFailed(resolved)) {
|
||||
const code = resolved.error.code === 'not_found' || resolved.error.code === 'scope_missing' ? 'scope_missing' : resolved.error.code;
|
||||
this.recordLinkFailure(link, code, code === 'scope_missing' ? 'scope_lost' : undefined);
|
||||
await this.recordLinkFailure(link, code, code === 'scope_missing' ? 'scope_lost' : undefined);
|
||||
return { state: code === 'scope_missing' ? 'scope_lost' : 'failed', pulled: 0, pushed: 0, conflicts: 0, missing: 0, errorCode: code };
|
||||
}
|
||||
|
||||
// Read before the listing because they decide how much of it is needed: a
|
||||
// file restored in TREK waits for a listing that shows its copy.
|
||||
const items = this.loadItems(link.id);
|
||||
const local = this.loadLocalDocuments(link);
|
||||
const items = await this.loadItems(link.id);
|
||||
const local = await this.loadLocalDocuments(link);
|
||||
if (opts.full || needsFullListing(items, local)) scope.cursor = null;
|
||||
|
||||
const listing = await provider.list(ref, scope);
|
||||
if (docFailed(listing)) {
|
||||
const state = listing.error.code === 'unauthorized' ? 'needs_reauth' : 'failed';
|
||||
this.recordLinkFailure(link, listing.error.code, state);
|
||||
await this.recordLinkFailure(link, listing.error.code, state);
|
||||
return { state, pulled: 0, pushed: 0, conflicts: 0, missing: 0, errorCode: listing.error.code };
|
||||
}
|
||||
|
||||
@@ -237,7 +237,7 @@ export class DocSyncService {
|
||||
// Refusing the whole run is the point: the listing is not trustworthy, so
|
||||
// nothing in it should be acted on, not even the parts that look fine.
|
||||
this.logger.warn(`link ${link.id}: mass-delete guard tripped (${plan.missingCount} of ${items.length} gone), run abandoned`);
|
||||
this.recordLinkFailure(link, 'mass_delete_guard', 'partial');
|
||||
await this.recordLinkFailure(link, 'mass_delete_guard', 'partial');
|
||||
return { state: 'partial', pulled: 0, pushed: 0, conflicts: 0, missing: plan.missingCount, errorCode: 'mass_delete_guard' };
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ export class DocSyncService {
|
||||
* clean.
|
||||
*/
|
||||
const cursor = state === 'ok' && !wroteUpstream ? listing.data.cursor : null;
|
||||
this.recordLinkSuccess(link, cursor, state, softFailure ?? null);
|
||||
await this.recordLinkSuccess(link, cursor, state, softFailure ?? null);
|
||||
if (pulled > 0 || pushed > 0) {
|
||||
this.realtime.broadcast(link.trip_id, 'docsync:changed', { linkId: link.id, pulled, pushed });
|
||||
}
|
||||
@@ -468,17 +468,17 @@ export class DocSyncService {
|
||||
// when it arrives through the store instead.
|
||||
const allowed = isVideoExtension(path.extname(name)) || isAllowedByOperator(name, await this.allowedTypes.get());
|
||||
if (isBlockedName(name) || !allowed) {
|
||||
this.upsertItem(ctx.link, { itemId, remote, state: 'rejected_type', errorCode: 'unsupported_type' });
|
||||
await this.upsertItem(ctx.link, { itemId, remote, state: 'rejected_type', errorCode: 'unsupported_type' });
|
||||
return 'unsupported_type';
|
||||
}
|
||||
if (remote.size !== null && remote.size > MAX_FILE_SIZE) {
|
||||
this.upsertItem(ctx.link, { itemId, remote, state: 'too_large', errorCode: 'too_large' });
|
||||
await this.upsertItem(ctx.link, { itemId, remote, state: 'too_large', errorCode: 'too_large' });
|
||||
return 'too_large';
|
||||
}
|
||||
|
||||
const fetched = await ctx.provider.fetch(ctx.ref, ctx.scope, remote.remoteId);
|
||||
if (docFailed(fetched)) {
|
||||
this.upsertItem(ctx.link, { itemId, remote, state: 'error', errorCode: fetched.error.code });
|
||||
await this.upsertItem(ctx.link, { itemId, remote, state: 'error', errorCode: fetched.error.code });
|
||||
return fetched.error.code;
|
||||
}
|
||||
|
||||
@@ -506,7 +506,7 @@ export class DocSyncService {
|
||||
} catch (err) {
|
||||
await fs.promises.rm(tmpPath, { force: true });
|
||||
const code: DocsyncErrorCode = err instanceof Error && err.message === 'too_large' ? 'too_large' : 'provider_error';
|
||||
this.upsertItem(ctx.link, { itemId, remote, state: code === 'too_large' ? 'too_large' : 'error', errorCode: code });
|
||||
await this.upsertItem(ctx.link, { itemId, remote, state: code === 'too_large' ? 'too_large' : 'error', errorCode: code });
|
||||
return code;
|
||||
}
|
||||
|
||||
@@ -531,7 +531,7 @@ export class DocSyncService {
|
||||
// here would read it as TREK's own and send the old name back up.
|
||||
if (superseded && !superseded.deleted_at && pairing?.content_sha256 === sha256) {
|
||||
await fs.promises.rm(tmpPath, { force: true });
|
||||
this.upsertItem(ctx.link, {
|
||||
await this.upsertItem(ctx.link, {
|
||||
itemId,
|
||||
remote,
|
||||
state: 'synced',
|
||||
@@ -545,7 +545,7 @@ export class DocSyncService {
|
||||
await this.storage.put('files', storageKey, { tmpPath });
|
||||
} catch {
|
||||
await fs.promises.rm(tmpPath, { force: true });
|
||||
this.upsertItem(ctx.link, { itemId, remote, state: 'error', errorCode: 'provider_error' });
|
||||
await this.upsertItem(ctx.link, { itemId, remote, state: 'error', errorCode: 'provider_error' });
|
||||
return 'provider_error';
|
||||
}
|
||||
|
||||
@@ -568,7 +568,7 @@ export class DocSyncService {
|
||||
{ filename: storageKey, originalname: name, size: bytes, mimetype: remote.mimeType || 'application/octet-stream' },
|
||||
// Attributed to the person whose connection brought it in, which is the
|
||||
// only honest answer: nobody in TREK uploaded it.
|
||||
this.config.getConnection(ctx.link.connection_id)?.owner_user_id ?? 0,
|
||||
(await this.config.getConnection(ctx.link.connection_id))?.owner_user_id ?? 0,
|
||||
{
|
||||
place_id: superseded?.place_id ?? null,
|
||||
reservation_id: superseded?.reservation_id ?? null,
|
||||
@@ -587,7 +587,7 @@ export class DocSyncService {
|
||||
.run(file.id, supersededId);
|
||||
await this.files.softDeleteFile(supersededId as number);
|
||||
}
|
||||
this.upsertItem(ctx.link, {
|
||||
await this.upsertItem(ctx.link, {
|
||||
itemId,
|
||||
remote,
|
||||
state: 'synced',
|
||||
@@ -618,11 +618,11 @@ export class DocSyncService {
|
||||
// Paperless refuses anything outside its parser list with a 400. Checking
|
||||
// first turns a recurring hard failure into one visible row that says why.
|
||||
if (caps.acceptedMimeTypes && !caps.acceptedMimeTypes.includes(mime)) {
|
||||
this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'rejected_type', errorCode: 'unsupported_type' });
|
||||
await this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'rejected_type', errorCode: 'unsupported_type' });
|
||||
return 'unsupported_type';
|
||||
}
|
||||
if (caps.maxUploadBytes !== null && local.size > caps.maxUploadBytes) {
|
||||
this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'too_large', errorCode: 'too_large' });
|
||||
await this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'too_large', errorCode: 'too_large' });
|
||||
return 'too_large';
|
||||
}
|
||||
|
||||
@@ -644,11 +644,11 @@ export class DocSyncService {
|
||||
const got = await this.storage.getStream('files', String(file.filename));
|
||||
stream = got.stream;
|
||||
} catch {
|
||||
this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'error', errorCode: 'provider_error' });
|
||||
await this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'error', errorCode: 'provider_error' });
|
||||
return 'provider_error';
|
||||
}
|
||||
|
||||
const uid = this.existingUid(ctx.link.id, itemId) ?? newTrekDocUid();
|
||||
const uid = (await this.existingUid(ctx.link.id, itemId)) ?? newTrekDocUid();
|
||||
const res = await ctx.provider.push(ctx.ref, ctx.scope, {
|
||||
body: stream,
|
||||
fileName: local.name,
|
||||
@@ -662,7 +662,7 @@ export class DocSyncService {
|
||||
});
|
||||
|
||||
if (docFailed(res)) {
|
||||
this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'error', errorCode: res.error.code, trekDocUid: uid });
|
||||
await this.upsertItem(ctx.link, { itemId, fileId: local.fileId, state: 'error', errorCode: res.error.code, trekDocUid: uid });
|
||||
return res.error.code;
|
||||
}
|
||||
|
||||
@@ -672,9 +672,9 @@ export class DocSyncService {
|
||||
// the unique index on (link_id, remote_id) would abort this run (and every
|
||||
// run after it) with a constraint error. The upload happened, so nothing is
|
||||
// lost; what must not happen is the pairing moving off the file that owns it.
|
||||
const heldBy = this.pairingOwner(ctx.link.id, res.data.remoteId, itemId);
|
||||
const heldBy = await this.pairingOwner(ctx.link.id, res.data.remoteId, itemId);
|
||||
if (heldBy !== null) {
|
||||
this.upsertItem(ctx.link, {
|
||||
await this.upsertItem(ctx.link, {
|
||||
itemId,
|
||||
fileId: local.fileId,
|
||||
state: 'error',
|
||||
@@ -684,7 +684,7 @@ export class DocSyncService {
|
||||
return 'conflict';
|
||||
}
|
||||
|
||||
this.upsertItem(ctx.link, {
|
||||
await this.upsertItem(ctx.link, {
|
||||
itemId,
|
||||
fileId: local.fileId,
|
||||
state: 'synced',
|
||||
@@ -718,7 +718,7 @@ export class DocSyncService {
|
||||
* and the only way to find out is to try again. The scheduler never calls
|
||||
* this: automatic retries are exactly what the limit exists to stop.
|
||||
*/
|
||||
retryShelvedItems(linkId: number): void {
|
||||
async retryShelvedItems(linkId: number): Promise<void> {
|
||||
this.db.connection
|
||||
.prepare(
|
||||
`UPDATE document_sync_items
|
||||
@@ -730,7 +730,7 @@ export class DocSyncService {
|
||||
|
||||
// ── State loading and writing ──────────────────────────────────────────────
|
||||
|
||||
private loadItems(linkId: number): SyncItemState[] {
|
||||
private async loadItems(linkId: number): Promise<SyncItemState[]> {
|
||||
const rows = this.db.connection
|
||||
.prepare(
|
||||
`SELECT id, file_id, trek_doc_uid, remote_id, remote_version, remote_name, remote_size, remote_modified_at,
|
||||
@@ -771,7 +771,7 @@ export class DocSyncService {
|
||||
* Paperless, everything else to Nextcloud": splitting a trip across bindings
|
||||
* would need a per-document assignment that nothing in the UI offers yet.
|
||||
*/
|
||||
private loadLocalDocuments(link: LinkRow): LocalDocument[] {
|
||||
private async loadLocalDocuments(link: LinkRow): Promise<LocalDocument[]> {
|
||||
const rows = this.db.connection
|
||||
.prepare(
|
||||
`SELECT f.id, f.original_name, f.file_size, f.mime_type, f.deleted_at
|
||||
@@ -797,7 +797,7 @@ export class DocSyncService {
|
||||
}
|
||||
|
||||
/** The item already paired with this remote document, if it is a different one. */
|
||||
private pairingOwner(linkId: number, remoteId: string, itemId: number | null): number | null {
|
||||
private async pairingOwner(linkId: number, remoteId: string, itemId: number | null): Promise<number | null> {
|
||||
const row = this.db.connection
|
||||
.prepare('SELECT id FROM document_sync_items WHERE link_id = ? AND remote_id = ?')
|
||||
.get(linkId, remoteId) as { id?: number } | undefined;
|
||||
@@ -805,7 +805,7 @@ export class DocSyncService {
|
||||
return itemId !== null && Number(row.id) === Number(itemId) ? null : Number(row.id);
|
||||
}
|
||||
|
||||
private existingUid(linkId: number, itemId: number | null): string | null {
|
||||
private async existingUid(linkId: number, itemId: number | null): Promise<string | null> {
|
||||
if (itemId === null) return null;
|
||||
const row = this.db.connection
|
||||
.prepare('SELECT trek_doc_uid FROM document_sync_items WHERE id = ? AND link_id = ?')
|
||||
@@ -820,7 +820,7 @@ export class DocSyncService {
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
private upsertItem(
|
||||
private async upsertItem(
|
||||
link: LinkRow,
|
||||
patch: {
|
||||
itemId: number | null;
|
||||
@@ -839,7 +839,7 @@ export class DocSyncService {
|
||||
pushedSha256?: string;
|
||||
trekDocUid?: string;
|
||||
},
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const failed = patch.state === 'error';
|
||||
/**
|
||||
* A failed transfer leaves the pairing describing the copy TREK holds.
|
||||
@@ -946,7 +946,7 @@ export class DocSyncService {
|
||||
);
|
||||
}
|
||||
|
||||
private recordLinkSuccess(link: LinkRow, cursor: string | null, state: string, errorCode: string | null): void {
|
||||
private async recordLinkSuccess(link: LinkRow, cursor: string | null, state: string, errorCode: string | null): Promise<void> {
|
||||
this.db.connection
|
||||
.prepare(
|
||||
`UPDATE trip_document_links
|
||||
@@ -957,7 +957,7 @@ export class DocSyncService {
|
||||
.run(cursor, state, errorCode, link.id);
|
||||
}
|
||||
|
||||
private recordLinkFailure(link: LinkRow, code: string, state = 'failed'): void {
|
||||
private async recordLinkFailure(link: LinkRow, code: string, state = 'failed'): Promise<void> {
|
||||
const failures = link.failure_count + 1;
|
||||
const wait = backoffSeconds(LINK_BACKOFF_SECONDS, failures);
|
||||
this.db.connection
|
||||
@@ -998,7 +998,7 @@ export class DocSyncService {
|
||||
* next run to sort out rather than the owner's choice being refused.
|
||||
*/
|
||||
private async renameRemoteTo(link: LinkRow, remoteId: string, name: string, itemId: number): Promise<void> {
|
||||
const conn = this.config.getConnection(link.connection_id);
|
||||
const conn = await this.config.getConnection(link.connection_id);
|
||||
const provider = this.registry.get(link.provider_id);
|
||||
if (!conn || !provider) return;
|
||||
const res = await provider.rename(this.config.toRef(conn), this.config.toScopeRef(link), remoteId, name);
|
||||
@@ -1017,7 +1017,7 @@ export class DocSyncService {
|
||||
.get(itemId) as Record<string, unknown> | undefined;
|
||||
if (!item || item.state !== 'conflict') return false;
|
||||
if (tripId !== undefined && Number(item.trip_id) !== Number(tripId)) return false;
|
||||
const link = this.config.getLink(Number(item.link_id));
|
||||
const link = await this.config.getLink(Number(item.link_id));
|
||||
if (!link) return false;
|
||||
|
||||
/**
|
||||
@@ -1087,7 +1087,7 @@ export class DocSyncService {
|
||||
* that vanished upstream. Deliberately not "everything not synced": a row
|
||||
* waiting for its turn is not a problem anyone should be shown.
|
||||
*/
|
||||
issues(tripId: number): Array<Record<string, unknown>> {
|
||||
async issues(tripId: number): Promise<Array<Record<string, unknown>>> {
|
||||
return this.db.connection
|
||||
.prepare(
|
||||
`SELECT i.id, i.state, i.error_code, i.remote_name, i.remote_missing_at, f.original_name AS file_name
|
||||
@@ -1103,7 +1103,7 @@ export class DocSyncService {
|
||||
|
||||
/** Per-trip view for the UI: what is synced, what needs attention. */
|
||||
async status(tripId: number): Promise<Record<string, unknown>> {
|
||||
const links = this.config.listLinks(tripId);
|
||||
const links = await this.config.listLinks(tripId);
|
||||
const counts = this.db.connection
|
||||
.prepare('SELECT state, COUNT(*) AS n FROM document_sync_items WHERE trip_id = ? GROUP BY state')
|
||||
.all(tripId) as Array<{ state: string; n: number }>;
|
||||
@@ -1146,7 +1146,7 @@ export class DocSyncService {
|
||||
for (const l of links) {
|
||||
const row = byLink.get(l.id);
|
||||
linkCards.push({
|
||||
...this.config.publicLink(l, null),
|
||||
...(await this.config.publicLink(l, null)),
|
||||
// Paused rather than failed, so the card can say why nothing moves
|
||||
// without the binding's own state being touched.
|
||||
providerOff: await this.isSwitchedOff(l),
|
||||
|
||||
@@ -88,7 +88,7 @@ export interface DocumentConnectionRef {
|
||||
* stored but never changes it: the values on screen may be for another
|
||||
* account, or never be saved at all.
|
||||
*/
|
||||
saveSecret?: (key: string, value: string | null) => void;
|
||||
saveSecret?: (key: string, value: string | null) => Promise<void>;
|
||||
}
|
||||
|
||||
/** The container at the provider that one trip is bound to. */
|
||||
|
||||
@@ -228,7 +228,7 @@ export interface SynologyDriveCreds {
|
||||
* connection passes one; a probe of form values uses the stored token without
|
||||
* being able to change it.
|
||||
*/
|
||||
saveDeviceToken?: (stored: string | null) => void;
|
||||
saveDeviceToken?: (stored: string | null) => Promise<void>;
|
||||
allowInsecureTls: boolean;
|
||||
}
|
||||
|
||||
@@ -554,7 +554,7 @@ export class SynologyDriveClient {
|
||||
* anything is written, so a change is written once and not on every call of
|
||||
* the run that made it.
|
||||
*/
|
||||
private deviceSlot(creds: SynologyDriveCreds): DeviceTokenSlot | null {
|
||||
private async deviceSlot(creds: SynologyDriveCreds): Promise<DeviceTokenSlot | null> {
|
||||
if (creds.connectionId <= 0) return null;
|
||||
const key = `${creds.connectionId}\u0000${creds.connectionCreatedAt}`;
|
||||
const account = this.accountDigest(creds);
|
||||
@@ -563,24 +563,24 @@ export class SynologyDriveClient {
|
||||
slot = { account, token: deviceTokenFor(creds.storedDeviceToken, account) };
|
||||
this.deviceTokens.set(key, slot);
|
||||
}
|
||||
this.persist(creds, slot);
|
||||
await this.persist(creds, slot);
|
||||
return slot;
|
||||
}
|
||||
|
||||
private persist(creds: SynologyDriveCreds, slot: DeviceTokenSlot): void {
|
||||
private async persist(creds: SynologyDriveCreds, slot: DeviceTokenSlot): Promise<void> {
|
||||
if (!creds.saveDeviceToken) return;
|
||||
if (slot.stored === undefined) slot.stored = creds.storedDeviceToken ?? null;
|
||||
const wanted = slot.token === null ? null : storedDeviceToken(slot.account, slot.token);
|
||||
if (wanted === slot.stored) return;
|
||||
creds.saveDeviceToken(wanted);
|
||||
await creds.saveDeviceToken(wanted);
|
||||
slot.stored = wanted;
|
||||
}
|
||||
|
||||
private setDeviceToken(creds: SynologyDriveCreds, token: string | null): void {
|
||||
const slot = this.deviceSlot(creds);
|
||||
private async setDeviceToken(creds: SynologyDriveCreds, token: string | null): Promise<void> {
|
||||
const slot = await this.deviceSlot(creds);
|
||||
if (!slot || slot.token === token) return;
|
||||
slot.token = token;
|
||||
this.persist(creds, slot);
|
||||
await this.persist(creds, slot);
|
||||
}
|
||||
|
||||
private async request(
|
||||
@@ -691,8 +691,8 @@ export class SynologyDriveClient {
|
||||
private async session(creds: SynologyDriveCreds): Promise<SynoSession> {
|
||||
const cached = this.sessions.get(this.sessionKey(creds));
|
||||
if (cached && Date.now() - cached.createdAt < SESSION_MAX_AGE_MS) {
|
||||
const slot = this.deviceSlot(creds);
|
||||
if (slot && slot.token === null && cached.deviceId) this.setDeviceToken(creds, cached.deviceId);
|
||||
const slot = await this.deviceSlot(creds);
|
||||
if (slot && slot.token === null && cached.deviceId) await this.setDeviceToken(creds, cached.deviceId);
|
||||
return cached;
|
||||
}
|
||||
return await this.login(creds);
|
||||
@@ -736,7 +736,7 @@ export class SynologyDriveClient {
|
||||
throw new SynologyDriveError('provider_error', 'The NAS accepted the login but returned no session id');
|
||||
}
|
||||
const issuedDeviceId = isRecord(data) && typeof data.did === 'string' ? data.did : deviceId;
|
||||
if (issuedDeviceId) this.setDeviceToken(creds, issuedDeviceId);
|
||||
if (issuedDeviceId) await this.setDeviceToken(creds, issuedDeviceId);
|
||||
const session: SynoSession = {
|
||||
sid,
|
||||
synoToken: isRecord(data) && typeof data.synotoken === 'string' ? data.synotoken : null,
|
||||
@@ -761,7 +761,7 @@ export class SynologyDriveClient {
|
||||
* is what the lockout records.
|
||||
*/
|
||||
private async authenticate(creds: SynologyDriveCreds): Promise<{ data: unknown; deviceId: string | null }> {
|
||||
const deviceId = this.deviceSlot(creds)?.token ?? null;
|
||||
const deviceId = (await this.deviceSlot(creds))?.token ?? null;
|
||||
try {
|
||||
return { data: await this.call(creds, this.loginParams(creds, deviceId), { cgi: AUTH_CGI }), deviceId };
|
||||
} catch (error: unknown) {
|
||||
@@ -769,7 +769,7 @@ export class SynologyDriveClient {
|
||||
throw error;
|
||||
}
|
||||
// Unless another login replaced it while this one was out.
|
||||
if (this.deviceSlot(creds)?.token === deviceId) this.setDeviceToken(creds, null);
|
||||
if ((await this.deviceSlot(creds))?.token === deviceId) await this.setDeviceToken(creds, null);
|
||||
if (!creds.otpCode) throw error;
|
||||
return { data: await this.call(creds, this.loginParams(creds, null), { cgi: AUTH_CGI }), deviceId: null };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user