Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

21.5 KB
Raw Blame
/**
 * External Persistent Time-lapse Storage Adapter
 *
 * Keeps time-lapse keyframes out of `.ink` project files while persisting them reliably across
 * app restarts, tab closes, and crashes:
 * - Tauri Desktop: `%LOCALAPPDATA%/inkstudio_timelapse/<recordingId>/` (append-only `frames.ndjson` + atomic `meta.json`)
 * - Browser / WebView fallback: IndexedDB (`InkStudioTimelapseDB`) so frames consume zero JS heap RAM
 *   and survive page reloads / restarts
 * - Document-to-recording link index in safe localStorage so even non-`.ink` files (.psd, .png) and
 *   Recent Documents seamlessly reconnect to their time-lapse recording on reopen.
 */

import {
  TimelapseCaptureArea,
  TimelapseCaptureResolution,
} from '../types/editor';
import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';

export interface PersistentTimelapseMeta {
  recordingId: string;
  documentName: string;
  enabled: boolean;
  captureArea: TimelapseCaptureArea;
  captureResolution: TimelapseCaptureResolution;
  nextIndex: number;
  createdAt: number;
  updatedAt: number;
}

export interface PersistentFrameRecord {
  index: number;
  timestamp: number;
  width: number;
  height: number;
  mimeType: 'image/webp' | 'image/jpeg' | 'image/png';
  bytes: number;
  captureArea?: TimelapseCaptureArea;
}

export interface LoadedPersistentSession {
  meta: PersistentTimelapseMeta | null;
  frames: PersistentFrameRecord[];
  totalBytes: number;
}

export interface StoredRecordingSummary {
  recordingId: string;
  documentName: string;
  enabled: boolean;
  captureArea: TimelapseCaptureArea;
  captureResolution: TimelapseCaptureResolution;
  frameCount: number;
  totalBytes: number;
  createdAt: number;
  updatedAt: number;
}

export interface DocumentRecordingLinkMap {
  byDocId: Record<string, string>;
  byPath: Record<string, string>;
  lastActiveRecordingId?: string;
}

const DOC_LINK_LS_KEY = 'inkstudio_timelapse_doc_links_v1';
const MAX_LINK_ENTRIES = 200;

const IDB_NAME = 'InkStudioTimelapseDB';
const IDB_VERSION = 1;
const IDB_SESSIONS_STORE = 'sessions';
const IDB_FRAMES_STORE = 'frames';

export function isTauriRuntime(): boolean {
  return (
    typeof window !== 'undefined' &&
    Boolean((window as unknown as Record<string, unknown>).__TAURI_INTERNALS__)
  );
}

let cachedTauriInvokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;

function getTauriInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {
  if (!cachedTauriInvokePromise) {
    cachedTauriInvokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
  }
  return cachedTauriInvokePromise;
}

export async function invokeTauri<T>(cmd: string, args: Record<string, unknown>): Promise<T> {
  const invoke = await getTauriInvoke();
  return invoke<T>(cmd, args);
}

export async function invokeTauriRaw<T>(
  cmd: string,
  body: Uint8Array | ArrayBuffer | undefined,
  headers: Record<string, string>
): Promise<T> {
  const invoke = await getTauriInvoke();
  return invoke<T>(cmd, body, { headers });
}

export function toArrayBuffer(raw: ArrayBuffer | Uint8Array | number[]): ArrayBuffer {
  if (raw instanceof ArrayBuffer) return raw;
  if (raw instanceof Uint8Array) {
    if (
      raw.buffer instanceof ArrayBuffer &&
      raw.byteOffset === 0 &&
      raw.byteLength === raw.buffer.byteLength
    ) {
      return raw.buffer;
    }
    return raw.slice().buffer;
  }
  return new Uint8Array(raw).buffer;
}

export function generateRecordingId(): string {
  try {
    if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
      return `tl-${crypto.randomUUID()}`;
    }
  } catch {
    // fallback below
  }
  return `tl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}

export function normalizeLinkPath(rawPath: string | undefined | null): string | null {
  if (!rawPath || typeof rawPath !== 'string') return null;
  const trimmed = rawPath.trim().replace(/\\/g, '/').toLowerCase();
  if (!trimmed || trimmed.endsWith('*')) return null;
  return trimmed;
}

function readLinkMap(): DocumentRecordingLinkMap {
  try {
    const raw = safeLocalStorageGetItem(DOC_LINK_LS_KEY);
    if (!raw) return { byDocId: {}, byPath: {} };
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object') return { byDocId: {}, byPath: {} };
    return {
      byDocId: parsed.byDocId && typeof parsed.byDocId === 'object' ? { ...parsed.byDocId } : {},
      byPath: parsed.byPath && typeof parsed.byPath === 'object' ? { ...parsed.byPath } : {},
      ...(typeof parsed.lastActiveRecordingId === 'string'
        ? { lastActiveRecordingId: parsed.lastActiveRecordingId }
        : {}),
    };
  } catch {
    return { byDocId: {}, byPath: {} };
  }
}

function pruneMapKeys(map: Record<string, string>): Record<string, string> {
  const keys = Object.keys(map);
  if (keys.length <= MAX_LINK_ENTRIES) return map;
  const trimmed: Record<string, string> = {};
  for (const k of keys.slice(keys.length - MAX_LINK_ENTRIES)) {
    trimmed[k] = map[k];
  }
  return trimmed;
}

function writeLinkMap(map: DocumentRecordingLinkMap): void {
  const compact: DocumentRecordingLinkMap = {
    byDocId: pruneMapKeys(map.byDocId),
    byPath: pruneMapKeys(map.byPath),
    ...(map.lastActiveRecordingId ? { lastActiveRecordingId: map.lastActiveRecordingId } : {}),
  };
  safeLocalStorageSetItem(DOC_LINK_LS_KEY, JSON.stringify(compact), 'timelapse document links');
}

export function saveDocumentRecordingLink(opts: {
  recordingId: string;
  docId?: string | null;
  sourcePath?: string | null;
}): void {
  if (!opts.recordingId) return;
  const map = readLinkMap();
  if (opts.docId) {
    map.byDocId[opts.docId] = opts.recordingId;
  }
  const normPath = normalizeLinkPath(opts.sourcePath);
  if (normPath) {
    map.byPath[normPath] = opts.recordingId;
  }
  map.lastActiveRecordingId = opts.recordingId;
  writeLinkMap(map);
}

export function lookupLinkedRecordingId(opts: {
  docId?: string | null;
  sourcePath?: string | null;
}): string | null {
  const map = readLinkMap();
  if (opts.docId && map.byDocId[opts.docId]) {
    return map.byDocId[opts.docId];
  }
  const normPath = normalizeLinkPath(opts.sourcePath);
  if (normPath && map.byPath[normPath]) {
    return map.byPath[normPath];
  }
  return null;
}

export function removeRecordingLinks(recordingId: string): void {
  const map = readLinkMap();
  let changed = false;
  for (const [k, v] of Object.entries(map.byDocId)) {
    if (v === recordingId) {
      delete map.byDocId[k];
      changed = true;
    }
  }
  for (const [k, v] of Object.entries(map.byPath)) {
    if (v === recordingId) {
      delete map.byPath[k];
      changed = true;
    }
  }
  if (map.lastActiveRecordingId === recordingId) {
    delete map.lastActiveRecordingId;
    changed = true;
  }
  if (changed) {
    writeLinkMap(map);
  }
}

// --- IndexedDB persistent fallback for Browser / Web environments ---

interface IdbStoredSessionRecord extends PersistentTimelapseMeta {
  frames: PersistentFrameRecord[];
  totalBytes: number;
}

interface IdbStoredFrameRow {
  key: string;
  recordingId: string;
  index: number;
  mimeType: 'image/webp' | 'image/jpeg' | 'image/png';
  bytes: Uint8Array;
}

let cachedIdbPromise: Promise<IDBDatabase | null> | null = null;

function getIndexedDbApi(): IDBFactory | null {
  if (typeof indexedDB !== 'undefined' && indexedDB) return indexedDB;
  if (typeof window !== 'undefined' && window.indexedDB) return window.indexedDB;
  return null;
}

function openTimelapseIdb(): Promise<IDBDatabase | null> {
  const idb = getIndexedDbApi();
  if (!idb) return Promise.resolve(null);
  if (cachedIdbPromise) return cachedIdbPromise;

  cachedIdbPromise = new Promise<IDBDatabase | null>((resolve) => {
    try {
      const req = idb.open(IDB_NAME, IDB_VERSION);
      req.onupgradeneeded = () => {
        const db = req.result;
        if (!db.objectStoreNames.contains(IDB_SESSIONS_STORE)) {
          db.createObjectStore(IDB_SESSIONS_STORE, { keyPath: 'recordingId' });
        }
        if (!db.objectStoreNames.contains(IDB_FRAMES_STORE)) {
          const store = db.createObjectStore(IDB_FRAMES_STORE, { keyPath: 'key' });
          store.createIndex('recordingId', 'recordingId', { unique: false });
        }
      };
      req.onsuccess = () => resolve(req.result);
      req.onerror = () => {
        cachedIdbPromise = null;
        resolve(null);
      };
    } catch {
      cachedIdbPromise = null;
      resolve(null);
    }
  });
  return cachedIdbPromise;
}

export function isIndexedDbAvailable(): boolean {
  return Boolean(getIndexedDbApi());
}

async function idbSaveMeta(meta: PersistentTimelapseMeta): Promise<boolean> {
  const db = await openTimelapseIdb();
  if (!db) return false;
  return new Promise<boolean>((resolve) => {
    try {
      const tx = db.transaction(IDB_SESSIONS_STORE, 'readwrite');
      const store = tx.objectStore(IDB_SESSIONS_STORE);
      const getReq = store.get(meta.recordingId);
      getReq.onsuccess = () => {
        const existing = getReq.result as IdbStoredSessionRecord | undefined;
        const merged: IdbStoredSessionRecord = {
          ...meta,
          frames: existing?.frames ?? [],
          totalBytes: existing?.totalBytes ?? 0,
        };
        store.put(merged);
      };
      tx.oncomplete = () => resolve(true);
      tx.onerror = () => resolve(false);
      tx.onabort = () => resolve(false);
    } catch {
      resolve(false);
    }
  });
}

async function idbWriteFrame(
  recordingId: string,
  record: PersistentFrameRecord,
  bytes: Uint8Array,
  metaFallback?: PersistentTimelapseMeta
): Promise<boolean> {
  const db = await openTimelapseIdb();
  if (!db) return false;
  return new Promise<boolean>((resolve) => {
    try {
      const tx = db.transaction([IDB_FRAMES_STORE, IDB_SESSIONS_STORE], 'readwrite');
      const frameStore = tx.objectStore(IDB_FRAMES_STORE);
      const sessionStore = tx.objectStore(IDB_SESSIONS_STORE);

      const frameRow: IdbStoredFrameRow = {
        key: `${recordingId}:${record.index}`,
        recordingId,
        index: record.index,
        mimeType: record.mimeType,
        bytes,
      };
      frameStore.put(frameRow);

      const getReq = sessionStore.get(recordingId);
      getReq.onsuccess = () => {
        const existing = getReq.result as IdbStoredSessionRecord | undefined;
        const base: IdbStoredSessionRecord = existing ?? {
          recordingId,
          documentName: metaFallback?.documentName ?? 'Untitled',
          enabled: metaFallback?.enabled ?? true,
          captureArea: metaFallback?.captureArea ?? 'artwork',
          captureResolution: metaFallback?.captureResolution ?? '1080p',
          nextIndex: record.index + 1,
          createdAt: metaFallback?.createdAt ?? Date.now(),
          updatedAt: Date.now(),
          frames: [],
          totalBytes: 0,
        };
        if (!Array.isArray(base.frames)) {
          base.frames = [];
        }
        const existingIdx = base.frames.findIndex((f) => f.index === record.index);
        if (existingIdx >= 0) {
          base.totalBytes = Math.max(0, base.totalBytes - base.frames[existingIdx].bytes) + record.bytes;
          base.frames[existingIdx] = record;
        } else {
          base.frames.push(record);
          base.frames.sort((a, b) => a.index - b.index);
          base.totalBytes += record.bytes;
        }
        base.nextIndex = Math.max(base.nextIndex, record.index + 1);
        base.updatedAt = Date.now();
        sessionStore.put(base);
      };

      tx.oncomplete = () => resolve(true);
      tx.onerror = () => resolve(false);
      tx.onabort = () => resolve(false);
    } catch {
      resolve(false);
    }
  });
}

async function idbReadFrame(recordingId: string, index: number): Promise<Uint8Array | null> {
  const db = await openTimelapseIdb();
  if (!db) return null;
  return new Promise<Uint8Array | null>((resolve) => {
    try {
      const tx = db.transaction(IDB_FRAMES_STORE, 'readonly');
      const req = tx.objectStore(IDB_FRAMES_STORE).get(`${recordingId}:${index}`);
      req.onsuccess = () => {
        const row = req.result as IdbStoredFrameRow | undefined;
        if (!row?.bytes) {
          resolve(null);
          return;
        }
        resolve(row.bytes instanceof Uint8Array ? row.bytes : new Uint8Array(row.bytes));
      };
      req.onerror = () => resolve(null);
    } catch {
      resolve(null);
    }
  });
}

async function idbLoadSession(recordingId: string): Promise<LoadedPersistentSession | null> {
  const db = await openTimelapseIdb();
  if (!db) return null;
  return new Promise<LoadedPersistentSession | null>((resolve) => {
    try {
      const tx = db.transaction(IDB_SESSIONS_STORE, 'readonly');
      const req = tx.objectStore(IDB_SESSIONS_STORE).get(recordingId);
      req.onsuccess = () => {
        const rec = req.result as IdbStoredSessionRecord | undefined;
        if (!rec) {
          resolve({ meta: null, frames: [], totalBytes: 0 });
          return;
        }
        const { frames, totalBytes, ...meta } = rec;
        resolve({
          meta,
          frames: Array.isArray(frames) ? frames : [],
          totalBytes: Number.isFinite(totalBytes) ? totalBytes : 0,
        });
      };
      req.onerror = () => resolve(null);
    } catch {
      resolve(null);
    }
  });
}

async function idbListSessions(): Promise<StoredRecordingSummary[]> {
  const db = await openTimelapseIdb();
  if (!db) return [];
  return new Promise<StoredRecordingSummary[]>((resolve) => {
    try {
      const tx = db.transaction(IDB_SESSIONS_STORE, 'readonly');
      const req = tx.objectStore(IDB_SESSIONS_STORE).getAll();
      req.onsuccess = () => {
        const rows = (req.result as IdbStoredSessionRecord[] | undefined) ?? [];
        const summaries: StoredRecordingSummary[] = rows
          .filter((r) => {
            if (!r) return false;
            const framesLen = Array.isArray(r.frames) ? r.frames.length : 0;
            return framesLen > 0 || Boolean(r.enabled);
          })
          .map((r) => ({
            recordingId: r.recordingId,
            documentName: r.documentName || 'Untitled',
            enabled: Boolean(r.enabled),
            captureArea: r.captureArea || 'artwork',
            captureResolution: r.captureResolution || '1080p',
            frameCount: Array.isArray(r.frames) ? r.frames.length : 0,
            totalBytes: r.totalBytes || 0,
            createdAt: r.createdAt || 0,
            updatedAt: r.updatedAt || 0,
          }))
          .sort((a, b) => b.updatedAt - a.updatedAt);
        resolve(summaries);
      };
      req.onerror = () => resolve([]);
      tx.onerror = () => resolve([]);
      tx.onabort = () => resolve([]);
    } catch {
      resolve([]);
    }
  });
}

async function idbClearSession(recordingId: string): Promise<void> {
  const db = await openTimelapseIdb();
  if (!db) return;
  await new Promise<void>((resolve) => {
    try {
      const tx = db.transaction([IDB_SESSIONS_STORE, IDB_FRAMES_STORE], 'readwrite');
      tx.objectStore(IDB_SESSIONS_STORE).delete(recordingId);
      const frameStore = tx.objectStore(IDB_FRAMES_STORE);
      const idx = frameStore.index('recordingId');
      const cursorReq = idx.openCursor(IDBKeyRange.only(recordingId));
      cursorReq.onsuccess = () => {
        const cursor = cursorReq.result;
        if (cursor) {
          cursor.delete();
          cursor.continue();
        }
      };
      tx.oncomplete = () => resolve();
      tx.onerror = () => resolve();
      tx.onabort = () => resolve();
    } catch {
      resolve();
    }
  });
}

// --- Unified Persistent Backend API ---

function sanitizeCaptureArea(raw: unknown): TimelapseCaptureArea {
  if (raw === 'canvas-view' || raw === 'app-window') return raw;
  return 'artwork';
}

function sanitizeCaptureResolution(raw: unknown): TimelapseCaptureResolution {
  if (raw === '720p' || raw === '1080p' || raw === '2k' || raw === '4k') return raw;
  return '1080p';
}

export async function persistSessionMeta(meta: PersistentTimelapseMeta): Promise<boolean> {
  if (isTauriRuntime()) {
    try {
      await invokeTauri('timelapse_save_meta', {
        sessionId: meta.recordingId,
        metaJson: JSON.stringify(meta),
      });
      return true;
    } catch {
      return false;
    }
  }
  return idbSaveMeta(meta);
}

export async function persistSingleFrame(
  recordingId: string,
  record: PersistentFrameRecord,
  bytes: Uint8Array,
  metaFallback?: PersistentTimelapseMeta
): Promise<boolean> {
  if (isTauriRuntime()) {
    try {
      const ext =
        record.mimeType === 'image/jpeg'
          ? 'jpg'
          : record.mimeType === 'image/png'
            ? 'png'
            : 'webp';
      const headers: Record<string, string> = {
        'x-session-id': encodeURIComponent(recordingId),
        'x-frame-index': String(record.index),
        'x-ext': ext,
        'x-timestamp': String(Math.max(0, Math.round(record.timestamp))),
        'x-width': String(Math.max(2, Math.round(record.width))),
        'x-height': String(Math.max(2, Math.round(record.height))),
      };
      if (record.captureArea) {
        headers['x-capture-area'] = encodeURIComponent(record.captureArea);
      }
      await invokeTauriRaw('timelapse_write_frame', bytes, headers);
      return true;
    } catch {
      return false;
    }
  }
  return idbWriteFrame(recordingId, record, bytes, metaFallback);
}

export async function loadPersistedSession(
  recordingId: string
): Promise<LoadedPersistentSession | null> {
  if (isTauriRuntime()) {
    try {
      const raw = await invokeTauri<{
        meta?: Record<string, unknown> | null;
        frames?: Array<Record<string, unknown>>;
        totalBytes?: number;
      }>('timelapse_load_session', { sessionId: recordingId });
      if (!raw) return null;
      const meta: PersistentTimelapseMeta | null = raw.meta
        ? {
            recordingId: String(raw.meta.recordingId || recordingId),
            documentName: String(raw.meta.documentName || ''),
            enabled: Boolean(raw.meta.enabled),
            captureArea: sanitizeCaptureArea(raw.meta.captureArea),
            captureResolution: sanitizeCaptureResolution(raw.meta.captureResolution),
            nextIndex: Math.max(0, Number(raw.meta.nextIndex) || 0),
            createdAt: Number(raw.meta.createdAt) || 0,
            updatedAt: Number(raw.meta.updatedAt) || 0,
          }
        : null;
      const frames: PersistentFrameRecord[] = Array.isArray(raw.frames)
        ? raw.frames.map((f) => ({
            index: Math.max(0, Number(f.index) || 0),
            timestamp: Number(f.timestamp) || 0,
            width: Math.max(0, Number(f.width) || 0),
            height: Math.max(0, Number(f.height) || 0),
            mimeType:
              f.mimeType === 'image/jpeg'
                ? 'image/jpeg'
                : f.mimeType === 'image/png'
                  ? 'image/png'
                  : 'image/webp',
            bytes: Math.max(0, Number(f.bytes) || 0),
            ...(f.captureArea ? { captureArea: sanitizeCaptureArea(f.captureArea) } : {}),
          }))
        : [];
      return {
        meta,
        frames,
        totalBytes: Math.max(0, Number(raw.totalBytes) || 0),
      };
    } catch {
      // Fallback to legacy `timelapse_list_frames` if running against an older backend mock
      try {
        const list = await invokeTauri<Array<[number, string]>>('timelapse_list_frames', {
          sessionId: recordingId,
        });
        const frames: PersistentFrameRecord[] = (list || []).map(([idx, ext]) => ({
          index: idx,
          timestamp: 0,
          width: 0,
          height: 0,
          mimeType:
            ext === 'jpg' || ext === 'jpeg'
              ? 'image/jpeg'
              : ext === 'png'
                ? 'image/png'
                : 'image/webp',
          bytes: 0,
        }));
        return { meta: null, frames, totalBytes: 0 };
      } catch {
        return null;
      }
    }
  }
  return idbLoadSession(recordingId);
}

export async function readPersistedFrame(
  recordingId: string,
  index: number,
  mimeType: 'image/webp' | 'image/jpeg' | 'image/png'
): Promise<Uint8Array | null> {
  if (isTauriRuntime()) {
    try {
      const raw = await invokeTauriRaw<ArrayBuffer | Uint8Array | number[]>(
        'timelapse_read_frame',
        undefined,
        {
          'x-session-id': encodeURIComponent(recordingId),
          'x-frame-index': String(index),
          'x-ext':
            mimeType === 'image/jpeg'
              ? 'jpg'
              : mimeType === 'image/png'
                ? 'png'
                : 'webp',
        }
      );
      return new Uint8Array(toArrayBuffer(raw));
    } catch {
      return null;
    }
  }
  return idbReadFrame(recordingId, index);
}

export async function listPersistedRecordings(): Promise<StoredRecordingSummary[]> {
  if (isTauriRuntime()) {
    try {
      const rows = await invokeTauri<Array<Record<string, unknown>>>('timelapse_list_sessions', {});
      return (rows || []).map((r) => ({
        recordingId: String(r.recordingId || ''),
        documentName: String(r.documentName || 'Untitled'),
        enabled: Boolean(r.enabled),
        captureArea: sanitizeCaptureArea(r.captureArea),
        captureResolution: sanitizeCaptureResolution(r.captureResolution),
        frameCount: Math.max(0, Number(r.frameCount) || 0),
        totalBytes: Math.max(0, Number(r.totalBytes) || 0),
        createdAt: Number(r.createdAt) || 0,
        updatedAt: Number(r.updatedAt) || 0,
      }));
    } catch {
      return [];
    }
  }
  return idbListSessions();
}

export async function deletePersistedRecording(recordingId: string): Promise<void> {
  removeRecordingLinks(recordingId);
  if (isTauriRuntime()) {
    await invokeTauri('timelapse_clear', { sessionId: recordingId }).catch(() => {});
    return;
  }
  await idbClearSession(recordingId);
}