import { FileData } from '@verdant-web/common'; import { Context } from '../context/context.js'; import { Disposable } from '../internal.js'; import { Sync } from '../sync/Sync.js'; import { EntityFile, EntityFileContext, MARK_FAILED, UPDATE, } from './EntityFile.js'; export class FileManager extends Disposable { private sync; private context; private cache = new Map>(); private fileData = new Map>(); constructor({ sync, context }: { sync: Sync; context: Context }) { super(); this.sync = sync; this.context = context; this.addDispose( this.context.internalEvents.subscribe( 'fileUploaded', this.onFileUploaded, ), ); } add = async (file: FileData) => { if (!file.remote) { // immediately update local files. this.updateFileData(file); } // this will download any original remote file and trigger a re-upload to the // new file's identity, in addition to storing it on disk const processedFile = await ( await this.context.files ).add(file, { cloneRemote: true }); this.updateFileData(processedFile); }; /** * Immediately returns an EntityFile to use, then either loads * the file from cache, local database, or the server. */ get = ( id: string, options: { downloadRemote?: boolean; ctx: Context; fileContext: EntityFileContext; }, ) => { const cacheKey = `${options.fileContext.oid}:${String(options.fileContext.key)}:${id}`; const cachedFile = this.cache.get(cacheKey)?.deref(); if (cachedFile) { return cachedFile; } this.cache.delete(cacheKey); const file = new EntityFile(id, options); this.cache.set(cacheKey, this.context.weakRef(file)); const data = this.fileData.get(id)?.deref(); if (data) { file[UPDATE](data); } else { this.fileData.delete(id); this.load(file); } return file; }; private updateFileData = (data: FileData) => { this.fileData.set(data.id, this.context.weakRef(data)); for (const [key, fileRef] of this.cache) { const file = fileRef.deref(); if (!file) { this.cache.delete(key); continue; } if (file.id === data.id) { file[UPDATE](data); } } }; private load = async (file: EntityFile) => { const fileData = await (await this.context.files).get(file.id); // immediately apply any file data we have if (fileData) { this.updateFileData(fileData); } if (!fileData?.url && (!fileData || fileData.remote)) { // maybe we don't have it yet, it might be on the server still. try { // if not online, enqueue this for whenever we go online. if (this.sync.status !== 'active') { this.context.log( 'info', 'Sync is not active, waiting for online to load file', file.id, file.name, ); const unsub = this.sync.subscribe('onlineChange', (online) => { if (online) { unsub(); this.load(file); } }); return; } const result = await this.sync.getFile(file.id); if (result.success) { // avoid overwriting local values except for url const copyWithUrl: FileData = { ...result.data, ...fileData, url: result.data.url, }; await (await this.context.files).update(copyWithUrl); this.updateFileData(result.data); } else { this.context.log('error', 'Failed to load file', result); if (!fileData) { // only mark failed if we have no local data to fall back to file[MARK_FAILED](result.error?.toString()); } } } catch (err) { this.context.log('error', 'Failed to load file', err); if (!fileData) { // only mark failed if we have no local data to fall back to file[MARK_FAILED](err instanceof Error ? err.message : String(err)); } } } }; private onFileUploaded = async (data: FileData) => { this.context.log('debug', 'Marking file as uploaded', data.id); (await this.context.files).onUploaded(data.id); }; }