Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

wip: files (attachments)

Nikolai Gimandf4108ced86f
diff --git a/api/.env.example b/api/.env.example
index 58f32a7..e9ee1f1 100644
--- a/api/.env.example
+++ b/api/.env.example
@@ -99,7 +99,8 @@ GITEA_INTEGRATION_CALLBACK_URL=http://localhost:1401/module/integrations/oauth/g
# CENTRIFUGO_PUBLIC_PORT=8000
# Files (task attachments)
-# Where uploaded files are stored: local (disk) or s3 (S3-compatible: AWS S3, MinIO, R2, B2).
+# Attachments are disabled until FILE_STORAGE_PROVIDER names a provider AND that provider is fully configured:
+# local needs FILE_STORAGE_LOCAL_DIR (mount it as a volume in Docker), s3 needs the FILE_STORAGE_S3_* variables below.
# Both providers may be configured at once; FILE_STORAGE_PROVIDER is the one new uploads go to.
# FILE_STORAGE_PROVIDER=local
# FILE_MAX_SIZE_MB=50
diff --git a/api/src/App.ts b/api/src/App.ts
index f701aef..45b6f3a 100644
--- a/api/src/App.ts
+++ b/api/src/App.ts
@@ -9,6 +9,7 @@ import { LoginMethods } from './tv-modules/auth/LoginMethods';
import { InviteEmailDispatcher } from './tv-modules/collaboration/InviteEmailDispatcher';
import { PublicApiUrl } from './modules/public-url';
import { validateWebhooksEnvOnStartup } from './tv-modules/webhooks/webhooks.utils';
+import { FileStorageFactory } from './tv-modules/files/storage/FileStorageFactory';
import cookieParser from 'cookie-parser';
import { registerAllEventHandlers, startAllWorkers } from './core/all-events';
@@ -21,6 +22,7 @@ export default class App {
PublicApiUrl.validateOnStartup();
InviteEmailDispatcher.validateOnStartup();
validateWebhooksEnvOnStartup();
+ FileStorageFactory.validateOnStartup();
this.app = express();
this.port = port;
diff --git a/api/src/scripts/files-migrate-storage.ts b/api/src/scripts/files-migrate-storage.ts
new file mode 100644
index 0000000..695f97d
--- /dev/null
+++ b/api/src/scripts/files-migrate-storage.ts
@@ -0,0 +1,74 @@
+import { config } from 'dotenv';
+import type { FileStorageProvider } from 'taskview-db-schemas';
+import { FilesRepository } from '../tv-modules/files/FilesRepository';
+import { FileStorageFactory } from '../tv-modules/files/storage/FileStorageFactory';
+import { FileStorageMigrator } from '../tv-modules/files/storage/FileStorageMigrator';
+
+config({ override: true });
+
+class FilesMigrateStorageCommand {
+ private readonly from: FileStorageProvider;
+ private readonly to: FileStorageProvider;
+ private readonly goalId: number | null;
+
+ constructor(argv: string[]) {
+ this.from = this.readArg(argv, '--from');
+ this.to = this.readArg(argv, '--to');
+ this.goalId = this.readOptionalNumber(argv, '--goal');
+ if (this.from === this.to) throw new Error('--from and --to must differ');
+ }
+
+ async run(): Promise<void> {
+ const factory = FileStorageFactory.getInstance();
+ for (const provider of [this.from, this.to]) {
+ if (!factory.has(provider)) throw new Error(`Provider "${provider}" is not configured in the environment`);
+ }
+
+ const migrator = new FileStorageMigrator({
+ source: factory.get(this.from),
+ target: factory.get(this.to),
+ repository: new FilesRepository(),
+ goalId: this.goalId,
+ });
+
+ console.log(`Migrating files: ${this.from} -> ${this.to}${this.goalId ? ` (project ${this.goalId})` : ''}`);
+ const report = await migrator.run();
+ console.log(`migrated: ${report.migrated}`);
+ console.log(`skipped: ${report.skipped}`);
+ console.log(`cleanup failed: ${report.cleanupFailed}`);
+ for (const error of report.errors) console.log(` ${error.fileId}: ${error.reason}`);
+ process.exitCode = report.skipped > 0 ? 1 : 0;
+ }
+
+ private readOptionalNumber(argv: string[], name: string): number | null {
+ const index = argv.indexOf(name);
+ if (index < 0) return null;
+ const value = Number(argv[index + 1]);
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive project id`);
+ return value;
+ }
+
+ private readArg(argv: string[], name: string): FileStorageProvider {
+ const index = argv.indexOf(name);
+ const value = index >= 0 ? argv[index + 1] : undefined;
+ if (value !== 'local' && value !== 's3') throw new Error(`${name} must be "local" or "s3"`);
+ return value;
+ }
+}
+
+let command: FilesMigrateStorageCommand;
+try {
+ command = new FilesMigrateStorageCommand(process.argv.slice(2));
+} catch (err) {
+ console.error((err as Error).message);
+ console.error('Usage: files:migrate --from <local|s3> --to <local|s3> [--goal <projectId>]');
+ process.exit(1);
+}
+
+command
+ .run()
+ .catch((err) => {
+ console.error((err as Error).message ?? err);
+ process.exitCode = 1;
+ })
+ .finally(() => process.exit());
diff --git a/api/src/tv-modules/files/FilesController.ts b/api/src/tv-modules/files/FilesController.ts
index 559780f..aa3b13c 100644
--- a/api/src/tv-modules/files/FilesController.ts
+++ b/api/src/tv-modules/files/FilesController.ts
@@ -27,6 +27,7 @@ const codeToStatus: Record<FileErrorCode, number> = {
too_large: 413,
invalid: 400,
storage_error: 500,
+ storage_not_configured: 503,
};
type IncomingFile = { stream: Readable; filename: string; mimeType: string };
@@ -37,6 +38,10 @@ export default class FilesController {
return res.status(codeToStatus[result.code]).send(result.message ?? result.code);
}
+ status = (req: Request, res: Response) => {
+ return res.tvJson(req.appUser.filesManager.status());
+ };
+
upload = async (req: Request, res: Response) => {
const params = FileArkTypeGoalIdParam(req.params);
if (params instanceof type.errors) return res.status(400).send(params.summary);
diff --git a/api/src/tv-modules/files/FilesManager.ts b/api/src/tv-modules/files/FilesManager.ts
index faff317..421e638 100644
--- a/api/src/tv-modules/files/FilesManager.ts
+++ b/api/src/tv-modules/files/FilesManager.ts
@@ -11,6 +11,7 @@ import { FileTooLargeError, HashingStream } from './storage/HashingStream';
import {
FILE_DOWNLOAD_TOKEN_TTL_SECONDS,
FILE_NAME_MAX_LENGTH,
+ FILE_STORAGE_NOT_CONFIGURED_MESSAGE,
type FileContent,
type FileDownloadUrl,
type FileDto,
@@ -21,6 +22,7 @@ import {
type FileListPage,
type FileRenameArgs,
type FileResult,
+ type FileStorageStatusDto,
type FileUnlinkArgs,
type FileUploadArgs,
} from './types';
@@ -51,7 +53,12 @@ export class FilesManager {
return this.storages.maxFileSizeBytes;
}
+ status(): FileStorageStatusDto {
+ return this.storages.status();
+ }
+
async upload(args: FileUploadArgs): Promise<FileResult<FileDto>> {
+ if (!this.storages.isConfigured) return fail('storage_not_configured', FILE_STORAGE_NOT_CONFIGURED_MESSAGE);
if (args.taskId !== null) {
const task = await this.tasksRepository.fetchTaskByIdNew(args.taskId);
if (!task) return fail('not_found', 'task not found');
@@ -183,6 +190,7 @@ export class FilesManager {
async issueDownloadUrl(args: FileIssueDownloadUrlArgs): Promise<FileResult<FileDownloadUrl>> {
const file = await this.repository.getById(args.fileId);
if (!file) return fail('not_found');
+ if (!this.storages.has(file.storageProvider)) return fail('storage_not_configured', FILE_STORAGE_NOT_CONFIGURED_MESSAGE);
const exp = Math.floor(Date.now() / 1000) + FILE_DOWNLOAD_TOKEN_TTL_SECONDS;
const token = new FileDownloadTokens().sign({ fileId: file.id, inline: args.inline, exp });
return ok({ url: `/module/files/content/${token}`, expiresAt: new Date(exp * 1000).toISOString() });
@@ -193,6 +201,7 @@ export class FilesManager {
if (!payload) return fail('forbidden', 'invalid or expired token');
const file = await this.repository.getById(payload.fileId);
if (!file) return fail('not_found');
+ if (!this.storages.has(file.storageProvider)) return fail('storage_not_configured', FILE_STORAGE_NOT_CONFIGURED_MESSAGE);
try {
const { stream, sizeBytes } = await this.storages.get(file.storageProvider).get(file.storageKey);
return ok({ file, stream, sizeBytes: sizeBytes || file.sizeBytes, inline: payload.inline });
diff --git a/api/src/tv-modules/files/FilesRoutes.ts b/api/src/tv-modules/files/FilesRoutes.ts
index 0eedb92..0197297 100644
--- a/api/src/tv-modules/files/FilesRoutes.ts
+++ b/api/src/tv-modules/files/FilesRoutes.ts
@@ -21,6 +21,9 @@ export default class FilesRoutes implements Routable {
}
initRoutes() {
+ // Whether attachments are enabled on this server (storage configured) and the upload size limit.
+ this.router.get('/status', [IsLoggedIn], this.controller.status);
+
// Project scope: upload (multipart, optional ?taskId= to link right away) and paginated listing.
this.router.post('/goal/:goalId', [IsLoggedIn, requireFilePermission(GoalPermissions.FILE_CAN_MANAGE, goalIdFromParam)], this.controller.upload);
this.router.get('/goal/:goalId', [IsLoggedIn, requireFilePermission(GoalPermissions.FILE_CAN_VIEW, goalIdFromParam)], this.controller.listForGoal);
diff --git a/api/src/tv-modules/files/__tests__/FileDownloadTokens.spec.ts b/api/src/tv-modules/files/__tests__/FileDownloadTokens.spec.ts
new file mode 100644
index 0000000..26689ab
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/FileDownloadTokens.spec.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import { FileDownloadTokens } from '../FileDownloadTokens';
+
+const SECRET = 'x'.repeat(64);
+const FILE_ID = '4c2a5c0e-8c3f-4a1e-9f0e-2c5b1d8e7a90';
+
+describe('FileDownloadTokens', () => {
+ it('round-trips a payload', () => {
+ const tokens = new FileDownloadTokens(SECRET);
+ const exp = Math.floor(Date.now() / 1000) + 60;
+ const payload = tokens.verify(tokens.sign({ fileId: FILE_ID, inline: true, exp }));
+ expect(payload).toEqual({ fileId: FILE_ID, inline: true, exp });
+ });
+
+ it('rejects an expired token', () => {
+ const tokens = new FileDownloadTokens(SECRET);
+ const token = tokens.sign({ fileId: FILE_ID, inline: false, exp: 1000 });
+ expect(tokens.verify(token, 1001)).toBeNull();
+ expect(tokens.verify(token, 999)).not.toBeNull();
+ });
+
+ it('rejects a tampered body and a token signed with another secret', () => {
+ const tokens = new FileDownloadTokens(SECRET);
+ const other = new FileDownloadTokens('y'.repeat(64));
+ const exp = Math.floor(Date.now() / 1000) + 60;
+ const token = tokens.sign({ fileId: FILE_ID, inline: false, exp });
+ const [body, mac] = token.split('.');
+
+ expect(tokens.verify(`${body.slice(0, -2)}AA.${mac}`)).toBeNull();
+ expect(tokens.verify(other.sign({ fileId: FILE_ID, inline: false, exp }))).toBeNull();
+ expect(tokens.verify('garbage')).toBeNull();
+ });
+
+ it('requires a secret', () => {
+ expect(() => new FileDownloadTokens('')).toThrow('ENCRYPTION_KEY');
+ });
+});
diff --git a/api/src/tv-modules/files/__tests__/FileStorageConfigReader.spec.ts b/api/src/tv-modules/files/__tests__/FileStorageConfigReader.spec.ts
new file mode 100644
index 0000000..5e0903f
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/FileStorageConfigReader.spec.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+import { FileStorageConfigReader } from '../storage/FileStorageConfigReader';
+
+const s3Env = {
+ FILE_STORAGE_S3_BUCKET: 'b',
+ FILE_STORAGE_S3_REGION: 'r',
+ FILE_STORAGE_S3_ACCESS_KEY: 'a',
+ FILE_STORAGE_S3_SECRET_KEY: 's',
+};
+
+describe('FileStorageConfigReader', () => {
+ it('is inactive when no provider is named, even if provider settings exist', () => {
+ const empty = FileStorageConfigReader.fromEnv({});
+ expect(empty.active).toBeNull();
+ expect(empty.inactiveReason).toContain('FILE_STORAGE_PROVIDER is not set');
+ expect(empty.maxFileSizeBytes).toBe(50 * 1024 * 1024);
+ expect(empty.providers).toEqual({});
+
+ const described = FileStorageConfigReader.fromEnv({ FILE_STORAGE_LOCAL_DIR: '/var/files', ...s3Env });
+ expect(described.active).toBeNull();
+ expect(described.providers.local).toEqual({ type: 'local', rootDir: '/var/files' });
+ expect(described.providers.s3).toMatchObject({ type: 's3', bucket: 'b' });
+ });
+
+ it('activates local only with an explicit directory', () => {
+ const withDir = FileStorageConfigReader.fromEnv({ FILE_STORAGE_PROVIDER: 'local', FILE_STORAGE_LOCAL_DIR: './data/files' });
+ expect(withDir.active).toBe('local');
+ expect(withDir.inactiveReason).toBeNull();
+
+ const noDir = FileStorageConfigReader.fromEnv({ FILE_STORAGE_PROVIDER: 'local' });
+ expect(noDir.active).toBeNull();
+ expect(noDir.inactiveReason).toContain('FILE_STORAGE_LOCAL_DIR');
+ expect(noDir.providers.local).toBeUndefined();
+ });
+
+ it('configures both providers when both are described, with s3 active', () => {
+ const config = FileStorageConfigReader.fromEnv({
+ FILE_STORAGE_PROVIDER: 's3',
+ FILE_STORAGE_LOCAL_DIR: '/var/files',
+ FILE_STORAGE_S3_ENDPOINT: 'http://minio:9000',
+ FILE_STORAGE_S3_FORCE_PATH_STYLE: 'true',
+ FILE_MAX_SIZE_MB: '5',
+ ...s3Env,
+ });
+ expect(config.active).toBe('s3');
+ expect(config.maxFileSizeBytes).toBe(5 * 1024 * 1024);
+ expect(config.providers.local).toEqual({ type: 'local', rootDir: '/var/files' });
+ expect(config.providers.s3).toMatchObject({ type: 's3', bucket: 'b', endpoint: 'http://minio:9000', forcePathStyle: true });
+ });
+
+ it('does not configure local when s3 is active and no local dir is given', () => {
+ const config = FileStorageConfigReader.fromEnv({ FILE_STORAGE_PROVIDER: 's3', ...s3Env });
+ expect(config.providers.local).toBeUndefined();
+ });
+
+ it('is inactive with the missing variables listed when s3 is named but incomplete', () => {
+ const config = FileStorageConfigReader.fromEnv({ FILE_STORAGE_PROVIDER: 's3', FILE_STORAGE_S3_BUCKET: 'b' });
+ expect(config.active).toBeNull();
+ expect(config.inactiveReason).toContain('FILE_STORAGE_S3_REGION');
+ expect(config.inactiveReason).toContain('FILE_STORAGE_S3_SECRET_KEY');
+ expect(config.inactiveReason).not.toContain('FILE_STORAGE_S3_BUCKET');
+ });
+
+ it('is inactive for an unknown provider instead of throwing', () => {
+ const config = FileStorageConfigReader.fromEnv({ FILE_STORAGE_PROVIDER: 'ftp' });
+ expect(config.active).toBeNull();
+ expect(config.inactiveReason).toContain('"ftp" is not supported');
+ });
+});
diff --git a/api/src/tv-modules/files/__tests__/FileStorageFactory.spec.ts b/api/src/tv-modules/files/__tests__/FileStorageFactory.spec.ts
new file mode 100644
index 0000000..d3cb8c8
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/FileStorageFactory.spec.ts
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { $logger } from '../../../modules/logget';
+import { FILE_STORAGE_DOCS_URL } from '../storage/FileStorageConfigReader';
+import { FileStorageFactory } from '../storage/FileStorageFactory';
+import { FileStorageNotConfiguredError } from '../storage/FileStorageNotConfiguredError';
+
+const STORAGE_VARS = ['FILE_STORAGE_PROVIDER', 'FILE_STORAGE_LOCAL_DIR', 'FILE_STORAGE_S3_BUCKET'] as const;
+
+describe('FileStorageFactory startup', () => {
+ const saved: Partial<Record<(typeof STORAGE_VARS)[number], string | undefined>> = {};
+
+ beforeEach(() => {
+ for (const name of STORAGE_VARS) saved[name] = process.env[name];
+ FileStorageFactory.resetInstance();
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ vi.spyOn(console, 'log').mockImplementation(() => undefined);
+ vi.spyOn($logger, 'warn').mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ for (const name of STORAGE_VARS) {
+ if (saved[name] === undefined) delete process.env[name];
+ else process.env[name] = saved[name];
+ }
+ FileStorageFactory.resetInstance();
+ vi.restoreAllMocks();
+ });
+
+ it('warns on the console and in the log, and refuses the active storage, when no provider is set', () => {
+ delete process.env.FILE_STORAGE_PROVIDER;
+ delete process.env.FILE_STORAGE_LOCAL_DIR;
+ delete process.env.FILE_STORAGE_S3_BUCKET;
+
+ FileStorageFactory.validateOnStartup();
+
+ const expected = expect.stringMatching(/\[files\] File storage is not configured.*FILE_STORAGE_PROVIDER is not set.*FILE_STORAGE_LOCAL_DIR.*FILE_STORAGE_S3_\*/);
+ expect(console.warn).toHaveBeenCalledWith(expected);
+ expect($logger.warn).toHaveBeenCalledWith(expected);
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining(FILE_STORAGE_DOCS_URL));
+
+ const factory = FileStorageFactory.getInstance();
+ expect(factory.isConfigured).toBe(false);
+ expect(factory.status().enabled).toBe(false);
+ expect(() => factory.active()).toThrow(FileStorageNotConfiguredError);
+ });
+
+ it('names the missing variable when the provider is set but incomplete', () => {
+ process.env.FILE_STORAGE_PROVIDER = 'local';
+ delete process.env.FILE_STORAGE_LOCAL_DIR;
+
+ FileStorageFactory.validateOnStartup();
+
+ expect($logger.warn).toHaveBeenCalledWith(expect.stringContaining('FILE_STORAGE_PROVIDER=local requires FILE_STORAGE_LOCAL_DIR'));
+ expect(FileStorageFactory.getInstance().isConfigured).toBe(false);
+ });
+
+ it('stays quiet and serves the active storage when the provider is configured', () => {
+ process.env.FILE_STORAGE_PROVIDER = 'local';
+ process.env.FILE_STORAGE_LOCAL_DIR = './.test-data/files';
+
+ FileStorageFactory.validateOnStartup();
+
+ expect(console.warn).not.toHaveBeenCalled();
+ expect($logger.warn).not.toHaveBeenCalled();
+ expect(console.log).toHaveBeenCalledWith('[files] File storage: local');
+ const factory = FileStorageFactory.getInstance();
+ expect(factory.status()).toEqual({ enabled: true, maxFileSizeBytes: factory.maxFileSizeBytes });
+ expect(factory.active().provider).toBe('local');
+ });
+});
diff --git a/api/src/tv-modules/files/__tests__/FileStorageMigrator.spec.ts b/api/src/tv-modules/files/__tests__/FileStorageMigrator.spec.ts
new file mode 100644
index 0000000..7becb32
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/FileStorageMigrator.spec.ts
@@ -0,0 +1,161 @@
+import { createHash } from 'node:crypto';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Readable } from 'node:stream';
+import type { FilesSchemaTypeForSelect, FileStorageProvider } from 'taskview-db-schemas';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import type { FilesRepository } from '../FilesRepository';
+import type { FileStorage } from '../storage/FileStorage';
+import { FileStorageMigrator } from '../storage/FileStorageMigrator';
+import { LocalFileStorage } from '../storage/LocalFileStorage';
+import type { FileListByProviderArgs, FileUpdateStorageProviderArgs } from '../types';
+
+class FakeS3Storage implements FileStorage {
+ readonly provider = 's3' as const;
+ private readonly inner: LocalFileStorage;
+
+ constructor(rootDir: string) {
+ this.inner = new LocalFileStorage({ type: 'local', rootDir });
+ }
+
+ put(args: Parameters<FileStorage['put']>[0]) { return this.inner.put(args); }
+ get(key: string) { return this.inner.get(key); }
+ delete(key: string) { return this.inner.delete(key); }
+ exists(key: string) { return this.inner.exists(key); }
+}
+
+class InMemoryFilesRepository {
+ rows: FilesSchemaTypeForSelect[] = [];
+
+ async listByProvider(args: FileListByProviderArgs) {
+ return this.rows
+ .filter((r) => r.storageProvider === args.provider && !args.excludeIds.includes(r.id))
+ .slice(0, args.limit);
+ }
+
+ async updateStorageProvider(args: FileUpdateStorageProviderArgs) {
+ const row = this.rows.find((r) => r.id === args.fileId);
+ if (row) row.storageProvider = args.provider;
+ }
+}
+
+const row = (id: string, goalId: number, checksum: string, provider: FileStorageProvider): FilesSchemaTypeForSelect => ({
+ id,
+ goalId,
+ uploaderId: 1,
+ uploaderEmail: '[email protected]',
+ name: `${id}.txt`,
+ originalName: `${id}.txt`,
+ mimeType: 'text/plain',
+ sizeBytes: 0,
+ checksumSha256: checksum,
+ storageProvider: provider,
+ storageKey: `${goalId}/${id}`,
+ createdAt: new Date(),
+ editedAt: new Date(),
+});
+
+const sha = (s: string) => createHash('sha256').update(s).digest('hex');
+
+describe('FileStorageMigrator', () => {
+ let dirA = '';
+ let dirB = '';
+ let source: FileStorage;
+ let target: FileStorage;
+ let repository: InMemoryFilesRepository;
+
+ beforeEach(async () => {
+ dirA = await mkdtemp(join(tmpdir(), 'tv-mig-a-'));
+ dirB = await mkdtemp(join(tmpdir(), 'tv-mig-b-'));
+ source = new LocalFileStorage({ type: 'local', rootDir: dirA });
+ target = new FakeS3Storage(dirB);
+ repository = new InMemoryFilesRepository();
+ });
+
+ afterEach(async () => {
+ await rm(dirA, { recursive: true, force: true });
+ await rm(dirB, { recursive: true, force: true });
+ });
+
+ const migrator = () =>
+ new FileStorageMigrator({ source, target, repository: repository as unknown as FilesRepository, batchSize: 2 });
+
+ it('moves every file, switches the row and removes the source copy', async () => {
+ for (const id of ['a', 'b', 'c']) {
+ await source.put({ key: `1/${id}`, stream: Readable.from([Buffer.from(`content-${id}`)]), mimeType: 'text/plain' });
+ repository.rows.push(row(id, 1, sha(`content-${id}`), 'local'));
+ }
+
+ const report = await migrator().run();
+
+ expect(report).toEqual({ migrated: 3, skipped: 0, cleanupFailed: 0, errors: [] });
+ for (const id of ['a', 'b', 'c']) {
+ expect(await source.exists(`1/${id}`)).toBe(false);
+ expect(await target.exists(`1/${id}`)).toBe(true);
+ expect(repository.rows.find((r) => r.id === id)?.storageProvider).toBe('s3');
+ }
+ });
+
+ it('skips a file whose content does not match its checksum and keeps the source', async () => {
+ await source.put({ key: '1/ok', stream: Readable.from([Buffer.from('good')]), mimeType: 'text/plain' });
+ await source.put({ key: '1/bad', stream: Readable.from([Buffer.from('tampered')]), mimeType: 'text/plain' });
+ repository.rows.push(row('ok', 1, sha('good'), 'local'), row('bad', 1, sha('original'), 'local'));
+
+ const report = await migrator().run();
+
+ expect(report.migrated).toBe(1);
+ expect(report.skipped).toBe(1);
+ expect(report.errors).toEqual([{ fileId: 'bad', reason: 'checksum mismatch' }]);
+ expect(await source.exists('1/bad')).toBe(true);
+ expect(await target.exists('1/bad')).toBe(false);
+ expect(repository.rows.find((r) => r.id === 'bad')?.storageProvider).toBe('local');
+ });
+
+ it('is idempotent: a second run has nothing to do and reversing moves files back', async () => {
+ await source.put({ key: '1/x', stream: Readable.from([Buffer.from('x')]), mimeType: 'text/plain' });
+ repository.rows.push(row('x', 1, sha('x'), 'local'));
+
+ expect((await migrator().run()).migrated).toBe(1);
+ expect((await migrator().run()).migrated).toBe(0);
+
+ const back = new FileStorageMigrator({ source: target, target: source, repository: repository as unknown as FilesRepository });
+ expect((await back.run()).migrated).toBe(1);
+ expect(await source.exists('1/x')).toBe(true);
+ expect(repository.rows[0].storageProvider).toBe('local');
+ });
+
+ it('reports a file whose source stream fails mid-transfer instead of hanging', async () => {
+ await source.put({ key: '1/ok', stream: Readable.from([Buffer.from('good')]), mimeType: 'text/plain' });
+ repository.rows.push(row('broken', 1, sha('whatever'), 'local'), row('ok', 1, sha('good'), 'local'));
+ const failingSource: FileStorage = {
+ provider: 'local',
+ put: (args) => source.put(args),
+ delete: (key) => source.delete(key),
+ exists: (key) => source.exists(key),
+ get: async (key) => {
+ if (key !== '1/broken') return source.get(key);
+ const stream = new Readable({
+ read() {
+ this.push(Buffer.from('partial'));
+ this.destroy(new Error('connection reset'));
+ },
+ });
+ return { stream, sizeBytes: 100 };
+ },
+ };
+ const migrator = new FileStorageMigrator({ source: failingSource, target, repository: repository as unknown as FilesRepository });
+
+ const report = await migrator.run();
+
+ expect(report.migrated).toBe(1);
+ expect(report.skipped).toBe(1);
+ expect(report.errors).toEqual([{ fileId: 'broken', reason: 'connection reset' }]);
+ expect(await target.exists('1/broken')).toBe(false);
+ expect(repository.rows.find((r) => r.id === 'broken')?.storageProvider).toBe('local');
+ });
+
+ it('refuses identical providers', () => {
+ expect(() => new FileStorageMigrator({ source, target: source, repository: repository as unknown as FilesRepository })).toThrow('must differ');
+ });
+});
diff --git a/api/src/tv-modules/files/__tests__/Files.integration.spec.ts b/api/src/tv-modules/files/__tests__/Files.integration.spec.ts
new file mode 100644
index 0000000..fb93050
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/Files.integration.spec.ts
@@ -0,0 +1,392 @@
+import axios, { type AxiosInstance } from 'axios';
+import fs from 'fs/promises';
+import http from 'http';
+import { join } from 'path';
+import type { FileStorageProvider } from 'taskview-db-schemas';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { Database } from '../../../modules/db';
+import { GoalPermissions } from '../../../types/auth.types';
+import { FileDownloadTokens } from '../FileDownloadTokens';
+import { FilesRepository } from '../FilesRepository';
+import { FileStorageFactory } from '../storage/FileStorageFactory';
+import { FileStorageMigrator } from '../storage/FileStorageMigrator';
+import type { FileDto, FileListPage } from '../types';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+const port = 1823;
+const url = `http://localhost:${port}`;
+const MIGRATION_DIR = join(__dirname, '../../../migrations/taskview/sql/1.67.0');
+const LOGIN = '[email protected]';
+const PASSWORD = 'user1!#Q';
+
+const api: AxiosInstance = axios.create({
+ baseURL: url,
+ validateStatus: () => true,
+ httpAgent: new http.Agent({ keepAlive: false }),
+});
+
+let server: http.Server;
+let jwt = '';
+let goalId = 0;
+let otherGoalId = 0;
+let taskId = 0;
+const createdTokenIds: number[] = [];
+
+const asUser = () => ({ headers: { Authorization: `Bearer ${jwt}` } });
+
+async function upload(args: { goalId: number; taskId?: number; name: string; content: Buffer | string; mime?: string; auth?: { headers: Record<string, string> } }) {
+ const form = new FormData();
+ const part = typeof args.content === 'string' ? args.content : new Uint8Array(args.content);
+ form.append('file', new Blob([part], { type: args.mime ?? 'text/plain' }), args.name);
+ const query = args.taskId ? `?taskId=${args.taskId}` : '';
+ return api.post<{ response: FileDto }>(`/module/files/goal/${args.goalId}${query}`, form, args.auth ?? asUser());
+}
+
+async function issueToken(allowedPermissions: string[]) {
+ const response = await api.post('/module/api-tokens', { name: 'files-probe', allowedPermissions, allowedGoalIds: [] }, asUser());
+ expect(response.status).toBe(200);
+ createdTokenIds.push(response.data.response.item.id);
+ return { headers: { Authorization: `Bearer ${response.data.response.token}` } };
+}
+
+async function createTask(inGoal: number, description: string): Promise<number> {
+ const response = await api.post('/module/tasks', { goalId: inGoal, description }, asUser());
+ expect(response.status).toBe(200);
+ return response.data.response.id;
+}
+
+async function deleteAllFilesOf(inGoal: number) {
+ const page = await api.get<{ response: FileListPage }>(`/module/files/goal/${inGoal}?limit=200`, asUser());
+ for (const file of page.data.response?.items ?? []) {
+ await api.delete(`/module/files/file/${file.id}`, asUser());
+ }
+}
+
+function useProvider(provider: FileStorageProvider) {
+ process.env.FILE_STORAGE_PROVIDER = provider;
+ FileStorageFactory.resetInstance();
+}
+
+describe('Files module', () => {
+ beforeAll(async () => {
+ const db = Database.getInstance();
+ const client = await db.getClient();
+ for (const file of (await fs.readdir(MIGRATION_DIR)).sort()) {
+ await client.query(await fs.readFile(join(MIGRATION_DIR, file), 'utf-8'));
+ }
+ client.release();
+
+ server = new App(port).listen();
+
+ const login = await api.post('/module/auth/login', { login: LOGIN, password: PASSWORD });
+ expect(login.status).toBe(200);
+ jwt = login.data.access;
+
+ const goal = await api.post('/module/goals', { name: `files-it-${Date.now()}` }, asUser());
+ expect(goal.status).toBe(200);
+ goalId = goal.data.response.id;
+ const other = await api.post('/module/goals', { name: `files-it-other-${Date.now()}` }, asUser());
+ expect(other.status).toBe(200);
+ otherGoalId = other.data.response.id;
+
+ taskId = await createTask(goalId, 'task with files');
+ });
+
+ afterAll(async () => {
+ for (const provider of ['local', 's3'] as const) {
+ useProvider(provider);
+ await deleteAllFilesOf(goalId);
+ await deleteAllFilesOf(otherGoalId);
+ }
+ for (const id of [goalId, otherGoalId]) {
+ if (id) await api.delete('/module/goals', { ...asUser(), data: { goalId: id } });
+ }
+ for (const id of createdTokenIds) {
+ await api.delete('/module/api-tokens', { ...asUser(), data: { id } });
+ }
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }, 30_000);
+
+ it('reports storage as disabled and refuses uploads and downloads until a provider is configured', async () => {
+ useProvider('local');
+ const uploaded = await upload({ goalId, name: 'orphan.txt', content: 'orphan' });
+ expect(uploaded.status).toBe(200);
+ const fileId = uploaded.data.response.id;
+ const issued = await api.post(`/module/files/file/${fileId}/download-url`, {}, asUser());
+ expect(issued.status).toBe(200);
+ const contentUrl: string = issued.data.response.url;
+
+ const saved = { provider: process.env.FILE_STORAGE_PROVIDER, dir: process.env.FILE_STORAGE_LOCAL_DIR };
+ delete process.env.FILE_STORAGE_PROVIDER;
+ delete process.env.FILE_STORAGE_LOCAL_DIR;
+ FileStorageFactory.resetInstance();
+ try {
+ const status = await api.get('/module/files/status', asUser());
+ expect(status.status).toBe(200);
+ expect(status.data.response).toEqual({ enabled: false, maxFileSizeBytes: 1024 * 1024 });
+
+ const rejected = await upload({ goalId, name: 'never.txt', content: 'never' });
+ expect(rejected.status).toBe(503);
+ expect(rejected.data).toContain('not configured');
+
+ const link = await api.post(`/module/files/file/${fileId}/download-url`, {}, asUser());
+ expect(link.status).toBe(503);
+
+ const content = await api.get(contentUrl);
+ expect(content.status).toBe(503);
+ expect(content.data).toContain('not configured');
+
+ const listed = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}`, asUser());
+ expect(listed.status).toBe(200);
+ expect(listed.data.response.items.map((f) => f.id)).toContain(fileId);
+ } finally {
+ process.env.FILE_STORAGE_PROVIDER = saved.provider;
+ process.env.FILE_STORAGE_LOCAL_DIR = saved.dir;
+ FileStorageFactory.resetInstance();
+ }
+
+ const status = await api.get('/module/files/status', asUser());
+ expect(status.data.response.enabled).toBe(true);
+ expect((await api.get(contentUrl)).status).toBe(200);
+ expect((await api.delete(`/module/files/file/${fileId}`, asUser())).status).toBe(200);
+ });
+
+ it('seeds the files permission group with localized descriptions', async () => {
+ const result = await Database.getInstance().query<{ name: string; description_locales: Record<string, string> }>(
+ 'SELECT name, description_locales FROM tv_auth.permissions WHERE permission_group = 7 ORDER BY name'
+ );
+ expect(result.rows.map((r) => r.name)).toEqual(['file_can_manage', 'file_can_view']);
+ expect(result.rows[0].description_locales.ru).toBeTruthy();
+ });
+
+ it('grants file permissions to the roles of a new project', async () => {
+ const result = await Database.getInstance().query<{ role: string; permission: string }>(
+ `SELECT r.name AS role, p.name AS permission
+ FROM collaboration.roles r
+ JOIN collaboration.permissions_to_role pr ON pr.role_id = r.id
+ JOIN tv_auth.permissions p ON p.id = pr.permission_id
+ WHERE r.goal_id = $1 AND p.name LIKE 'file_%'
+ ORDER BY r.name, p.name`,
+ [goalId]
+ );
+ const byRole = new Map<string, string[]>();
+ for (const r of result.rows) byRole.set(r.role, [...(byRole.get(r.role) ?? []), r.permission]);
+ expect(byRole.get('editor')).toEqual(['file_can_manage', 'file_can_view']);
+ expect(byRole.get('executor')).toEqual(['file_can_view']);
+ });
+
+ describe.each(['local', 's3'] as const)('with the %s provider', (provider) => {
+ let taskFile: FileDto;
+ let projectFile: FileDto;
+
+ beforeAll(() => useProvider(provider));
+
+ it('uploads a file straight into a task', async () => {
+ const response = await upload({ goalId, taskId, name: 'spec.txt', content: 'hello attachments' });
+ expect(response.status).toBe(200);
+ taskFile = response.data.response;
+ expect(taskFile).toMatchObject({
+ goalId,
+ name: 'spec.txt',
+ originalName: 'spec.txt',
+ mimeType: 'text/plain',
+ sizeBytes: 17,
+ uploaderEmail: LOGIN,
+ linkedTaskIds: [taskId],
+ });
+
+ const row = await new FilesRepository().getById(taskFile.id);
+ expect(row?.storageProvider).toBe(provider);
+ expect(row?.storageKey).toBe(`${goalId}/${taskFile.id}`);
+ expect(row?.checksumSha256).toHaveLength(64);
+ expect(await FileStorageFactory.getInstance().get(provider).exists(row!.storageKey)).toBe(true);
+ });
+
+ it('lists the file under the task and counts it on the task row', async () => {
+ const files = await api.get(`/module/files/task/${taskId}`, asUser());
+ expect(files.status).toBe(200);
+ expect(files.data.response.map((f: FileDto) => f.id)).toContain(taskFile.id);
+
+ const task = await api.get(`/module/tasks/${taskId}`, asUser());
+ expect(task.status).toBe(200);
+ expect(task.data.response.filesCount).toBeGreaterThanOrEqual(1);
+ });
+
+ it('uploads a file into the project, then searches and filters the project list', async () => {
+ const response = await upload({ goalId, name: `Диаграмма-${provider}.png`, content: Buffer.from([1, 2, 3, 4]), mime: 'image/png' });
+ expect(response.status).toBe(200);
+ projectFile = response.data.response;
+ expect(projectFile.linkedTaskIds).toEqual([]);
+
+ const all = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}`, asUser());
+ expect(all.status).toBe(200);
+ expect(all.data.response.items.map((f) => f.id)).toEqual(expect.arrayContaining([taskFile.id, projectFile.id]));
+
+ const search = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}?search=диаграмма-${provider}`, asUser());
+ expect(search.data.response.items.map((f) => f.id)).toEqual([projectFile.id]);
+
+ const images = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}?type=image`, asUser());
+ expect(images.data.response.items.every((f) => f.mimeType.startsWith('image/'))).toBe(true);
+ expect(images.data.response.items.map((f) => f.id)).toContain(projectFile.id);
+
+ const documents = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}?type=document`, asUser());
+ expect(documents.data.response.items.map((f) => f.id)).not.toContain(projectFile.id);
+ });
+
+ it('paginates the project list with a cursor', async () => {
+ const first = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}?limit=1`, asUser());
+ expect(first.data.response.items).toHaveLength(1);
+ expect(first.data.response.nextCursor).toBeTruthy();
+
+ const second = await api.get<{ response: FileListPage }>(
+ `/module/files/goal/${goalId}?limit=1&cursor=${encodeURIComponent(first.data.response.nextCursor as string)}`,
+ asUser()
+ );
+ expect(second.data.response.items).toHaveLength(1);
+ expect(second.data.response.items[0].id).not.toBe(first.data.response.items[0].id);
+ });
+
+ it('links an existing project file to a task and refuses files of another project', async () => {
+ const linked = await api.post(`/module/files/task/${taskId}/link`, { fileIds: [projectFile.id] }, asUser());
+ expect(linked.status).toBe(200);
+ expect(linked.data.response[0].linkedTaskIds).toEqual([taskId]);
+
+ const foreign = await upload({ goalId: otherGoalId, name: 'foreign.txt', content: 'x' });
+ expect(foreign.status).toBe(200);
+ const crossProject = await api.post(`/module/files/task/${taskId}/link`, { fileIds: [foreign.data.response.id] }, asUser());
+ expect(crossProject.status).toBe(403);
+
+ const missing = await api.post(
+ `/module/files/task/${taskId}/link`,
+ { fileIds: ['00000000-0000-4000-8000-000000000000'] },
+ asUser()
+ );
+ expect(missing.status).toBe(404);
+ });
+
+ it('unlinks a file from a task without deleting it', async () => {
+ const unlinked = await api.delete(`/module/files/task/${taskId}/file/${projectFile.id}`, asUser());
+ expect(unlinked.status).toBe(200);
+
+ const again = await api.delete(`/module/files/task/${taskId}/file/${projectFile.id}`, asUser());
+ expect(again.status).toBe(404);
+
+ const stillThere = await api.get(`/module/files/file/${projectFile.id}`, asUser());
+ expect(stillThere.status).toBe(200);
+ expect(stillThere.data.response.linkedTaskIds).toEqual([]);
+ });
+
+ it('renames a file and keeps the original extension', async () => {
+ const renamed = await api.patch(`/module/files/file/${taskFile.id}`, { name: 'renamed' }, asUser());
+ expect(renamed.status).toBe(200);
+ expect(renamed.data.response.name).toBe('renamed.txt');
+ expect(renamed.data.response.originalName).toBe('spec.txt');
+
+ const long = await api.patch(`/module/files/file/${taskFile.id}`, { name: 'x'.repeat(300) }, asUser());
+ expect(long.status).toBe(200);
+ expect(long.data.response.name).toHaveLength(255);
+ expect(long.data.response.name.endsWith('.txt')).toBe(true);
+
+ const emoji = await api.patch(`/module/files/file/${taskFile.id}`, { name: `${'😀'.repeat(300)}.txt` }, asUser());
+ expect(emoji.status).toBe(200);
+ expect(Array.from(emoji.data.response.name)).toHaveLength(255);
+ expect(emoji.data.response.name.endsWith('.txt')).toBe(true);
+
+ const back = await api.patch(`/module/files/file/${taskFile.id}`, { name: 'renamed' }, asUser());
+ expect(back.status).toBe(200);
+ });
+
+ it('serves the content through a short-lived signed url, inline or as attachment', async () => {
+ const attachment = await api.post(`/module/files/file/${taskFile.id}/download-url`, { inline: false }, asUser());
+ expect(attachment.status).toBe(200);
+ expect(attachment.data.response.url).toMatch(/^\/module\/files\/content\//);
+
+ const content = await api.get(attachment.data.response.url, { responseType: 'arraybuffer' });
+ expect(content.status).toBe(200);
+ expect(Buffer.from(content.data).toString()).toBe('hello attachments');
+ expect(content.headers['content-type']).toContain('text/plain');
+ expect(content.headers['content-length']).toBe('17');
+ expect(content.headers['content-disposition']).toContain('attachment');
+ expect(content.headers['content-disposition']).toContain('renamed.txt');
+ expect(content.headers['cross-origin-resource-policy']).toBe('cross-origin');
+
+ const inline = await api.post(`/module/files/file/${taskFile.id}/download-url`, { inline: true }, asUser());
+ const inlineContent = await api.get(inline.data.response.url);
+ expect(inlineContent.headers['content-disposition']).toMatch(/^inline/);
+ });
+
+ it('rejects forged and expired content tokens', async () => {
+ expect((await api.get('/module/files/content/not-a-token')).status).toBe(403);
+ const expired = new FileDownloadTokens().sign({ fileId: taskFile.id, inline: false, exp: 1 });
+ expect((await api.get(`/module/files/content/${expired}`)).status).toBe(403);
+ });
+
+ it('rejects a file over the size limit and leaves nothing behind', async () => {
+ const before = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}?limit=200`, asUser());
+ const tooBig = await upload({ goalId, name: 'big.bin', content: Buffer.alloc(1024 * 1024 + 1) });
+ expect(tooBig.status).toBe(413);
+ const after = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}?limit=200`, asUser());
+ expect(after.data.response.items).toHaveLength(before.data.response.items.length);
+ });
+
+ it('deletes a file forever: links, row and stored object', async () => {
+ const row = await new FilesRepository().getById(taskFile.id);
+ const removed = await api.delete(`/module/files/file/${taskFile.id}`, asUser());
+ expect(removed.status).toBe(200);
+
+ expect((await api.get(`/module/files/file/${taskFile.id}`, asUser())).status).toBe(404);
+ const files = await api.get(`/module/files/task/${taskId}`, asUser());
+ expect(files.data.response.map((f: FileDto) => f.id)).not.toContain(taskFile.id);
+ expect(await FileStorageFactory.getInstance().get(provider).exists(row!.storageKey)).toBe(false);
+ });
+
+ it('enforces file permissions and authentication', async () => {
+ expect((await api.get(`/module/files/goal/${goalId}`)).status).toBe(401);
+ expect((await upload({ goalId, name: 'anon.txt', content: 'x', auth: { headers: {} } })).status).toBe(401);
+
+ const viewer = await issueToken([GoalPermissions.FILE_CAN_VIEW]);
+ expect((await api.get(`/module/files/goal/${goalId}`, viewer)).status).toBe(200);
+ expect((await upload({ goalId, name: 'viewer.txt', content: 'x', auth: viewer })).status).toBe(403);
+ expect((await api.delete(`/module/files/file/${projectFile.id}`, viewer)).status).toBe(403);
+
+ const stranger = await issueToken([GoalPermissions.TIMETRACKING_CAN_VIEW]);
+ expect((await api.get(`/module/files/goal/${goalId}`, stranger)).status).toBe(403);
+ expect((await api.get(`/module/files/task/${taskId}`, stranger)).status).toBe(403);
+
+ expect((await api.get(`/module/files/goal/999999999`, asUser())).status).toBe(403);
+ });
+ });
+
+ describe('storage migration between providers', () => {
+ it('moves files local -> s3 and back while content keeps being served', async () => {
+ useProvider('local');
+ const uploaded = await upload({ goalId, name: 'migrate-me.txt', content: 'moving bytes' });
+ expect(uploaded.status).toBe(200);
+ const fileId = uploaded.data.response.id;
+ const repository = new FilesRepository();
+ const factory = FileStorageFactory.getInstance();
+ const key = (await repository.getById(fileId))!.storageKey;
+
+ const forward = await new FileStorageMigrator({ source: factory.get('local'), target: factory.get('s3'), repository, goalId }).run();
+ expect(forward.skipped).toBe(0);
+ expect(forward.migrated).toBeGreaterThanOrEqual(1);
+ expect((await repository.getById(fileId))?.storageProvider).toBe('s3');
+ expect(await factory.get('local').exists(key)).toBe(false);
+ expect(await factory.get('s3').exists(key)).toBe(true);
+
+ const link = await api.post(`/module/files/file/${fileId}/download-url`, { inline: false }, asUser());
+ const content = await api.get(link.data.response.url);
+ expect(content.status).toBe(200);
+ expect(content.data).toBe('moving bytes');
+
+ const back = await new FileStorageMigrator({ source: factory.get('s3'), target: factory.get('local'), repository, goalId }).run();
+ expect(back.skipped).toBe(0);
+ expect((await repository.getById(fileId))?.storageProvider).toBe('local');
+ expect(await factory.get('local').exists(key)).toBe(true);
+ });
+ });
+});
diff --git a/api/src/tv-modules/files/__tests__/HashingStream.spec.ts b/api/src/tv-modules/files/__tests__/HashingStream.spec.ts
new file mode 100644
index 0000000..cd88266
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/HashingStream.spec.ts
@@ -0,0 +1,23 @@
+import { createHash } from 'node:crypto';
+import { Readable, Writable } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+import { describe, expect, it } from 'vitest';
+import { FileTooLargeError, HashingStream } from '../storage/HashingStream';
+
+const sink = () => new Writable({ write(_chunk, _enc, cb) { cb(); } });
+
+describe('HashingStream', () => {
+ it('computes sha256 and counts bytes while passing data through', async () => {
+ const payload = Buffer.from('hello files');
+ const hashing = new HashingStream();
+ await pipeline(Readable.from([payload.subarray(0, 5), payload.subarray(5)]), hashing, sink());
+
+ expect(hashing.sizeBytes).toBe(payload.length);
+ expect(hashing.digestHex()).toBe(createHash('sha256').update(payload).digest('hex'));
+ });
+
+ it('fails the pipeline once the limit is exceeded', async () => {
+ const hashing = new HashingStream(4);
+ await expect(pipeline(Readable.from([Buffer.from('12345')]), hashing, sink())).rejects.toBeInstanceOf(FileTooLargeError);
+ });
+});
diff --git a/api/src/tv-modules/files/__tests__/LocalFileStorage.spec.ts b/api/src/tv-modules/files/__tests__/LocalFileStorage.spec.ts
new file mode 100644
index 0000000..7b07e8d
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/LocalFileStorage.spec.ts
@@ -0,0 +1,52 @@
+import { mkdtemp, readdir, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Readable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { LocalFileStorage } from '../storage/LocalFileStorage';
+
+const read = async (stream: Readable) => Buffer.concat(await stream.toArray());
+
+describe('LocalFileStorage', () => {
+ let rootDir = '';
+ let storage: LocalFileStorage;
+
+ beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'tv-files-'));
+ storage = new LocalFileStorage({ type: 'local', rootDir });
+ });
+
+ afterEach(async () => {
+ await rm(rootDir, { recursive: true, force: true });
+ });
+
+ it('stores, reads, checks and deletes an object by key', async () => {
+ const stored = await storage.put({ key: '7/abc', stream: Readable.from([Buffer.from('payload')]), mimeType: 'text/plain' });
+ expect(stored).toEqual({ key: '7/abc', sizeBytes: 7 });
+
+ const got = await storage.get('7/abc');
+ expect(got.sizeBytes).toBe(7);
+ expect((await read(got.stream)).toString()).toBe('payload');
+ expect(await storage.exists('7/abc')).toBe(true);
+
+ await storage.delete('7/abc');
+ expect(await storage.exists('7/abc')).toBe(false);
+ await expect(storage.delete('7/abc')).resolves.toBeUndefined();
+ });
+
+ it('leaves no partial file behind when the source stream fails', async () => {
+ const failing = new Readable({
+ read() {
+ this.push(Buffer.from('half'));
+ this.destroy(new Error('boom'));
+ },
+ });
+ await expect(storage.put({ key: '7/broken', stream: failing, mimeType: 'text/plain' })).rejects.toThrow('boom');
+ expect(await storage.exists('7/broken')).toBe(false);
+ expect(await readdir(join(rootDir, '7'))).toEqual([]);
+ });
+
+ it('refuses keys that escape the root directory', async () => {
+ await expect(storage.get('../etc/passwd')).rejects.toThrow('escapes the root directory');
+ });
+});
diff --git a/api/src/tv-modules/files/__tests__/S3FileStorage.integration.spec.ts b/api/src/tv-modules/files/__tests__/S3FileStorage.integration.spec.ts
new file mode 100644
index 0000000..b20edd9
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/S3FileStorage.integration.spec.ts
@@ -0,0 +1,40 @@
+import { randomBytes } from 'node:crypto';
+import { Readable } from 'node:stream';
+import { describe, expect, it } from 'vitest';
+import { FileStorageConfigReader } from '../storage/FileStorageConfigReader';
+import { S3FileStorage } from '../storage/S3FileStorage';
+import type { S3FileStorageConfig } from '../storage/storage.types';
+
+// Runs against MinIO from dev-containers-test/docker-compose.minio.yml (see vitest.config.ts env).
+const config = FileStorageConfigReader.fromEnv().providers.s3 as S3FileStorageConfig;
+const storage = new S3FileStorage(config);
+const read = async (stream: Readable) => Buffer.concat(await stream.toArray());
+
+describe('S3FileStorage (MinIO)', () => {
+ it('stores, reads, checks and deletes an object by key', async () => {
+ const key = `it/${Date.now()}/small`;
+ const stored = await storage.put({ key, stream: Readable.from([Buffer.from('payload')]), mimeType: 'text/plain' });
+ expect(stored).toEqual({ key, sizeBytes: 7 });
+
+ const got = await storage.get(key);
+ expect(got.sizeBytes).toBe(7);
+ expect((await read(got.stream)).toString()).toBe('payload');
+ expect(await storage.exists(key)).toBe(true);
+
+ await storage.delete(key);
+ expect(await storage.exists(key)).toBe(false);
+ await expect(storage.get(key)).rejects.toBeTruthy();
+ });
+
+ it('streams a file larger than one multipart chunk unchanged', async () => {
+ const key = `it/${Date.now()}/large`;
+ const payload = randomBytes(6 * 1024 * 1024);
+ const stored = await storage.put({ key, stream: Readable.from([payload]), mimeType: 'application/octet-stream' });
+ expect(stored.sizeBytes).toBe(payload.length);
+
+ const got = await storage.get(key);
+ expect(got.sizeBytes).toBe(payload.length);
+ expect((await read(got.stream)).equals(payload)).toBe(true);
+ await storage.delete(key);
+ }, 30_000);
+});
diff --git a/api/src/tv-modules/files/storage/FileStorageConfigReader.ts b/api/src/tv-modules/files/storage/FileStorageConfigReader.ts
new file mode 100644
index 0000000..1e75390
--- /dev/null
+++ b/api/src/tv-modules/files/storage/FileStorageConfigReader.ts
@@ -0,0 +1,74 @@
+import type { FileStorageProvider } from 'taskview-db-schemas';
+import type {
+ FileStorageActiveResolution,
+ FileStorageConfig,
+ FileStorageProviderConfig,
+ FileStorageResolveActiveArgs,
+ FileStorageS3Reading,
+} from './storage.types';
+
+const DEFAULT_MAX_FILE_SIZE_MB = 50;
+const S3_REQUIRED_VARS = ['FILE_STORAGE_S3_BUCKET', 'FILE_STORAGE_S3_REGION', 'FILE_STORAGE_S3_ACCESS_KEY', 'FILE_STORAGE_S3_SECRET_KEY'] as const;
+
+export const FILE_STORAGE_DOCS_URL = 'https://taskview.tech/docs/configuration/environment-variables#files-task-attachments';
+
+// Attachments are active only when FILE_STORAGE_PROVIDER names a provider AND that provider has all of its settings.
+// Anything else leaves the module inactive with a reason, so the API still starts and can explain what is missing.
+export class FileStorageConfigReader {
+ static fromEnv(env: NodeJS.ProcessEnv = process.env): FileStorageConfig {
+ const providers: FileStorageConfig['providers'] = {};
+
+ const local = FileStorageConfigReader.readLocal(env);
+ if (local) providers.local = local;
+ const s3 = FileStorageConfigReader.readS3(env);
+ if (s3.config) providers.s3 = s3.config;
+
+ const { active, inactiveReason } = FileStorageConfigReader.resolveActive({ env, providers, s3Missing: s3.missing });
+
+ const maxMb = Number(env.FILE_MAX_SIZE_MB ?? DEFAULT_MAX_FILE_SIZE_MB);
+ return {
+ maxFileSizeBytes: (Number.isFinite(maxMb) && maxMb > 0 ? maxMb : DEFAULT_MAX_FILE_SIZE_MB) * 1024 * 1024,
+ active,
+ inactiveReason,
+ providers,
+ };
+ }
+
+ private static resolveActive(args: FileStorageResolveActiveArgs): FileStorageActiveResolution {
+ const raw = args.env.FILE_STORAGE_PROVIDER?.trim();
+ if (!raw) return { active: null, inactiveReason: 'FILE_STORAGE_PROVIDER is not set' };
+ if (raw !== 'local' && raw !== 's3') {
+ return { active: null, inactiveReason: `FILE_STORAGE_PROVIDER="${raw}" is not supported, use "local" or "s3"` };
+ }
+ const active: FileStorageProvider = raw;
+ if (active === 'local' && !args.providers.local) {
+ return { active: null, inactiveReason: 'FILE_STORAGE_PROVIDER=local requires FILE_STORAGE_LOCAL_DIR (in Docker mount it as a volume)' };
+ }
+ if (active === 's3' && !args.providers.s3) {
+ return { active: null, inactiveReason: `FILE_STORAGE_PROVIDER=s3 requires ${args.s3Missing.join(', ')}` };
+ }
+ return { active, inactiveReason: null };
+ }
+
+ private static readLocal(env: NodeJS.ProcessEnv): FileStorageProviderConfig | null {
+ const rootDir = env.FILE_STORAGE_LOCAL_DIR?.trim();
+ return rootDir ? { type: 'local', rootDir } : null;
+ }
+
+ private static readS3(env: NodeJS.ProcessEnv): FileStorageS3Reading {
+ const missing = S3_REQUIRED_VARS.filter((name) => !env[name]?.trim());
+ if (missing.length > 0) return { config: null, missing };
+ return {
+ config: {
+ type: 's3',
+ bucket: env.FILE_STORAGE_S3_BUCKET as string,
+ region: env.FILE_STORAGE_S3_REGION as string,
+ endpoint: env.FILE_STORAGE_S3_ENDPOINT || null,
+ accessKeyId: env.FILE_STORAGE_S3_ACCESS_KEY as string,
+ secretAccessKey: env.FILE_STORAGE_S3_SECRET_KEY as string,
+ forcePathStyle: env.FILE_STORAGE_S3_FORCE_PATH_STYLE === 'true',
+ },
+ missing: [],
+ };
+ }
+}
diff --git a/api/src/tv-modules/files/storage/FileStorageFactory.ts b/api/src/tv-modules/files/storage/FileStorageFactory.ts
new file mode 100644
index 0000000..ee41ee3
--- /dev/null
+++ b/api/src/tv-modules/files/storage/FileStorageFactory.ts
@@ -0,0 +1,88 @@
+import type { FileStorageProvider } from 'taskview-db-schemas';
+import { $logger } from '../../../modules/logget';
+import type { FileStorageStatusDto } from '../types';
+import type { FileStorage } from './FileStorage';
+import { FILE_STORAGE_DOCS_URL, FileStorageConfigReader } from './FileStorageConfigReader';
+import { FileStorageNotConfiguredError } from './FileStorageNotConfiguredError';
+import { LocalFileStorage } from './LocalFileStorage';
+import { S3FileStorage } from './S3FileStorage';
+import type { FileStorageConfig, FileStorageProviderConfig } from './storage.types';
+
+export class FileStorageFactory {
+ private static instance: FileStorageFactory | null = null;
+ private readonly config: FileStorageConfig;
+ private readonly storages = new Map<FileStorageProvider, FileStorage>();
+
+ constructor(config: FileStorageConfig) {
+ this.config = config;
+ for (const providerConfig of Object.values(config.providers)) {
+ const storage = FileStorageFactory.build(providerConfig);
+ this.storages.set(storage.provider, storage);
+ }
+ }
+
+ static getInstance(): FileStorageFactory {
+ if (!FileStorageFactory.instance) {
+ FileStorageFactory.instance = new FileStorageFactory(FileStorageConfigReader.fromEnv());
+ }
+ return FileStorageFactory.instance;
+ }
+
+ static resetInstance(): void {
+ FileStorageFactory.instance = null;
+ }
+
+ static validateOnStartup(): void {
+ const factory = FileStorageFactory.getInstance();
+ if (factory.isConfigured) {
+ console.log(`[files] File storage: ${factory.config.active}`);
+ return;
+ }
+ const message =
+ `[files] File storage is not configured - task attachments are disabled (${factory.inactiveReason}). ` +
+ 'To enable them set FILE_STORAGE_PROVIDER=local with FILE_STORAGE_LOCAL_DIR (mount it as a volume in Docker), ' +
+ `or FILE_STORAGE_PROVIDER=s3 with the FILE_STORAGE_S3_* variables. See ${FILE_STORAGE_DOCS_URL}`;
+ console.warn(message);
+ $logger.warn(message);
+ }
+
+ static build(config: FileStorageProviderConfig): FileStorage {
+ switch (config.type) {
+ case 'local':
+ return new LocalFileStorage(config);
+ case 's3':
+ return new S3FileStorage(config);
+ }
+ }
+
+ get maxFileSizeBytes(): number {
+ return this.config.maxFileSizeBytes;
+ }
+
+ get isConfigured(): boolean {
+ return this.config.active !== null;
+ }
+
+ get inactiveReason(): string | null {
+ return this.config.inactiveReason;
+ }
+
+ status(): FileStorageStatusDto {
+ return { enabled: this.isConfigured, maxFileSizeBytes: this.config.maxFileSizeBytes };
+ }
+
+ active(): FileStorage {
+ if (this.config.active === null) throw new FileStorageNotConfiguredError(this.config.inactiveReason ?? 'unknown reason');
+ return this.get(this.config.active);
+ }
+
+ get(provider: FileStorageProvider): FileStorage {
+ const storage = this.storages.get(provider);
+ if (!storage) throw new Error(`File storage provider is not configured: ${provider}`);
+ return storage;
+ }
+
+ has(provider: FileStorageProvider): boolean {
+ return this.storages.has(provider);
+ }
+}
diff --git a/api/src/tv-modules/files/storage/FileStorageMigrator.ts b/api/src/tv-modules/files/storage/FileStorageMigrator.ts
new file mode 100644
index 0000000..77d33c7
--- /dev/null
+++ b/api/src/tv-modules/files/storage/FileStorageMigrator.ts
@@ -0,0 +1,71 @@
+import type { FilesRepository } from '../FilesRepository';
+import type { FileStorage } from './FileStorage';
+import { HashingStream } from './HashingStream';
+import type { FileMigrationReport, FileStorageMigratorArgs } from './storage.types';
+
+const DEFAULT_BATCH_SIZE = 100;
+
+export class FileStorageMigrator {
+ private readonly source: FileStorage;
+ private readonly target: FileStorage;
+ private readonly repository: FilesRepository;
+ private readonly batchSize: number;
+ private readonly goalId: number | null;
+
+ constructor(args: FileStorageMigratorArgs) {
+ if (args.source.provider === args.target.provider) {
+ throw new Error('Source and target storage providers must differ');
+ }
+ this.source = args.source;
+ this.target = args.target;
+ this.repository = args.repository;
+ this.batchSize = args.batchSize ?? DEFAULT_BATCH_SIZE;
+ this.goalId = args.goalId ?? null;
+ }
+
+ async run(): Promise<FileMigrationReport> {
+ const report: FileMigrationReport = { migrated: 0, skipped: 0, cleanupFailed: 0, errors: [] };
+ const skippedIds: string[] = [];
+
+ while (true) {
+ const batch = await this.repository.listByProvider({
+ provider: this.source.provider,
+ excludeIds: skippedIds,
+ limit: this.batchSize,
+ goalId: this.goalId,
+ });
+ if (batch.length === 0) break;
+
+ for (const file of batch) {
+ try {
+ const { stream } = await this.source.get(file.storageKey);
+ const hashing = new HashingStream();
+ stream.on('error', (err) => hashing.destroy(err));
+ hashing.on('error', () => stream.destroy());
+ await this.target.put({ key: file.storageKey, stream: stream.pipe(hashing), mimeType: file.mimeType });
+
+ if (hashing.digestHex() !== file.checksumSha256) {
+ await this.target.delete(file.storageKey).catch(() => undefined);
+ throw new Error('checksum mismatch');
+ }
+
+ await this.repository.updateStorageProvider({ fileId: file.id, provider: this.target.provider });
+ report.migrated += 1;
+
+ try {
+ await this.source.delete(file.storageKey);
+ } catch (err) {
+ report.cleanupFailed += 1;
+ report.errors.push({ fileId: file.id, reason: `cleanup failed: ${(err as Error).message}` });
+ }
+ } catch (err) {
+ report.skipped += 1;
+ skippedIds.push(file.id);
+ report.errors.push({ fileId: file.id, reason: (err as Error).message });
+ }
+ }
+ }
+
+ return report;
+ }
+}
diff --git a/api/src/tv-modules/files/storage/FileStorageNotConfiguredError.ts b/api/src/tv-modules/files/storage/FileStorageNotConfiguredError.ts
new file mode 100644
index 0000000..4950029
--- /dev/null
+++ b/api/src/tv-modules/files/storage/FileStorageNotConfiguredError.ts
@@ -0,0 +1,9 @@
+export class FileStorageNotConfiguredError extends Error {
+ readonly reason: string;
+
+ constructor(reason: string) {
+ super(`File storage is not configured: ${reason}`);
+ this.name = 'FileStorageNotConfiguredError';
+ this.reason = reason;
+ }
+}
diff --git a/api/src/tv-modules/files/storage/HashingStream.ts b/api/src/tv-modules/files/storage/HashingStream.ts
new file mode 100644
index 0000000..9254339
--- /dev/null
+++ b/api/src/tv-modules/files/storage/HashingStream.ts
@@ -0,0 +1,42 @@
+import { createHash, type Hash } from 'node:crypto';
+import { Transform, type TransformCallback } from 'node:stream';
+
+export class HashingStream extends Transform {
+ private readonly hash: Hash;
+ private bytes = 0;
+ private readonly maxBytes: number | null;
+
+ constructor(maxBytes: number | null = null) {
+ super();
+ this.hash = createHash('sha256');
+ this.maxBytes = maxBytes;
+ }
+
+ _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {
+ this.bytes += chunk.length;
+ if (this.maxBytes !== null && this.bytes > this.maxBytes) {
+ callback(new FileTooLargeError(this.maxBytes));
+ return;
+ }
+ this.hash.update(chunk);
+ callback(null, chunk);
+ }
+
+ get sizeBytes(): number {
+ return this.bytes;
+ }
+
+ digestHex(): string {
+ return this.hash.digest('hex');
+ }
+}
+
+export class FileTooLargeError extends Error {
+ readonly maxBytes: number;
+
+ constructor(maxBytes: number) {
+ super(`File exceeds the limit of ${maxBytes} bytes`);
+ this.name = 'FileTooLargeError';
+ this.maxBytes = maxBytes;
+ }
+}
diff --git a/api/src/tv-modules/files/storage/LocalFileStorage.ts b/api/src/tv-modules/files/storage/LocalFileStorage.ts
new file mode 100644
index 0000000..a14be6d
--- /dev/null
+++ b/api/src/tv-modules/files/storage/LocalFileStorage.ts
@@ -0,0 +1,56 @@
+import { createReadStream, createWriteStream } from 'node:fs';
+import { access, mkdir, rename, stat, unlink } from 'node:fs/promises';
+import { dirname, join, resolve, sep } from 'node:path';
+import { pipeline } from 'node:stream/promises';
+import type { FileStorage } from './FileStorage';
+import type { LocalFileStorageConfig, StorageGetResult, StoragePutArgs, StoredObject } from './storage.types';
+
+export class LocalFileStorage implements FileStorage {
+ readonly provider = 'local' as const;
+ private readonly rootDir: string;
+
+ constructor(config: LocalFileStorageConfig) {
+ this.rootDir = resolve(config.rootDir);
+ }
+
+ async put(args: StoragePutArgs): Promise<StoredObject> {
+ const finalPath = this.resolveKey(args.key);
+ const tempPath = `${finalPath}.part`;
+ await mkdir(dirname(finalPath), { recursive: true });
+ try {
+ await pipeline(args.stream, createWriteStream(tempPath));
+ await rename(tempPath, finalPath);
+ } catch (err) {
+ await unlink(tempPath).catch(() => undefined);
+ throw err;
+ }
+ const info = await stat(finalPath);
+ return { key: args.key, sizeBytes: info.size };
+ }
+
+ async get(key: string): Promise<StorageGetResult> {
+ const path = this.resolveKey(key);
+ const info = await stat(path);
+ return { stream: createReadStream(path), sizeBytes: info.size };
+ }
+
+ async delete(key: string): Promise<void> {
+ await unlink(this.resolveKey(key)).catch((err: NodeJS.ErrnoException) => {
+ if (err.code !== 'ENOENT') throw err;
+ });
+ }
+
+ async exists(key: string): Promise<boolean> {
+ return access(this.resolveKey(key))
+ .then(() => true)
+ .catch(() => false);
+ }
+
+ private resolveKey(key: string): string {
+ const path = resolve(join(this.rootDir, key));
+ if (!path.startsWith(this.rootDir + sep)) {
+ throw new Error(`Storage key escapes the root directory: ${key}`);
+ }
+ return path;
+ }
+}
diff --git a/api/src/tv-modules/files/storage/S3FileStorage.ts b/api/src/tv-modules/files/storage/S3FileStorage.ts
new file mode 100644
index 0000000..cfd9a5e
--- /dev/null
+++ b/api/src/tv-modules/files/storage/S3FileStorage.ts
@@ -0,0 +1,65 @@
+import type { Readable } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, S3Client } from '@aws-sdk/client-s3';
+import { Upload } from '@aws-sdk/lib-storage';
+import type { FileStorage } from './FileStorage';
+import { HashingStream } from './HashingStream';
+import type { S3FileStorageConfig, StorageGetResult, StoragePutArgs, StoredObject } from './storage.types';
+
+export class S3FileStorage implements FileStorage {
+ readonly provider = 's3' as const;
+ private readonly client: S3Client;
+ private readonly bucket: string;
+
+ constructor(config: S3FileStorageConfig) {
+ this.bucket = config.bucket;
+ this.client = new S3Client({
+ region: config.region,
+ endpoint: config.endpoint ?? undefined,
+ forcePathStyle: config.forcePathStyle,
+ credentials: { accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey },
+ });
+ }
+
+ async put(args: StoragePutArgs): Promise<StoredObject> {
+ const counter = new HashingStream();
+ // pipeline (not pipe) so a failure of the source stream reaches the upload instead of hanging it.
+ const feeding = pipeline(args.stream, counter);
+ const upload = new Upload({
+ client: this.client,
+ params: { Bucket: this.bucket, Key: args.key, Body: counter, ContentType: args.mimeType },
+ });
+ try {
+ await Promise.all([feeding, upload.done()]);
+ } catch (err) {
+ await upload.abort().catch(() => undefined);
+ throw err;
+ }
+ return { key: args.key, sizeBytes: counter.sizeBytes };
+ }
+
+ async get(key: string): Promise<StorageGetResult> {
+ const result = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: key }));
+ if (!result.Body) throw new Error(`Empty body for storage key ${key}`);
+ return { stream: result.Body as Readable, sizeBytes: result.ContentLength ?? 0 };
+ }
+
+ async delete(key: string): Promise<void> {
+ await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: key }));
+ }
+
+ async exists(key: string): Promise<boolean> {
+ try {
+ await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: key }));
+ return true;
+ } catch (err) {
+ if (this.isNotFound(err)) return false;
+ throw err;
+ }
+ }
+
+ private isNotFound(err: unknown): boolean {
+ const e = err as { name?: string; $metadata?: { httpStatusCode?: number } };
+ return e?.name === 'NotFound' || e?.name === 'NoSuchKey' || e?.$metadata?.httpStatusCode === 404;
+ }
+}
diff --git a/api/src/tv-modules/files/storage/storage.types.ts b/api/src/tv-modules/files/storage/storage.types.ts
index 90ea7f0..7edf047 100644
--- a/api/src/tv-modules/files/storage/storage.types.ts
+++ b/api/src/tv-modules/files/storage/storage.types.ts
@@ -22,10 +22,27 @@ export type FileStorageProviderConfig = LocalFileStorageConfig | S3FileStorageCo
export type FileStorageConfig = {
maxFileSizeBytes: number;
- active: FileStorageProvider;
+ active: FileStorageProvider | null;
+ inactiveReason: string | null;
providers: Partial<Record<FileStorageProvider, FileStorageProviderConfig>>;
};
+export type FileStorageActiveResolution = {
+ active: FileStorageProvider | null;
+ inactiveReason: string | null;
+};
+
+export type FileStorageResolveActiveArgs = {
+ env: NodeJS.ProcessEnv;
+ providers: FileStorageConfig['providers'];
+ s3Missing: string[];
+};
+
+export type FileStorageS3Reading = {
+ config: S3FileStorageConfig | null;
+ missing: string[];
+};
+
export type StoragePutArgs = {
key: string;
stream: Readable;
diff --git a/api/src/tv-modules/files/types.ts b/api/src/tv-modules/files/types.ts
index 301f015..36eddea 100644
--- a/api/src/tv-modules/files/types.ts
+++ b/api/src/tv-modules/files/types.ts
@@ -123,7 +123,13 @@ export type FileContent = {
inline: boolean;
};
-export type FileErrorCode = 'not_found' | 'forbidden' | 'too_large' | 'invalid' | 'storage_error';
+export type FileErrorCode = 'not_found' | 'forbidden' | 'too_large' | 'invalid' | 'storage_error' | 'storage_not_configured';
+export const FILE_STORAGE_NOT_CONFIGURED_MESSAGE = 'File storage is not configured on this server';
+
+export type FileStorageStatusDto = {
+ enabled: boolean;
+ maxFileSizeBytes: number;
+};
export type FileResult<T> = { ok: true; data: T } | { ok: false; code: FileErrorCode; message?: string };
export type FileListCursor = {
diff --git a/docs/1.getting-started/2.installation.md b/docs/1.getting-started/2.installation.md
index cb2e506..987709d 100644
--- a/docs/1.getting-started/2.installation.md
+++ b/docs/1.getting-started/2.installation.md
@@ -51,6 +51,10 @@ JWT_SIGN="secret"
ACCESS_LIFE_TIME="3d"
REFRESH_LIFE_TIME="9d"
+# Task attachments: disabled until a provider is configured. Mount the directory as a volume (see compose below).
+FILE_STORAGE_PROVIDER=local
+FILE_STORAGE_LOCAL_DIR=/usr/src/app/data/files
+
SMTP_HOST=smtp
SMTP_PORT=587
SMTP_USERNAME=
@@ -141,6 +145,9 @@ services:
- ./.env.taskview
volumes:
- ./logs:/usr/src/app/logs
+ # Task attachments. Keep this volume, otherwise files live inside the container and vanish when it is recreated.
+ # Enable attachments with FILE_STORAGE_PROVIDER=local and FILE_STORAGE_LOCAL_DIR=/usr/src/app/data/files in .env.taskview.
+ - ./files:/usr/src/app/data/files
#- /local/AuthKey.p8:/usr/src/app/AuthKey.p8
networks: [backend]
diff --git a/docs/4.configuration/1.environment-variables.md b/docs/4.configuration/1.environment-variables.md
index 5ea97f5..9f69801 100644
--- a/docs/4.configuration/1.environment-variables.md
+++ b/docs/4.configuration/1.environment-variables.md
@@ -249,18 +249,29 @@ Both Centrifugo and Firebase are optional. If not configured, their respective c
Uploaded files are stored outside PostgreSQL; the database keeps only metadata (name, size, SHA-256 checksum, which provider holds the bytes). Two providers are supported and both may be configured at the same time, which is how an instance is migrated from one to the other without downtime.
+Attachments are **off until a provider is configured**: `FILE_STORAGE_PROVIDER` must name a provider and all of that provider's variables must be set. Otherwise the API starts normally, logs a warning with what is missing, hides the upload buttons in the web app and answers uploads with `503`. There is no default directory on purpose: in Docker an unmounted directory lives inside the container and is lost when the container is recreated.
+
| Variable | Required | Default | Description |
|---|---|---|---|
-| `FILE_STORAGE_PROVIDER` | No | `local` | Provider that receives new uploads: `local` or `s3`. Its settings must be present. |
+| `FILE_STORAGE_PROVIDER` | To enable files | - | Provider that receives new uploads: `local` or `s3`. Its settings must be present, otherwise attachments stay disabled. |
| `FILE_MAX_SIZE_MB` | No | `50` | Maximum size of one uploaded file in megabytes. |
-| `FILE_STORAGE_LOCAL_DIR` | No | `./data/files` | Directory for the `local` provider. In Docker mount it as a volume. |
-| `FILE_STORAGE_S3_BUCKET` | For `s3` | - | Bucket name. Setting it enables the `s3` provider. |
+| `FILE_STORAGE_LOCAL_DIR` | For `local` | - | Directory for the `local` provider. In Docker mount it as a volume, e.g. `/taskview/files:/usr/src/app/data/files`. |
+| `FILE_STORAGE_S3_BUCKET` | For `s3` | - | Bucket name. |
| `FILE_STORAGE_S3_REGION` | For `s3` | - | Region, e.g. `us-east-1`. Any value works for MinIO. |
| `FILE_STORAGE_S3_ENDPOINT` | No | - | Custom endpoint for S3-compatible storage (MinIO, Cloudflare R2, Backblaze B2). Leave empty for AWS. |
| `FILE_STORAGE_S3_ACCESS_KEY` | For `s3` | - | Access key id. |
| `FILE_STORAGE_S3_SECRET_KEY` | For `s3` | - | Secret access key. |
| `FILE_STORAGE_S3_FORCE_PATH_STYLE` | No | `false` | Set to `true` for MinIO and most self-hosted S3-compatible servers. |
+### Encryption at rest
+
+TaskView does not encrypt file contents itself: the API writes the bytes it received and the database keeps only metadata. Encrypt at the storage layer instead; the API does not need to know about it.
+
+- `s3` - enable server-side encryption on the bucket (SSE-S3 or SSE-KMS on AWS, SSE on MinIO). Uploads and downloads keep working unchanged.
+- `local` - keep `FILE_STORAGE_LOCAL_DIR` on an encrypted disk or volume (for example LUKS on Linux). Back up the encryption key separately from the data.
+
+This protects the files on a lost disk, a leaked backup or an exposed bucket. Anyone who can call the API with file permissions still reads the files normally - that part is governed by the project roles `file_can_view` and `file_can_manage`.
+
### Moving files between providers
1. Add the settings of the new provider while `FILE_STORAGE_PROVIDER` still points to the old one.
@@ -356,7 +367,7 @@ TELEGRAM_WEBHOOK_SECRET=
# CENTRIFUGO_TOKEN_SECRET=your_centrifugo_token_secret
# CENTRIFUGO_PUBLIC_URL=wss://api.example.com/centrifugo/connection/websocket
-# Files
+# Files (attachments stay disabled until a provider is configured; mount the directory as a volume)
FILE_STORAGE_PROVIDER=local
FILE_STORAGE_LOCAL_DIR=/usr/src/app/data/files
# FILE_MAX_SIZE_MB=50
diff --git a/docs/6.faq/1.index.md b/docs/6.faq/1.index.md
index dbc4392..24493eb 100644
--- a/docs/6.faq/1.index.md
+++ b/docs/6.faq/1.index.md
@@ -63,11 +63,11 @@ Yes. Any task can have subtasks for breaking work into smaller steps. Subtasks a
### Can I attach files to tasks?
-Currently, TaskView does not support file attachments. You can add links and descriptions in the task notes using the rich text editor.
+Yes. Files can be attached to tasks and stored either on the server's local disk or in S3-compatible storage. You can also add links and descriptions in the task notes using the rich text editor.
### Does TaskView have time tracking?
-TaskView does not include built-in time tracking. It focuses on task management, Kanban workflows, and team collaboration.
+Yes. Start a timer on a task or log an entry manually. Every entry has a billable flag, so reports can be filtered to billable hours only. Reports are available by day, by person, by task, and by contributor, and the same data is exposed through the API and the MCP server.
### Does TaskView support financial tracking?
diff --git a/taskview-packages/taskview-api/src/api/files.ts b/taskview-packages/taskview-api/src/api/files.ts
index 2f561ca..ff45dd3 100644
--- a/taskview-packages/taskview-api/src/api/files.ts
+++ b/taskview-packages/taskview-api/src/api/files.ts
@@ -8,6 +8,7 @@ import type {
TvFileListArgs,
TvFileListPage,
TvFileRenameArgs,
+ TvFileStorageStatus,
TvFileUnlinkArgs,
TvFileUploadArgs,
} from './files.types';
@@ -15,6 +16,10 @@ import type {
export default class TvFilesApi extends TvApiBase {
protected moduleUrl = '/module/files';
+ public async status() {
+ return this.request(this.$axios.get<AppResponse<TvFileStorageStatus>>(`${this.moduleUrl}/status`));
+ }
+
public async upload(args: TvFileUploadArgs) {
const form = new FormData();
form.append('file', args.file, args.fileName);
diff --git a/taskview-packages/taskview-api/src/api/files.types.ts b/taskview-packages/taskview-api/src/api/files.types.ts
index 4d17cee..f6710b6 100644
--- a/taskview-packages/taskview-api/src/api/files.types.ts
+++ b/taskview-packages/taskview-api/src/api/files.types.ts
@@ -23,6 +23,11 @@ export type TvFileDownloadUrl = {
expiresAt: string;
};
+export type TvFileStorageStatus = {
+ enabled: boolean;
+ maxFileSizeBytes: number;
+};
+
export type TvFileListArgs = {
goalId: number;
search?: string | null;
diff --git a/web/src/bootstrap.ts b/web/src/bootstrap.ts
index 1ea52cf..c680ddb 100644
--- a/web/src/bootstrap.ts
+++ b/web/src/bootstrap.ts
@@ -69,6 +69,11 @@ function buildRoutes(extensions: TvWebExtension[]): RouteRecordRaw[] {
name: 'sprints',
component: () => import('./pages/user/sprints.vue'),
},
+ {
+ path: ':projectId/files',
+ name: 'files',
+ component: () => import('./pages/user/files.vue'),
+ },
{
path: ':projectId/collaboration',
name: 'collaboration',
diff --git a/web/src/components/features/files/FilesGrid.vue b/web/src/components/features/files/FilesGrid.vue
new file mode 100644
index 0000000..7b90ee4
--- /dev/null
+++ b/web/src/components/features/files/FilesGrid.vue
@@ -0,0 +1,52 @@
+<template>
+ <div
+ class="grid gap-3 grid-cols-2 @md:grid-cols-3 @xl:grid-cols-4"
+ data-testid="files-grid"
+ >
+ <FileUploadingTile
+ v-for="upload in uploads"
+ :key="upload.id"
+ :upload="upload"
+ @retry="emit('retry', upload.id)"
+ @cancel="emit('cancel', upload.id)"
+ />
+ <FileTile
+ v-for="file in files"
+ :key="file.id"
+ :file="file"
+ :can-manage="canManage"
+ :in-task="inTask"
+ @open="emit('open', file)"
+ @download="emit('download', file)"
+ @open-in-new-tab="emit('openInNewTab', file)"
+ @rename="emit('rename', file)"
+ @unlink="emit('unlink', file)"
+ @delete="emit('delete', file)"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import type { TvFile } from 'taskview-api'
+import type { FileUploadItem } from '@/types/files.types'
+import FileTile from './parts/FileTile.vue'
+import FileUploadingTile from './parts/FileUploadingTile.vue'
+
+defineProps<{
+ files: TvFile[]
+ uploads: FileUploadItem[]
+ canManage: boolean
+ inTask: boolean
+}>()
+
+const emit = defineEmits<{
+ open: [file: TvFile]
+ download: [file: TvFile]
+ openInNewTab: [file: TvFile]
+ rename: [file: TvFile]
+ unlink: [file: TvFile]
+ delete: [file: TvFile]
+ retry: [uploadId: string]
+ cancel: [uploadId: string]
+}>()
+</script>
diff --git a/web/src/components/features/files/FilesProjectTab.vue b/web/src/components/features/files/FilesProjectTab.vue
new file mode 100644
index 0000000..a0b4f12
--- /dev/null
+++ b/web/src/components/features/files/FilesProjectTab.vue
@@ -0,0 +1,194 @@
+<template>
+ <div
+ ref="root"
+ class="relative flex flex-col gap-4 @container"
+ data-testid="files-project-tab"
+ >
+ <div
+ class="sticky top-0 z-10 flex flex-col @md:flex-row gap-2 @md:items-center bg-default p-2"
+ >
+ <UInput
+ v-model="search"
+ :placeholder="t('files.searchPlaceholder')"
+ icon="i-lucide-search"
+ variant="soft"
+ size="xl"
+ class="flex-1"
+ data-testid="files-search"
+ />
+ <UTabs
+ v-model="type"
+ :items="typeItems"
+ :content="false"
+ :ui="{ list: 'rounded-xl', trigger: 'rounded-lg', indicator: 'rounded-lg' }"
+ />
+ <FilesUploadButton
+ v-if="canUpload"
+ :label="t('files.upload')"
+ size="xl"
+ @click="openDialog"
+ />
+ </div>
+
+ <div
+ v-if="isDragging && canUpload"
+ class="absolute inset-2 z-20 rounded-2xl border-2 border-dashed border-primary bg-primary/5 flex items-center justify-center pointer-events-none"
+ >
+ <p class="text-primary font-medium">
+ {{ t('files.dropHint') }}
+ </p>
+ </div>
+
+ <div class="flex flex-col gap-4 px-2">
+ <UAlert
+ v-if="!storageEnabled"
+ color="warning"
+ variant="soft"
+ icon="i-lucide-hard-drive"
+ :title="t('files.storageDisabled')"
+ :description="t('files.storageDisabledHint')"
+ data-testid="files-storage-disabled"
+ />
+ <div
+ v-if="uploads.length > 0"
+ class="grid gap-3 grid-cols-2 @md:grid-cols-4"
+ >
+ <FileUploadingTile
+ v-for="item in uploads"
+ :key="item.id"
+ :upload="item"
+ @retry="retry(item.id)"
+ @cancel="cancel(item.id)"
+ />
+ </div>
+
+ <div
+ v-if="!project.loading && project.items.length === 0"
+ class="flex flex-col items-center gap-2 py-16 text-center text-muted"
+ >
+ <UIcon
+ name="i-lucide-folder-open"
+ class="size-8 text-dimmed"
+ />
+ <p>{{ search ? t('files.project.nothingFound') : t('files.project.empty') }}</p>
+ </div>
+
+ <div
+ v-else
+ class="flex flex-col gap-2"
+ >
+ <FileProjectRow
+ v-for="file in project.items"
+ :key="file.id"
+ :file="file"
+ :can-manage="canManage"
+ @open="actions.open(file)"
+ @link-to-task="linkTarget = file"
+ @download="actions.download(file)"
+ @open-in-new-tab="actions.openInNewTab(file)"
+ @rename="actions.renameTarget.value = file"
+ @delete="actions.deleteTarget.value = file"
+ />
+ <div
+ v-if="project.nextCursor || project.loading"
+ class="flex justify-center py-3"
+ >
+ <UButton
+ :label="t('files.loadMore')"
+ color="neutral"
+ variant="ghost"
+ :loading="project.loading"
+ @click="filesStore.loadMoreForGoal()"
+ />
+ </div>
+ </div>
+ </div>
+
+ <FilesViewer
+ v-model:index="actions.viewerIndex.value"
+ :files="project.items"
+ />
+ <FileRenameDialog
+ v-model:file="actions.renameTarget.value"
+ @submit="actions.rename"
+ />
+ <FileDeleteDialog
+ v-model:file="actions.deleteTarget.value"
+ :current-task-id="null"
+ @confirm="actions.deleteForever"
+ />
+ <FileTaskPickerDialog
+ v-model:file="linkTarget"
+ :goal-id="goalId"
+ @select="linkToTask"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, toRef, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { storeToRefs } from 'pinia'
+import { useDebounceFn } from '@vueuse/core'
+import type { TvFile, TvFileKindFilter } from 'taskview-api'
+import { useFilesStore } from '@/stores/files.store'
+import { useFileUpload } from '@/composables/useFileUpload'
+import { useFileDropZone } from '@/composables/useFileDropZone'
+import { useFileActions } from '@/composables/useFileActions'
+import FilesUploadButton from './FilesUploadButton.vue'
+import FilesViewer from './FilesViewer.vue'
+import FileUploadingTile from './parts/FileUploadingTile.vue'
+import FileProjectRow from './parts/FileProjectRow.vue'
+import FileRenameDialog from './parts/FileRenameDialog.vue'
+import FileDeleteDialog from './parts/FileDeleteDialog.vue'
+import FileTaskPickerDialog from './parts/FileTaskPickerDialog.vue'
+
+const props = defineProps<{
+ goalId: number
+ canManage: boolean
+}>()
+
+const { t } = useI18n()
+const toast = useToast()
+const filesStore = useFilesStore()
+const { project } = storeToRefs(filesStore)
+
+const root = ref<HTMLElement | null>(null)
+const search = ref('')
+const type = ref<TvFileKindFilter>('all')
+const linkTarget = ref<TvFile | null>(null)
+
+const typeItems = computed(() => [
+ { value: 'all', label: t('files.filters.all') },
+ { value: 'image', label: t('files.filters.images') },
+ { value: 'document', label: t('files.filters.documents') },
+])
+
+const goalId = toRef(props, 'goalId')
+const storageEnabled = computed(() => filesStore.storageEnabled)
+const canUpload = computed(() => props.canManage && storageEnabled.value)
+const noTask = ref<number | null>(null)
+const { uploads, upload, openDialog, retry, cancel } = useFileUpload({ goalId, taskId: noTask, enabled: canUpload })
+const { isDragging } = useFileDropZone({ target: root, enabled: canUpload, onFiles: upload })
+void filesStore.fetchStorageStatus()
+
+const files = computed(() => project.value.items)
+const actions = useFileActions({ files, taskId: noTask })
+
+const reload = () => filesStore.fetchForGoal({ goalId: props.goalId, search: search.value, type: type.value })
+const debouncedReload = useDebounceFn(reload, 300)
+
+watch(() => props.goalId, () => void reload(), { immediate: true })
+watch(search, () => void debouncedReload())
+watch(type, () => void reload())
+
+async function linkToTask(args: { file: TvFile, taskId: number }) {
+ const ok = await filesStore.link({ taskId: args.taskId, fileIds: [args.file.id] })
+ if (!ok) {
+ toast.add({ title: t('files.errors.linkFailed'), color: 'error' })
+ return
+ }
+ const current = project.value.items.find((f) => f.id === args.file.id)
+ if (current && !current.linkedTaskIds.includes(args.taskId)) current.linkedTaskIds = [...current.linkedTaskIds, args.taskId]
+}
+</script>
diff --git a/web/src/components/features/files/FilesUploadButton.vue b/web/src/components/features/files/FilesUploadButton.vue
new file mode 100644
index 0000000..0fdf32b
--- /dev/null
+++ b/web/src/components/features/files/FilesUploadButton.vue
@@ -0,0 +1,28 @@
+<template>
+ <UButton
+ icon="i-lucide-paperclip"
+ :label="label ?? t('files.attach')"
+ color="neutral"
+ variant="soft"
+ :size="size ?? 'sm'"
+ :ui="{ base: 'rounded-xl' }"
+ data-testid="files-upload-button"
+ @click="emit('click')"
+ />
+</template>
+
+<script setup lang="ts">
+import type { ButtonProps } from '@nuxt/ui'
+import { useI18n } from 'vue-i18n'
+
+defineProps<{
+ label?: string
+ size?: ButtonProps['size']
+}>()
+
+const emit = defineEmits<{
+ click: []
+}>()
+
+const { t } = useI18n()
+</script>
diff --git a/web/src/components/features/files/FilesViewer.vue b/web/src/components/features/files/FilesViewer.vue
new file mode 100644
index 0000000..917498d
--- /dev/null
+++ b/web/src/components/features/files/FilesViewer.vue
@@ -0,0 +1,183 @@
+<template>
+ <UModal
+ v-model:open="open"
+ fullscreen
+ :ui="{ content: 'bg-black/95 text-white', body: 'p-0 flex-1 min-h-0' }"
+ >
+ <template #content>
+ <div
+ class="flex flex-col h-full"
+ tabindex="0"
+ @keydown.left="prev"
+ @keydown.right="next"
+ @keydown.esc="open = false"
+ >
+ <div class="flex items-center gap-2 px-4 py-3">
+ <p class="flex-1 min-w-0 truncate text-sm">
+ {{ current?.name }}
+ <span
+ v-if="current"
+ class="text-white/60"
+ >· {{ formatBytes(current.sizeBytes) }}</span>
+ </p>
+ <span
+ v-if="files.length > 1"
+ class="text-xs text-white/60"
+ >{{ (index ?? 0) + 1 }} / {{ files.length }}</span>
+ <UButton
+ icon="i-lucide-download"
+ color="neutral"
+ variant="ghost"
+ :aria-label="t('files.menu.download')"
+ data-testid="file-viewer-download"
+ @click="current && download(current)"
+ />
+ <UButton
+ icon="i-lucide-external-link"
+ color="neutral"
+ variant="ghost"
+ :aria-label="t('files.menu.openInNewTab')"
+ @click="current && openInNewTab(current)"
+ />
+ <UButton
+ icon="i-lucide-x"
+ color="neutral"
+ variant="ghost"
+ :aria-label="t('files.close')"
+ data-testid="file-viewer-close"
+ @click="open = false"
+ />
+ </div>
+
+ <div class="relative flex-1 min-h-0 flex items-center justify-center px-12">
+ <UButton
+ v-if="files.length > 1"
+ icon="i-lucide-chevron-left"
+ color="neutral"
+ variant="ghost"
+ size="xl"
+ class="absolute left-2 top-1/2 -translate-y-1/2"
+ :aria-label="t('files.previous')"
+ @click="prev"
+ />
+
+ <div
+ v-if="loading"
+ class="flex items-center justify-center"
+ >
+ <UIcon
+ name="i-lucide-loader-circle"
+ class="size-8 animate-spin text-white/60"
+ />
+ </div>
+ <template v-else-if="current && src">
+ <img
+ v-if="kind === 'image'"
+ :src="src"
+ :alt="current.name"
+ class="max-w-full max-h-full object-contain"
+ />
+ <video
+ v-else-if="kind === 'video'"
+ :src="src"
+ controls
+ class="max-w-full max-h-full"
+ />
+ <audio
+ v-else-if="kind === 'audio'"
+ :src="src"
+ controls
+ />
+ <iframe
+ v-else-if="kind === 'pdf' || kind === 'text'"
+ :src="src"
+ :title="current.name"
+ class="w-full h-full bg-white rounded-lg"
+ />
+ <div
+ v-else
+ class="flex flex-col items-center gap-3 text-white/80"
+ >
+ <UIcon
+ :name="iconOf(current.mimeType)"
+ class="size-12"
+ />
+ <p class="text-sm">
+ {{ t('files.viewer.noPreview') }}
+ </p>
+ <UButton
+ :label="t('files.menu.download')"
+ icon="i-lucide-download"
+ @click="download(current)"
+ />
+ </div>
+ </template>
+
+ <UButton
+ v-if="files.length > 1"
+ icon="i-lucide-chevron-right"
+ color="neutral"
+ variant="ghost"
+ size="xl"
+ class="absolute right-2 top-1/2 -translate-y-1/2"
+ :aria-label="t('files.next')"
+ @click="next"
+ />
+ </div>
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { TvFile } from 'taskview-api'
+import { useFileKind } from '@/composables/useFileKind'
+import { useFileDownload } from '@/composables/useFileDownload'
+
+const props = defineProps<{
+ files: TvFile[]
+}>()
+
+const index = defineModel<number | null>('index', { default: null })
+
+const { t } = useI18n()
+const { kindOf, iconOf, formatBytes } = useFileKind()
+const { urlFor, download, openInNewTab } = useFileDownload()
+
+const src = ref<string | null>(null)
+const loading = ref(false)
+
+const open = computed({
+ get: () => index.value !== null,
+ set: (value: boolean) => {
+ if (!value) index.value = null
+ },
+})
+const current = computed(() => (index.value === null ? null : props.files[index.value] ?? null))
+const kind = computed(() => (current.value ? kindOf(current.value.mimeType) : 'other'))
+
+watch(current, async (file) => {
+ src.value = null
+ if (!file) return
+ if (kind.value === 'other') {
+ src.value = 'unavailable'
+ return
+ }
+ loading.value = true
+ src.value = await urlFor(file, true).finally(() => {
+ loading.value = false
+ })
+}, { immediate: true })
+
+function prev() {
+ if (index.value === null || props.files.length < 2) return
+ index.value = (index.value - 1 + props.files.length) % props.files.length
+}
+
+function next() {
+ if (index.value === null || props.files.length < 2) return
+ index.value = (index.value + 1) % props.files.length
+}
+</script>
diff --git a/web/src/components/features/files/parts/FileDeleteDialog.vue b/web/src/components/features/files/parts/FileDeleteDialog.vue
new file mode 100644
index 0000000..5395939
--- /dev/null
+++ b/web/src/components/features/files/parts/FileDeleteDialog.vue
@@ -0,0 +1,68 @@
+<template>
+ <UModal
+ v-model:open="open"
+ :fullscreen="isMobile"
+ :title="t('files.delete.title')"
+ :ui="{ content: 'max-w-md' }"
+ >
+ <template #body>
+ <p class="text-sm text-muted">
+ {{ t('files.delete.confirm', { name: file?.name ?? '' }) }}
+ </p>
+ <p
+ v-if="otherTasksCount > 0"
+ class="text-sm text-warning mt-2"
+ >
+ {{ t('files.delete.linkedElsewhere', { count: otherTasksCount }, otherTasksCount) }}
+ </p>
+ </template>
+ <template #footer>
+ <div class="flex justify-end gap-2 w-full">
+ <UButton
+ :label="t('files.cancel')"
+ color="neutral"
+ variant="ghost"
+ @click="open = false"
+ />
+ <UButton
+ :label="t('files.delete.submit')"
+ icon="i-lucide-trash-2"
+ color="error"
+ data-testid="file-delete-confirm"
+ @click="emit('confirm')"
+ />
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { TvFile } from 'taskview-api'
+import { useTaskView } from '@/composables/useTaskView'
+
+const props = defineProps<{
+ currentTaskId: number | null
+}>()
+
+const file = defineModel<TvFile | null>('file', { default: null })
+
+const emit = defineEmits<{
+ confirm: []
+}>()
+
+const { t } = useI18n()
+const { isMobile } = useTaskView()
+
+const open = computed({
+ get: () => file.value !== null,
+ set: (value: boolean) => {
+ if (!value) file.value = null
+ },
+})
+
+const otherTasksCount = computed(() =>
+ (file.value?.linkedTaskIds ?? []).filter((id) => id !== props.currentTaskId).length,
+)
+</script>
diff --git a/web/src/components/features/files/parts/FilePickerDialog.vue b/web/src/components/features/files/parts/FilePickerDialog.vue
new file mode 100644
index 0000000..38c1fa3
--- /dev/null
+++ b/web/src/components/features/files/parts/FilePickerDialog.vue
@@ -0,0 +1,127 @@
+<template>
+ <UModal
+ v-model:open="open"
+ :fullscreen="isMobile"
+ :title="t('files.picker.title')"
+ :ui="{ content: 'max-w-lg' }"
+ >
+ <template #body>
+ <div class="flex flex-col gap-3">
+ <UInput
+ v-model="query"
+ :placeholder="t('files.searchPlaceholder')"
+ icon="i-lucide-search"
+ variant="soft"
+ autofocus
+ :loading="loading"
+ />
+ <div class="max-h-80 overflow-y-auto flex flex-col gap-1">
+ <p
+ v-if="!loading && options.length === 0"
+ class="text-sm text-muted py-6 text-center"
+ >
+ {{ t('files.picker.empty') }}
+ </p>
+ <label
+ v-for="file in options"
+ :key="file.id"
+ class="flex items-center gap-3 rounded-xl px-2 py-1.5 hover:bg-elevated cursor-pointer"
+ >
+ <UCheckbox
+ :model-value="selected.has(file.id)"
+ @update:model-value="toggle(file.id)"
+ />
+ <UIcon
+ :name="iconOf(file.mimeType)"
+ class="size-4 text-muted shrink-0"
+ />
+ <span class="text-sm truncate flex-1">{{ file.name }}</span>
+ <span class="text-xs text-muted shrink-0">{{ formatBytes(file.sizeBytes) }}</span>
+ </label>
+ </div>
+ </div>
+ </template>
+ <template #footer>
+ <div class="flex justify-end gap-2 w-full">
+ <UButton
+ :label="t('files.cancel')"
+ color="neutral"
+ variant="ghost"
+ @click="open = false"
+ />
+ <UButton
+ :label="t('files.picker.submit', { count: selected.size }, selected.size)"
+ :disabled="selected.size === 0"
+ data-testid="file-picker-submit"
+ @click="submit"
+ />
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useDebounceFn } from '@vueuse/core'
+import type { TvFile } from 'taskview-api'
+import { $tvApi } from '@/plugins/axios'
+import { logError } from '@/helpers/Helper'
+import { useTaskView } from '@/composables/useTaskView'
+import { useFileKind } from '@/composables/useFileKind'
+
+const props = defineProps<{
+ goalId: number
+ excludedIds: string[]
+}>()
+
+const open = defineModel<boolean>('open', { default: false })
+
+const emit = defineEmits<{
+ select: [fileIds: string[]]
+}>()
+
+const { t } = useI18n()
+const { isMobile } = useTaskView()
+const { iconOf, formatBytes } = useFileKind()
+
+const query = ref('')
+const loading = ref(false)
+const items = ref<TvFile[]>([])
+const selected = ref(new Set<string>())
+
+const options = computed(() => items.value.filter((f) => !props.excludedIds.includes(f.id)))
+
+async function load() {
+ loading.value = true
+ const page = await $tvApi.files
+ .listForGoal({ goalId: props.goalId, search: query.value || null, limit: 100 })
+ .catch(logError)
+ .finally(() => {
+ loading.value = false
+ })
+ items.value = page?.items ?? []
+}
+
+const debouncedLoad = useDebounceFn(load, 300)
+
+watch(query, () => debouncedLoad())
+watch(open, (value) => {
+ if (!value) return
+ query.value = ''
+ selected.value = new Set()
+ void load()
+})
+
+function toggle(id: string) {
+ const next = new Set(selected.value)
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
+ selected.value = next
+}
+
+function submit() {
+ emit('select', [...selected.value])
+ open.value = false
+}
+</script>
diff --git a/web/src/components/features/files/parts/FilePreview.vue b/web/src/components/features/files/parts/FilePreview.vue
new file mode 100644
index 0000000..f7fcf28
--- /dev/null
+++ b/web/src/components/features/files/parts/FilePreview.vue
@@ -0,0 +1,54 @@
+<template>
+ <div class="relative w-full h-full flex items-center justify-center bg-elevated/60 overflow-hidden">
+ <img
+ v-if="kind === 'image' && src"
+ :src="src"
+ :alt="file.name"
+ class="w-full h-full object-cover"
+ loading="lazy"
+ @error="failed = true"
+ />
+ <div
+ v-else
+ class="flex flex-col items-center gap-1 text-muted"
+ >
+ <UIcon
+ :name="iconOf(file.mimeType)"
+ class="size-7"
+ />
+ <span
+ v-if="extension"
+ class="text-[10px] font-semibold tracking-wide"
+ >{{ extension }}</span>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import type { TvFile } from 'taskview-api'
+import { useFileKind } from '@/composables/useFileKind'
+import { useFileDownload } from '@/composables/useFileDownload'
+
+const props = defineProps<{
+ file: TvFile
+}>()
+
+const { kindOf, iconOf, extensionOf } = useFileKind()
+const { urlFor } = useFileDownload()
+
+const failed = ref(false)
+const src = ref<string | null>(null)
+const kind = computed(() => (failed.value ? 'other' : kindOf(props.file.mimeType)))
+const extension = computed(() => extensionOf(props.file.name))
+
+watch(
+ () => props.file.id,
+ async () => {
+ failed.value = false
+ src.value = null
+ if (kindOf(props.file.mimeType) === 'image') src.value = await urlFor(props.file, true)
+ },
+ { immediate: true },
+)
+</script>
diff --git a/web/src/components/features/files/parts/FileProjectRow.vue b/web/src/components/features/files/parts/FileProjectRow.vue
new file mode 100644
index 0000000..ed18932
--- /dev/null
+++ b/web/src/components/features/files/parts/FileProjectRow.vue
@@ -0,0 +1,105 @@
+<template>
+ <div
+ class="flex items-center gap-3 rounded-2xl p-3 bg-accented/20 hover:bg-elevated transition-colors cursor-pointer"
+ :data-testid="`file-row-${file.id}`"
+ @click="emit('open')"
+ >
+ <div class="size-12 shrink-0 rounded-xl overflow-hidden">
+ <FilePreview :file="file" />
+ </div>
+ <div class="flex-1 min-w-0 flex flex-col gap-1">
+ <p class="text-sm truncate">
+ {{ file.name }}
+ </p>
+ <div class="flex flex-wrap gap-1">
+ <ULink
+ v-for="taskId in file.linkedTaskIds"
+ :key="taskId"
+ :to="{ name: 'user', params: { projectId: file.goalId, listId: ALL_TASKS_LIST_ID, taskId } }"
+ raw
+ :data-testid="`file-task-link-${taskId}`"
+ @click.stop
+ >
+ <UBadge
+ :label="`#${taskId}`"
+ icon="i-lucide-list-checks"
+ color="neutral"
+ variant="subtle"
+ size="sm"
+ class="hover:bg-accented transition-colors"
+ />
+ </ULink>
+ <UBadge
+ v-if="file.linkedTaskIds.length === 0"
+ :label="t('files.project.unlinked')"
+ color="neutral"
+ variant="soft"
+ size="sm"
+ />
+ </div>
+ <p class="text-xs text-muted truncate">
+ {{ formatBytes(file.sizeBytes) }} · {{ file.uploaderEmail }} · {{ formattedDate }}
+ </p>
+ </div>
+ <div class="flex items-center gap-2 shrink-0">
+ <UButton
+ v-if="canManage"
+ icon="i-lucide-link"
+ color="neutral"
+ variant="soft"
+ size="lg"
+ :ui="{ base: 'rounded-xl' }"
+ :aria-label="t('files.linkToTask.title')"
+ data-testid="file-link-task"
+ @click.stop="emit('linkToTask')"
+ />
+ <UButton
+ icon="i-lucide-download"
+ color="neutral"
+ variant="soft"
+ size="lg"
+ :ui="{ base: 'rounded-xl' }"
+ :aria-label="t('files.menu.download')"
+ @click.stop="emit('download')"
+ />
+ <FileTileMenu
+ :file="file"
+ :can-manage="canManage"
+ :in-task="false"
+ variant="soft"
+ size="lg"
+ @download="emit('download')"
+ @open-in-new-tab="emit('openInNewTab')"
+ @rename="emit('rename')"
+ @delete="emit('delete')"
+ />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { useI18n } from 'vue-i18n'
+import { useDateFormat } from '@vueuse/core'
+import { ALL_TASKS_LIST_ID, type TvFile } from 'taskview-api'
+import { useFileKind } from '@/composables/useFileKind'
+import FilePreview from './FilePreview.vue'
+import FileTileMenu from './FileTileMenu.vue'
+
+const props = defineProps<{
+ file: TvFile
+ canManage: boolean
+}>()
+
+const emit = defineEmits<{
+ open: []
+ linkToTask: []
+ download: []
+ openInNewTab: []
+ rename: []
+ delete: []
+}>()
+
+const { t } = useI18n()
+const { formatBytes } = useFileKind()
+const formattedDate = useDateFormat(() => props.file.createdAt, 'DD.MM.YYYY')
+</script>
diff --git a/web/src/components/features/files/parts/FileRenameDialog.vue b/web/src/components/features/files/parts/FileRenameDialog.vue
new file mode 100644
index 0000000..0501b39
--- /dev/null
+++ b/web/src/components/features/files/parts/FileRenameDialog.vue
@@ -0,0 +1,69 @@
+<template>
+ <UModal
+ v-model:open="open"
+ :fullscreen="isMobile"
+ :title="t('files.rename.title')"
+ :ui="{ content: 'max-w-md' }"
+ >
+ <template #body>
+ <UFormField :label="t('files.rename.label')">
+ <UInput
+ v-model="name"
+ class="w-full"
+ autofocus
+ data-testid="file-rename-input"
+ @keydown.enter.prevent="submit"
+ />
+ </UFormField>
+ </template>
+ <template #footer>
+ <div class="flex justify-end gap-2 w-full">
+ <UButton
+ :label="t('files.cancel')"
+ color="neutral"
+ variant="ghost"
+ @click="open = false"
+ />
+ <UButton
+ :label="t('files.rename.submit')"
+ :disabled="!name.trim()"
+ data-testid="file-rename-submit"
+ @click="submit"
+ />
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { TvFile } from 'taskview-api'
+import { useTaskView } from '@/composables/useTaskView'
+
+const file = defineModel<TvFile | null>('file', { default: null })
+
+const emit = defineEmits<{
+ submit: [name: string]
+}>()
+
+const { t } = useI18n()
+const { isMobile } = useTaskView()
+
+const name = ref('')
+const open = computed({
+ get: () => file.value !== null,
+ set: (value: boolean) => {
+ if (!value) file.value = null
+ },
+})
+
+watch(file, (current) => {
+ name.value = current?.name ?? ''
+})
+
+function submit() {
+ if (!name.value.trim()) return
+ emit('submit', name.value.trim())
+}
+</script>
diff --git a/web/src/components/features/files/parts/FileTaskPickerDialog.vue b/web/src/components/features/files/parts/FileTaskPickerDialog.vue
new file mode 100644
index 0000000..f06e0b4
--- /dev/null
+++ b/web/src/components/features/files/parts/FileTaskPickerDialog.vue
@@ -0,0 +1,56 @@
+<template>
+ <UModal
+ v-model:open="open"
+ :fullscreen="isMobile"
+ :title="t('files.linkToTask.title')"
+ :ui="{ content: 'max-w-md' }"
+ >
+ <template #body>
+ <div class="flex flex-col gap-3">
+ <p class="text-sm text-muted truncate">
+ {{ file?.name }}
+ </p>
+ <TaskDependencyPicker
+ :goal-id="goalId"
+ :excluded-ids="file?.linkedTaskIds ?? []"
+ @select="pick"
+ />
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { TvFile } from 'taskview-api'
+import { useTaskView } from '@/composables/useTaskView'
+import TaskDependencyPicker from '@/components/features/tasks/parts/TaskDependencyPicker.vue'
+import type { DependencyTask } from '@/components/features/tasks/parts/TaskDependencies.types'
+
+defineProps<{
+ goalId: number
+}>()
+
+const file = defineModel<TvFile | null>('file', { default: null })
+
+const emit = defineEmits<{
+ select: [args: { file: TvFile, taskId: number }]
+}>()
+
+const { t } = useI18n()
+const { isMobile } = useTaskView()
+
+const open = computed({
+ get: () => file.value !== null,
+ set: (value: boolean) => {
+ if (!value) file.value = null
+ },
+})
+
+function pick(task: DependencyTask) {
+ if (!file.value) return
+ emit('select', { file: file.value, taskId: task.id })
+ file.value = null
+}
+</script>
diff --git a/web/src/components/features/files/parts/FileTile.vue b/web/src/components/features/files/parts/FileTile.vue
new file mode 100644
index 0000000..d4a3f70
--- /dev/null
+++ b/web/src/components/features/files/parts/FileTile.vue
@@ -0,0 +1,80 @@
+<template>
+ <div
+ class="group relative flex flex-col rounded-xl bg-elevated/40 hover:bg-elevated transition-colors cursor-pointer overflow-hidden"
+ :data-testid="`file-tile-${file.id}`"
+ @click="emit('open')"
+ >
+ <div class="aspect-[4/3] w-full min-h-0 overflow-hidden">
+ <FilePreview :file="file" />
+ </div>
+ <div class="flex flex-col gap-0.5 p-2 min-w-0">
+ <UTooltip :text="file.name">
+ <p class="text-sm truncate">
+ {{ file.name }}
+ </p>
+ </UTooltip>
+ <p class="text-xs text-muted truncate">
+ {{ formatBytes(file.sizeBytes) }} · {{ uploaderLabel }} · {{ formattedDate }}
+ </p>
+ </div>
+ <div
+ class="absolute top-1.5 right-1.5 flex items-center gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity"
+ >
+ <UButton
+ icon="i-lucide-download"
+ color="neutral"
+ variant="solid"
+ size="xs"
+ :aria-label="t('files.menu.download')"
+ data-testid="file-download"
+ @click.stop="emit('download')"
+ />
+ <FileTileMenu
+ :file="file"
+ :can-manage="canManage"
+ :in-task="inTask"
+ @download="emit('download')"
+ @open-in-new-tab="emit('openInNewTab')"
+ @rename="emit('rename')"
+ @unlink="emit('unlink')"
+ @delete="emit('delete')"
+ />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useDateFormat } from '@vueuse/core'
+import type { TvFile } from 'taskview-api'
+import { useFileKind } from '@/composables/useFileKind'
+import { useCollaborationStore } from '@/stores/collaboration.store'
+import FilePreview from './FilePreview.vue'
+import FileTileMenu from './FileTileMenu.vue'
+
+const props = defineProps<{
+ file: TvFile
+ canManage: boolean
+ inTask: boolean
+}>()
+
+const emit = defineEmits<{
+ open: []
+ download: []
+ openInNewTab: []
+ rename: []
+ unlink: []
+ delete: []
+}>()
+
+const { t } = useI18n()
+const { formatBytes } = useFileKind()
+const collaborationStore = useCollaborationStore()
+
+const formattedDate = useDateFormat(() => props.file.createdAt, 'DD.MM.YYYY')
+const uploaderLabel = computed(() => {
+ const known = props.file.uploaderId !== null ? collaborationStore.userMap.get(props.file.uploaderId) : null
+ return known?.email ?? props.file.uploaderEmail
+})
+</script>
diff --git a/web/src/components/features/files/parts/FileTileMenu.vue b/web/src/components/features/files/parts/FileTileMenu.vue
new file mode 100644
index 0000000..ab03451
--- /dev/null
+++ b/web/src/components/features/files/parts/FileTileMenu.vue
@@ -0,0 +1,65 @@
+<template>
+ <UDropdownMenu
+ :items="items"
+ :content="{ align: 'end' }"
+ >
+ <UButton
+ icon="i-lucide-ellipsis-vertical"
+ color="neutral"
+ :variant="variant ?? 'ghost'"
+ :size="size ?? 'xs'"
+ :ui="variant === 'soft' ? { base: 'rounded-xl' } : undefined"
+ :aria-label="t('files.menu.more')"
+ data-testid="file-menu"
+ @click.stop
+ />
+ </UDropdownMenu>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { ButtonProps, DropdownMenuItem } from '@nuxt/ui'
+import type { TvFile } from 'taskview-api'
+import { useFileKind } from '@/composables/useFileKind'
+
+const props = defineProps<{
+ file: TvFile
+ canManage: boolean
+ inTask: boolean
+ variant?: ButtonProps['variant']
+ size?: ButtonProps['size']
+}>()
+
+const emit = defineEmits<{
+ download: []
+ openInNewTab: []
+ rename: []
+ unlink: []
+ delete: []
+}>()
+
+const { t } = useI18n()
+const { isPreviewable } = useFileKind()
+
+const items = computed<DropdownMenuItem[][]>(() => {
+ const main: DropdownMenuItem[] = [
+ { label: t('files.menu.download'), icon: 'i-lucide-download', onSelect: () => emit('download') },
+ ]
+ if (isPreviewable(props.file.mimeType)) {
+ main.push({ label: t('files.menu.openInNewTab'), icon: 'i-lucide-external-link', onSelect: () => emit('openInNewTab') })
+ }
+ if (!props.canManage) return [main]
+
+ const manage: DropdownMenuItem[] = [
+ { label: t('files.menu.rename'), icon: 'i-lucide-pencil', onSelect: () => emit('rename') },
+ ]
+ if (props.inTask) {
+ manage.push({ label: t('files.menu.unlink'), icon: 'i-lucide-unlink', onSelect: () => emit('unlink') })
+ }
+ const danger: DropdownMenuItem[] = [
+ { label: t('files.menu.delete'), icon: 'i-lucide-trash-2', color: 'error', onSelect: () => emit('delete') },
+ ]
+ return [main, manage, danger]
+})
+</script>
diff --git a/web/src/components/features/files/parts/FileUploadingTile.vue b/web/src/components/features/files/parts/FileUploadingTile.vue
new file mode 100644
index 0000000..07e3849
--- /dev/null
+++ b/web/src/components/features/files/parts/FileUploadingTile.vue
@@ -0,0 +1,83 @@
+<template>
+ <div
+ class="relative flex flex-col rounded-xl overflow-hidden border border-dashed"
+ :class="upload.status === 'error' ? 'border-error/60 bg-error/5' : 'border-accented bg-elevated/40'"
+ data-testid="file-uploading-tile"
+ >
+ <div class="aspect-[4/3] w-full flex flex-col items-center justify-center gap-2 px-3">
+ <template v-if="upload.status === 'uploading'">
+ <UIcon
+ name="i-lucide-upload"
+ class="size-6 text-muted"
+ />
+ <UProgress
+ :model-value="upload.progress"
+ size="sm"
+ class="w-full"
+ />
+ </template>
+ <template v-else>
+ <UIcon
+ name="i-lucide-alert-circle"
+ class="size-6 text-error"
+ />
+ <p class="text-xs text-error text-center">
+ {{ t(upload.errorKey ?? 'files.errors.uploadFailed') }}
+ </p>
+ <div class="flex gap-1">
+ <UButton
+ :label="t('files.retry')"
+ size="xs"
+ color="neutral"
+ variant="soft"
+ @click="emit('retry')"
+ />
+ <UButton
+ icon="i-lucide-x"
+ size="xs"
+ color="neutral"
+ variant="ghost"
+ :aria-label="t('files.cancel')"
+ @click="emit('cancel')"
+ />
+ </div>
+ </template>
+ </div>
+ <div class="flex flex-col gap-0.5 p-2 min-w-0">
+ <p class="text-sm truncate">
+ {{ upload.name }}
+ </p>
+ <p class="text-xs text-muted">
+ {{ formatBytes(upload.sizeBytes) }}
+ </p>
+ </div>
+ <UButton
+ v-if="upload.status === 'uploading'"
+ icon="i-lucide-x"
+ color="neutral"
+ variant="ghost"
+ size="xs"
+ class="absolute top-1.5 right-1.5"
+ :aria-label="t('files.cancel')"
+ @click="emit('cancel')"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { useI18n } from 'vue-i18n'
+import type { FileUploadItem } from '@/types/files.types'
+import { useFileKind } from '@/composables/useFileKind'
+
+defineProps<{
+ upload: FileUploadItem
+}>()
+
+const emit = defineEmits<{
+ retry: []
+ cancel: []
+}>()
+
+const { t } = useI18n()
+const { formatBytes } = useFileKind()
+</script>
diff --git a/web/src/components/features/tasks/TaskDetailPanel.vue b/web/src/components/features/tasks/TaskDetailPanel.vue
index 4a2ae04..03fa2ca 100644
--- a/web/src/components/features/tasks/TaskDetailPanel.vue
+++ b/web/src/components/features/tasks/TaskDetailPanel.vue
@@ -1,5 +1,6 @@
<template>
<div
+ ref="panelRef"
class="h-full relative flex flex-col gap-4 @container"
data-testid="task-detail-panel"
>
@@ -51,6 +52,13 @@
:subtasks="task.subtasks"
:class="[colClass(fieldId), 'pl-10']"
/>
+ <TaskFiles
+ v-else-if="fieldId === 'files'"
+ :task-id="task.id"
+ :goal-id="task.goalId"
+ :drop-target="panelRef"
+ :class="colClass(fieldId)"
+ />
<NoteEditor
v-else-if="fieldId === 'note'"
:key="task.id"
@@ -175,6 +183,7 @@ import TvDeadlineSelect from '@/components/features/base/TvDeadlineSelect.vue'
import TaskRecurrence from '@/components/features/tasks/parts/TaskRecurrence.vue'
import TaskSourceLink from '@/components/features/tasks/parts/TaskSourceLink.vue'
import TaskSubtasks from '@/components/features/tasks/parts/TaskSubtasks.vue'
+import TaskFiles from '@/components/features/tasks/parts/TaskFiles.vue'
import TaskDependencies from '@/components/features/tasks/parts/TaskDependencies.vue'
import TaskIdCopy from '@/components/features/tasks/parts/TaskIdCopy.vue'
import TvSprintSelect from '@/components/features/base/TvSprintSelect.vue'
@@ -219,6 +228,7 @@ const fieldWidthById = computed(() => {
function colClass(id: string): string {
return fieldWidthById.value.get(id) === 'wide' ? '@lg:col-span-2' : 'w-full'
}
+const panelRef = ref<HTMLElement | null>(null)
const task = computed(() => tasksStore.selectedTask ?? null)
const projectId = computed(() => task.value?.goalId ?? 0)
const titleValue = ref(task.value?.description ?? '')
diff --git a/web/src/components/features/tasks/parts/TaskFiles.vue b/web/src/components/features/tasks/parts/TaskFiles.vue
new file mode 100644
index 0000000..1ad49c0
--- /dev/null
+++ b/web/src/components/features/tasks/parts/TaskFiles.vue
@@ -0,0 +1,146 @@
+<template>
+ <div
+ v-if="canViewFiles"
+ ref="root"
+ class="relative w-full h-fit rounded-2xl bg-accented/20 p-3.5 @container"
+ data-testid="task-files"
+ >
+ <div class="flex items-center gap-2 mb-2">
+ <label class="text-sm text-muted flex-1">
+ {{ t('files.title') }}
+ <span
+ v-if="files.length > 0"
+ class="text-dimmed"
+ >· {{ files.length }}</span>
+ </label>
+ <template v-if="canManageFiles">
+ <UButton
+ icon="i-lucide-folder-search"
+ :label="t('files.chooseFromProject')"
+ color="neutral"
+ variant="ghost"
+ size="xs"
+ data-testid="files-choose-from-project"
+ @click="pickerOpen = true"
+ />
+ <FilesUploadButton
+ v-if="storageEnabled"
+ size="xs"
+ @click="openDialog"
+ />
+ </template>
+ </div>
+
+ <div
+ v-if="isDragging && canUpload"
+ class="absolute inset-0 z-10 rounded-2xl border-2 border-dashed border-primary bg-primary/5 flex items-center justify-center pointer-events-none"
+ >
+ <p class="text-primary font-medium">
+ {{ t('files.dropHint') }}
+ </p>
+ </div>
+
+ <p
+ v-if="files.length === 0 && uploads.length === 0"
+ class="text-sm text-dimmed"
+ >
+ {{ emptyText }}
+ </p>
+
+ <FilesGrid
+ v-else
+ :files="files"
+ :uploads="uploads"
+ :can-manage="canManageFiles"
+ :in-task="true"
+ @open="actions.open"
+ @download="actions.download"
+ @open-in-new-tab="actions.openInNewTab"
+ @rename="(file) => (actions.renameTarget.value = file)"
+ @unlink="actions.unlink"
+ @delete="(file) => (actions.deleteTarget.value = file)"
+ @retry="retry"
+ @cancel="cancel"
+ />
+
+ <FilesViewer
+ v-model:index="actions.viewerIndex.value"
+ :files="files"
+ />
+ <FileRenameDialog
+ v-model:file="actions.renameTarget.value"
+ @submit="actions.rename"
+ />
+ <FileDeleteDialog
+ v-model:file="actions.deleteTarget.value"
+ :current-task-id="taskId"
+ @confirm="actions.deleteForever"
+ />
+ <FilePickerDialog
+ v-model:open="pickerOpen"
+ :goal-id="goalId"
+ :excluded-ids="files.map((f) => f.id)"
+ @select="linkExisting"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, toRef, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useFilesStore } from '@/stores/files.store'
+import { useGoalPermissions } from '@/composables/useGoalPermissions'
+import { useFileUpload } from '@/composables/useFileUpload'
+import { useFileDropZone } from '@/composables/useFileDropZone'
+import { useFileActions } from '@/composables/useFileActions'
+import FilesGrid from '@/components/features/files/FilesGrid.vue'
+import FilesViewer from '@/components/features/files/FilesViewer.vue'
+import FilesUploadButton from '@/components/features/files/FilesUploadButton.vue'
+import FileRenameDialog from '@/components/features/files/parts/FileRenameDialog.vue'
+import FileDeleteDialog from '@/components/features/files/parts/FileDeleteDialog.vue'
+import FilePickerDialog from '@/components/features/files/parts/FilePickerDialog.vue'
+
+const props = defineProps<{
+ taskId: number
+ goalId: number
+ dropTarget?: HTMLElement | null
+}>()
+
+const { t } = useI18n()
+const toast = useToast()
+const filesStore = useFilesStore()
+const { canViewFiles, canManageFiles } = useGoalPermissions()
+
+const root = ref<HTMLElement | null>(null)
+const pickerOpen = ref(false)
+
+const taskId = toRef(props, 'taskId')
+const goalId = toRef(props, 'goalId')
+const files = computed(() => filesStore.filesForTask(props.taskId))
+const dropTarget = computed(() => props.dropTarget ?? root.value)
+
+const storageEnabled = computed(() => filesStore.storageEnabled)
+const canUpload = computed(() => canManageFiles.value && storageEnabled.value)
+const emptyText = computed(() => {
+ if (!storageEnabled.value) return t('files.storageDisabled')
+ return canManageFiles.value ? t('files.emptyHint') : t('files.empty')
+})
+
+const { uploads, upload, openDialog, retry, cancel } = useFileUpload({ goalId, taskId, enabled: canUpload })
+const { isDragging } = useFileDropZone({ target: dropTarget, enabled: canUpload, onFiles: upload })
+const actions = useFileActions({ files, taskId })
+void filesStore.fetchStorageStatus()
+
+watch(
+ () => [props.taskId, canViewFiles.value] as const,
+ ([id, allowed]) => {
+ if (allowed) void filesStore.fetchForTask(id)
+ },
+ { immediate: true },
+)
+
+async function linkExisting(fileIds: string[]) {
+ const ok = await filesStore.link({ taskId: props.taskId, fileIds })
+ if (!ok) toast.add({ title: t('files.errors.linkFailed'), color: 'error' })
+}
+</script>
diff --git a/web/src/components/features/tasks/parts/TaskItem.vue b/web/src/components/features/tasks/parts/TaskItem.vue
index 5627910..88bb0d3 100644
--- a/web/src/components/features/tasks/parts/TaskItem.vue
+++ b/web/src/components/features/tasks/parts/TaskItem.vue
@@ -57,6 +57,19 @@
data-testid="task-recurrence-badge"
/>
+ <!-- Attached files -->
+ <UBadge
+ v-if="task.filesCount"
+ :label="String(task.filesCount)"
+ icon="i-lucide-paperclip"
+ color="neutral"
+ class="bg-elevated text-muted"
+ :ui="{ base: 'rounded-md', leadingIcon: 'size-3' }"
+ variant="subtle"
+ size="md"
+ data-testid="task-files-badge"
+ />
+
<!-- Project -->
<UBadge
v-if="projectName"
@@ -265,6 +278,7 @@ const hasAdditionalInfo = computed(() => {
props.task.endDate ||
props.task.amount ||
props.task.recurrenceRuleId ||
+ props.task.filesCount ||
assigneeEmails.value.length > 0 ||
taskTags.value.length > 0
})
diff --git a/web/src/components/sidebars/dashboard-second/SidebarTools.vue b/web/src/components/sidebars/dashboard-second/SidebarTools.vue
index d9c7132..f229d4a 100644
--- a/web/src/components/sidebars/dashboard-second/SidebarTools.vue
+++ b/web/src/components/sidebars/dashboard-second/SidebarTools.vue
@@ -67,6 +67,7 @@ const {
canViewKanban,
canViewGraph,
canViewSprints,
+ canViewFiles,
canManageUsers,
canViewIntegrations,
canViewTimeTracking,
@@ -95,6 +96,9 @@ const tools = computed<Tool[]>(() => {
if (canViewSprints.value) {
list.push({ key: 'sprints', label: t('contextMenu.sprints'), icon: 'i-lucide-rocket', to: { name: 'sprints', params: { projectId: id } }, active: () => route.name === 'sprints' })
}
+ if (canViewFiles.value) {
+ list.push({ key: 'files', label: t('contextMenu.files'), icon: 'i-lucide-paperclip', to: { name: 'files', params: { projectId: id } }, active: () => route.name === 'files' })
+ }
if (canManageUsers.value) {
list.push({ key: 'collaboration', label: t('contextMenu.collaboration'), icon: 'i-lucide-users', to: { name: 'collaboration', params: { projectId: id } }, active: () => route.name === 'collaboration' })
}
diff --git a/web/src/composables/useCentrifugo/handlers/files.ts b/web/src/composables/useCentrifugo/handlers/files.ts
new file mode 100644
index 0000000..5860d27
--- /dev/null
+++ b/web/src/composables/useCentrifugo/handlers/files.ts
@@ -0,0 +1,6 @@
+import { useFilesStore } from '@/stores/files.store'
+import type { RealtimeEventMap } from '../types'
+
+export function handleFilesChanged(data: RealtimeEventMap['files.changed']) {
+ useFilesStore().handleRemoteChange({ goalId: data.goalId, taskIds: data.taskIds })
+}
diff --git a/web/src/composables/useCentrifugo/handlers/index.ts b/web/src/composables/useCentrifugo/handlers/index.ts
index e0d93e1..4efb943 100644
--- a/web/src/composables/useCentrifugo/handlers/index.ts
+++ b/web/src/composables/useCentrifugo/handlers/index.ts
@@ -2,6 +2,7 @@ import type { RealtimeEventMap, RealtimeHandler } from '../types'
import { handleNotification } from './notification'
import { handleGoalsChanged } from './goals-changed'
import { handleRecurrenceInstanceCreated } from './recurrence'
+import { handleFilesChanged } from './files'
import {
handleTimeEntryCreated,
handleTimeEntryDeleted,
@@ -19,4 +20,5 @@ export const eventHandlers: { [K in keyof RealtimeEventMap]: RealtimeHandler<K>
'time-entry.updated': handleTimeEntryUpdated,
'time-entry.deleted': handleTimeEntryDeleted,
'recurrence.instanceCreated': handleRecurrenceInstanceCreated,
+ 'files.changed': handleFilesChanged,
}
diff --git a/web/src/composables/useCentrifugo/types.ts b/web/src/composables/useCentrifugo/types.ts
index 4c23ac3..12362ef 100644
--- a/web/src/composables/useCentrifugo/types.ts
+++ b/web/src/composables/useCentrifugo/types.ts
@@ -42,6 +42,11 @@ export type RealtimeEventMap = {
ruleId: number
taskId: number
}
+ 'files.changed': {
+ event: 'files.changed'
+ goalId: number
+ taskIds: number[]
+ }
}
export type RealtimeEvent = RealtimeEventMap[keyof RealtimeEventMap]
diff --git a/web/src/composables/useFileActions.ts b/web/src/composables/useFileActions.ts
new file mode 100644
index 0000000..a7806ec
--- /dev/null
+++ b/web/src/composables/useFileActions.ts
@@ -0,0 +1,58 @@
+import { ref, type Ref } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { TvFile } from 'taskview-api'
+import { useFilesStore } from '@/stores/files.store'
+import { useFileDownload } from '@/composables/useFileDownload'
+
+export type UseFileActionsArgs = {
+ files: Ref<TvFile[]>
+ taskId: Ref<number | null>
+}
+
+export function useFileActions(args: UseFileActionsArgs) {
+ const { t } = useI18n()
+ const toast = useToast()
+ const filesStore = useFilesStore()
+ const { download, openInNewTab } = useFileDownload()
+
+ const viewerIndex = ref<number | null>(null)
+ const renameTarget = ref<TvFile | null>(null)
+ const deleteTarget = ref<TvFile | null>(null)
+
+ const open = (file: TvFile) => {
+ const index = args.files.value.findIndex((f) => f.id === file.id)
+ viewerIndex.value = index === -1 ? null : index
+ }
+
+ const rename = async (name: string) => {
+ if (!renameTarget.value) return
+ const result = await filesStore.rename({ fileId: renameTarget.value.id, name })
+ renameTarget.value = null
+ if (!result) toast.add({ title: t('files.errors.renameFailed'), color: 'error' })
+ }
+
+ const unlink = async (file: TvFile) => {
+ if (args.taskId.value === null) return
+ const ok = await filesStore.unlink({ taskId: args.taskId.value, fileId: file.id })
+ if (!ok) toast.add({ title: t('files.errors.unlinkFailed'), color: 'error' })
+ }
+
+ const deleteForever = async () => {
+ if (!deleteTarget.value) return
+ const ok = await filesStore.deleteForever(deleteTarget.value.id)
+ deleteTarget.value = null
+ if (!ok) toast.add({ title: t('files.errors.deleteFailed'), color: 'error' })
+ }
+
+ return {
+ viewerIndex,
+ renameTarget,
+ deleteTarget,
+ open,
+ download,
+ openInNewTab,
+ rename,
+ unlink,
+ deleteForever,
+ }
+}
diff --git a/web/src/composables/useFileDownload.ts b/web/src/composables/useFileDownload.ts
new file mode 100644
index 0000000..b79ce2e
--- /dev/null
+++ b/web/src/composables/useFileDownload.ts
@@ -0,0 +1,36 @@
+import type { TvFile } from 'taskview-api'
+import $api from '@/helpers/axios'
+import { useFilesStore } from '@/stores/files.store'
+
+export function useFileDownload() {
+ const filesStore = useFilesStore()
+
+ const toAbsolute = (relative: string): string => {
+ const base = $api.defaults.baseURL || window.location.origin
+ return new URL(relative, base.endsWith('/') ? base : `${base}/`).toString()
+ }
+
+ const urlFor = async (file: TvFile, inline: boolean): Promise<string | null> => {
+ const url = await filesStore.downloadUrl({ fileId: file.id, inline })
+ return url ? toAbsolute(url) : null
+ }
+
+ const download = async (file: TvFile): Promise<void> => {
+ const url = await urlFor(file, false)
+ if (!url) return
+ const anchor = document.createElement('a')
+ anchor.href = url
+ anchor.download = file.name
+ anchor.rel = 'noopener'
+ document.body.appendChild(anchor)
+ anchor.click()
+ anchor.remove()
+ }
+
+ const openInNewTab = async (file: TvFile): Promise<void> => {
+ const url = await urlFor(file, true)
+ if (url) window.open(url, '_blank', 'noopener')
+ }
+
+ return { urlFor, download, openInNewTab }
+}
diff --git a/web/src/composables/useFileDropZone.ts b/web/src/composables/useFileDropZone.ts
new file mode 100644
index 0000000..af5af9d
--- /dev/null
+++ b/web/src/composables/useFileDropZone.ts
@@ -0,0 +1,18 @@
+import { type Ref } from 'vue'
+import { useDropZone } from '@vueuse/core'
+
+export type UseFileDropZoneArgs = {
+ target: Ref<HTMLElement | null>
+ enabled: Ref<boolean>
+ onFiles: (files: File[]) => void
+}
+
+export function useFileDropZone(args: UseFileDropZoneArgs) {
+ const { isOverDropZone } = useDropZone(args.target, {
+ onDrop: (files) => {
+ if (args.enabled.value && files && files.length > 0) args.onFiles(files)
+ },
+ preventDefaultForUnhandled: false,
+ })
+ return { isDragging: isOverDropZone }
+}
diff --git a/web/src/composables/useFileKind.ts b/web/src/composables/useFileKind.ts
new file mode 100644
index 0000000..bc096bb
--- /dev/null
+++ b/web/src/composables/useFileKind.ts
@@ -0,0 +1,47 @@
+import type { FileKind } from '@/types/files.types'
+
+const ICONS: Record<FileKind, string> = {
+ image: 'i-lucide-image',
+ pdf: 'i-lucide-file-text',
+ video: 'i-lucide-film',
+ audio: 'i-lucide-music',
+ text: 'i-lucide-file-text',
+ other: 'i-lucide-file',
+}
+
+const TEXT_TYPES = new Set(['application/json', 'application/xml', 'application/javascript'])
+
+export function fileKindOf(mimeType: string): FileKind {
+ if (mimeType.startsWith('image/')) return 'image'
+ if (mimeType === 'application/pdf') return 'pdf'
+ if (mimeType.startsWith('video/')) return 'video'
+ if (mimeType.startsWith('audio/')) return 'audio'
+ if (mimeType.startsWith('text/') || TEXT_TYPES.has(mimeType)) return 'text'
+ return 'other'
+}
+
+export function fileExtensionOf(name: string): string {
+ const dot = name.lastIndexOf('.')
+ return dot > 0 && dot < name.length - 1 ? name.slice(dot + 1).toUpperCase().slice(0, 5) : ''
+}
+
+export function useFileKind() {
+ const kindOf = fileKindOf
+ const iconOf = (mimeType: string) => ICONS[fileKindOf(mimeType)]
+ const isPreviewable = (mimeType: string) => fileKindOf(mimeType) !== 'other'
+ const extensionOf = fileExtensionOf
+
+ const formatBytes = (bytes: number): string => {
+ if (bytes < 1024) return `${bytes} B`
+ const units = ['KB', 'MB', 'GB', 'TB']
+ let value = bytes / 1024
+ let unit = 0
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024
+ unit += 1
+ }
+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`
+ }
+
+ return { kindOf, iconOf, isPreviewable, extensionOf, formatBytes }
+}
diff --git a/web/src/composables/useFileUpload.ts b/web/src/composables/useFileUpload.ts
new file mode 100644
index 0000000..79c16b4
--- /dev/null
+++ b/web/src/composables/useFileUpload.ts
@@ -0,0 +1,52 @@
+import { computed, onBeforeUnmount, onMounted, type Ref } from 'vue'
+import { useFileDialog } from '@vueuse/core'
+import { useFilesStore } from '@/stores/files.store'
+
+export type UseFileUploadArgs = {
+ goalId: Ref<number>
+ taskId: Ref<number | null>
+ enabled: Ref<boolean>
+ pasteTarget?: Ref<HTMLElement | null>
+}
+
+export function useFileUpload(args: UseFileUploadArgs) {
+ const filesStore = useFilesStore()
+ const uploads = computed(() => filesStore.uploadsFor(args.goalId.value, args.taskId.value))
+
+ const upload = (files: File[]) => {
+ if (!args.enabled.value || files.length === 0) return
+ void filesStore.upload({ goalId: args.goalId.value, taskId: args.taskId.value, files })
+ }
+
+ const dialog = useFileDialog({ multiple: true, reset: true })
+ dialog.onChange((list) => {
+ if (list) upload(Array.from(list))
+ })
+
+ const onPaste = (event: ClipboardEvent) => {
+ if (!args.enabled.value) return
+ const target = event.target as HTMLElement | null
+ if (target && (target.isContentEditable || ['INPUT', 'TEXTAREA'].includes(target.tagName))) return
+ const files = Array.from(event.clipboardData?.files ?? [])
+ if (files.length === 0) return
+ event.preventDefault()
+ upload(files)
+ }
+
+ onMounted(() => {
+ const element = args.pasteTarget?.value ?? document
+ element.addEventListener('paste', onPaste as EventListener)
+ })
+ onBeforeUnmount(() => {
+ const element = args.pasteTarget?.value ?? document
+ element.removeEventListener('paste', onPaste as EventListener)
+ })
+
+ return {
+ uploads,
+ upload,
+ openDialog: dialog.open,
+ retry: (id: string) => filesStore.retryUpload(id),
+ cancel: (id: string) => filesStore.cancelUpload(id),
+ }
+}
diff --git a/web/src/composables/useGoalPermissions.ts b/web/src/composables/useGoalPermissions.ts
index b082e24..0577f2f 100644
--- a/web/src/composables/useGoalPermissions.ts
+++ b/web/src/composables/useGoalPermissions.ts
@@ -31,6 +31,8 @@ export function useGoalPermissionsFor(goalRef: Ref<GoalItem | null>) {
canManageSprints: can('SPRINT_CAN_MANAGE'),
canAssignSprintTasks: can('SPRINT_CAN_ASSIGN_TASKS'),
canViewSprintAnalytics: can('SPRINT_CAN_VIEW_ANALYTICS'),
+ canViewFiles: computed(() => hasPermission(goalRef.value, 'FILE_CAN_VIEW') || hasPermission(goalRef.value, 'FILE_CAN_MANAGE')),
+ canManageFiles: can('FILE_CAN_MANAGE'),
}
}
@@ -94,6 +96,9 @@ export const useGoalPermissions = () => {
const canAssignSprintTasks = computed(() => permissions.SPRINT_CAN_ASSIGN_TASKS)
const canViewSprintAnalytics = computed(() => permissions.SPRINT_CAN_VIEW_ANALYTICS)
+ const canViewFiles = computed(() => permissions.FILE_CAN_VIEW || permissions.FILE_CAN_MANAGE)
+ const canManageFiles = computed(() => permissions.FILE_CAN_MANAGE)
+
return {
permissions,
canDeleteGoal,
@@ -135,5 +140,7 @@ export const useGoalPermissions = () => {
canManageSprints,
canAssignSprintTasks,
canViewSprintAnalytics,
+ canViewFiles,
+ canManageFiles,
}
}
diff --git a/web/src/locales/de.ts b/web/src/locales/de.ts
index 2bc6b7d..a50e50c 100644
--- a/web/src/locales/de.ts
+++ b/web/src/locales/de.ts
@@ -1446,6 +1446,8 @@ export default {
previous: 'Zurück',
next: 'Weiter',
noPermission: 'Sie haben keine Berechtigung, die Dateien dieses Projekts zu sehen',
+ storageDisabled: 'Der Dateispeicher ist auf diesem Server nicht konfiguriert',
+ storageDisabledHint: 'Anhänge sind nicht verfügbar.',
filters: {
all: 'Alle',
images: 'Bilder',
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index e474876..f357c1c 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -1460,6 +1460,8 @@ export default {
previous: 'Previous',
next: 'Next',
noPermission: 'You do not have permission to view files of this project',
+ storageDisabled: 'File storage is not configured on this server',
+ storageDisabledHint: 'Attachments are unavailable.',
filters: {
all: 'All',
images: 'Images',
diff --git a/web/src/locales/es.ts b/web/src/locales/es.ts
index 2406cc4..4c4c14f 100644
--- a/web/src/locales/es.ts
+++ b/web/src/locales/es.ts
@@ -1446,6 +1446,8 @@ export default {
previous: 'Anterior',
next: 'Siguiente',
noPermission: 'No tienes permiso para ver los archivos de este proyecto',
+ storageDisabled: 'El almacenamiento de archivos no está configurado en este servidor',
+ storageDisabledHint: 'Los adjuntos no están disponibles.',
filters: {
all: 'Todos',
images: 'Imágenes',
diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.ts
index acc2d50..7e53e5b 100644
--- a/web/src/locales/pt-br.ts
+++ b/web/src/locales/pt-br.ts
@@ -1457,6 +1457,8 @@ export default {
previous: 'Anterior',
next: 'Próximo',
noPermission: 'Você não tem permissão para ver os arquivos deste projeto',
+ storageDisabled: 'O armazenamento de arquivos não está configurado neste servidor',
+ storageDisabledHint: 'Os anexos não estão disponíveis.',
filters: {
all: 'Todos',
images: 'Imagens',
diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts
index 0d0f24b..47b7630 100644
--- a/web/src/locales/ru.ts
+++ b/web/src/locales/ru.ts
@@ -1395,6 +1395,8 @@ export default {
previous: 'Назад',
next: 'Вперёд',
noPermission: 'У вас нет прав на просмотр файлов этого проекта',
+ storageDisabled: 'Хранилище файлов не настроено на этом сервере',
+ storageDisabledHint: 'Вложения недоступны.',
filters: {
all: 'Все',
images: 'Картинки',
diff --git a/web/src/pages/user/files.vue b/web/src/pages/user/files.vue
new file mode 100644
index 0000000..86ac824
--- /dev/null
+++ b/web/src/pages/user/files.vue
@@ -0,0 +1,55 @@
+<template>
+ <UDashboardPanel
+ id="files"
+ :ui="{ body: 'pt-0! px-0!' }"
+ >
+ <template #header>
+ <UDashboardNavbar :title="`${projectName} - ${t('files.title')}`">
+ <template #leading>
+ <TvCollapseSidebarDesktop />
+ </template>
+ </UDashboardNavbar>
+ </template>
+
+ <template #body>
+ <div
+ v-if="!canViewFiles"
+ class="flex flex-col items-center gap-2 px-4 py-16 text-center"
+ >
+ <UIcon
+ name="i-lucide-lock"
+ class="size-8 text-dimmed"
+ />
+ <p class="text-muted">
+ {{ t('files.noPermission') }}
+ </p>
+ </div>
+ <FilesProjectTab
+ v-else
+ :goal-id="projectId"
+ :can-manage="canManageFiles"
+ />
+ </template>
+ </UDashboardPanel>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import TvCollapseSidebarDesktop from '@/components/features/base/TvCollapseSidebarDesktop.vue'
+import FilesProjectTab from '@/components/features/files/FilesProjectTab.vue'
+import { useAppRouteInfo } from '@/composables/useAppRouteInfo'
+import { useProjectDataLoader } from '@/composables/useProjectDataLoader'
+import { useGoalsStore } from '@/stores/goals.store'
+import { useGoalPermissionsFor } from '@/composables/useGoalPermissions'
+
+const { t } = useI18n()
+const { projectId } = useAppRouteInfo()
+const goalsStore = useGoalsStore()
+
+useProjectDataLoader(projectId)
+
+const projectName = computed(() => goalsStore.goalMap.get(projectId.value)?.name ?? '')
+const goal = computed(() => goalsStore.goalMap.get(projectId.value) ?? null)
+const { canViewFiles, canManageFiles } = useGoalPermissionsFor(goal)
+</script>
diff --git a/web/src/stores/files.store.ts b/web/src/stores/files.store.ts
new file mode 100644
index 0000000..66390a8
--- /dev/null
+++ b/web/src/stores/files.store.ts
@@ -0,0 +1,222 @@
+import { defineStore } from 'pinia'
+import type { TvFile, TvFileLinkArgs, TvFileRenameArgs, TvFileUnlinkArgs } from 'taskview-api'
+import { $tvApi } from '@/plugins/axios'
+import { logError } from '@/helpers/Helper'
+import type {
+ FileUploadItem,
+ FilesFetchForGoalArgs,
+ FilesRemoteChangeArgs,
+ FilesStoreState,
+ FilesUploadArgs,
+} from '@/types/files.types'
+
+const PAGE_SIZE = 50
+
+export const useFilesStore = defineStore('files', {
+ state: (): FilesStoreState => ({
+ byTask: {},
+ loadingTasks: {},
+ project: { goalId: null, items: [], nextCursor: null, search: '', type: 'all', loading: false },
+ uploads: [],
+ storage: { enabled: null, maxFileSizeBytes: null },
+ }),
+ getters: {
+ storageEnabled: (state): boolean => state.storage.enabled !== false,
+ filesForTask: (state) => (taskId: number): TvFile[] => state.byTask[taskId] ?? [],
+ uploadsFor: (state) => (goalId: number, taskId: number | null): FileUploadItem[] =>
+ state.uploads.filter((u) => u.goalId === goalId && u.taskId === taskId),
+ },
+ actions: {
+ async fetchStorageStatus(): Promise<void> {
+ if (this.storage.enabled !== null) return
+ const status = await $tvApi.files.status().catch(logError)
+ if (status) this.storage = { enabled: status.enabled, maxFileSizeBytes: status.maxFileSizeBytes }
+ },
+
+ async fetchForTask(taskId: number): Promise<void> {
+ this.loadingTasks[taskId] = true
+ const files = await $tvApi.files
+ .listForTask(taskId)
+ .catch(logError)
+ .finally(() => {
+ this.loadingTasks[taskId] = false
+ })
+ if (files) this.byTask[taskId] = files
+ },
+
+ async fetchForGoal(args: FilesFetchForGoalArgs): Promise<void> {
+ const changedScope = this.project.goalId !== args.goalId
+ if (changedScope || !args.append) {
+ this.project.goalId = args.goalId
+ this.project.items = []
+ this.project.nextCursor = null
+ }
+ if (args.search !== undefined) this.project.search = args.search
+ if (args.type !== undefined) this.project.type = args.type
+
+ this.project.loading = true
+ const page = await $tvApi.files
+ .listForGoal({
+ goalId: args.goalId,
+ search: this.project.search || null,
+ type: this.project.type,
+ cursor: args.append ? this.project.nextCursor : null,
+ limit: PAGE_SIZE,
+ })
+ .catch(logError)
+ .finally(() => {
+ this.project.loading = false
+ })
+ if (!page || this.project.goalId !== args.goalId) return
+ this.project.items = args.append ? [...this.project.items, ...page.items] : page.items
+ this.project.nextCursor = page.nextCursor
+ },
+
+ async loadMoreForGoal(): Promise<void> {
+ if (!this.project.goalId || !this.project.nextCursor || this.project.loading) return
+ await this.fetchForGoal({ goalId: this.project.goalId, append: true })
+ },
+
+ upload(args: FilesUploadArgs): Promise<TvFile[]> {
+ return Promise.all(args.files.map((file) => this.uploadOne({ goalId: args.goalId, taskId: args.taskId, file })))
+ .then((results) => results.filter((r): r is TvFile => r !== null))
+ },
+
+ async uploadOne(args: { goalId: number; taskId: number | null; file: File }): Promise<TvFile | null> {
+ const item: FileUploadItem = {
+ id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
+ goalId: args.goalId,
+ taskId: args.taskId,
+ file: args.file,
+ name: args.file.name,
+ sizeBytes: args.file.size,
+ progress: 0,
+ status: 'uploading',
+ errorKey: null,
+ controller: new AbortController(),
+ }
+ this.uploads.push(item)
+
+ try {
+ const uploaded = await $tvApi.files.upload({
+ goalId: args.goalId,
+ taskId: args.taskId,
+ file: args.file,
+ fileName: args.file.name,
+ signal: item.controller.signal,
+ onProgress: (percent) => {
+ const current = this.uploads.find((u) => u.id === item.id)
+ if (current) current.progress = percent
+ },
+ })
+ this.removeUpload(item.id)
+ this.applyUploaded(uploaded)
+ return uploaded
+ } catch (err) {
+ const current = this.uploads.find((u) => u.id === item.id)
+ if (!current) return null
+ if (item.controller.signal.aborted) {
+ this.removeUpload(item.id)
+ return null
+ }
+ current.status = 'error'
+ current.progress = 0
+ current.errorKey = this.errorKeyFor(err)
+ return null
+ }
+ },
+
+ retryUpload(uploadId: string): Promise<TvFile | null> {
+ const item = this.uploads.find((u) => u.id === uploadId)
+ if (!item) return Promise.resolve(null)
+ this.removeUpload(uploadId)
+ return this.uploadOne({ goalId: item.goalId, taskId: item.taskId, file: item.file })
+ },
+
+ cancelUpload(uploadId: string) {
+ const item = this.uploads.find((u) => u.id === uploadId)
+ if (!item) return
+ item.controller.abort()
+ this.removeUpload(uploadId)
+ },
+
+ removeUpload(uploadId: string) {
+ this.uploads = this.uploads.filter((u) => u.id !== uploadId)
+ },
+
+ async link(args: TvFileLinkArgs): Promise<boolean> {
+ const files = await $tvApi.files.link(args).catch(logError)
+ if (!files) return false
+ const current = this.byTask[args.taskId] ?? []
+ const known = new Set(current.map((f) => f.id))
+ this.byTask[args.taskId] = [...files.filter((f) => !known.has(f.id)), ...current]
+ files.forEach((f) => this.replaceEverywhere(f))
+ return true
+ },
+
+ async unlink(args: TvFileUnlinkArgs): Promise<boolean> {
+ const result = await $tvApi.files.unlink(args).then(() => true).catch((err) => { logError(err); return false })
+ if (!result) return false
+ this.byTask[args.taskId] = (this.byTask[args.taskId] ?? []).filter((f) => f.id !== args.fileId)
+ const inProject = this.project.items.find((f) => f.id === args.fileId)
+ if (inProject) inProject.linkedTaskIds = inProject.linkedTaskIds.filter((id) => id !== args.taskId)
+ return true
+ },
+
+ async rename(args: TvFileRenameArgs): Promise<TvFile | null> {
+ const file = await $tvApi.files.rename(args).catch(logError)
+ if (!file) return null
+ this.replaceEverywhere(file)
+ return file
+ },
+
+ async deleteForever(fileId: string): Promise<boolean> {
+ const result = await $tvApi.files.deleteForever(fileId).then(() => true).catch((err) => { logError(err); return false })
+ if (!result) return false
+ for (const taskId of Object.keys(this.byTask)) {
+ this.byTask[Number(taskId)] = this.byTask[Number(taskId)].filter((f) => f.id !== fileId)
+ }
+ this.project.items = this.project.items.filter((f) => f.id !== fileId)
+ return true
+ },
+
+ async downloadUrl(args: { fileId: string; inline: boolean }): Promise<string | null> {
+ const result = await $tvApi.files.downloadUrl(args).catch(logError)
+ return result?.url ?? null
+ },
+
+ handleRemoteChange(args: FilesRemoteChangeArgs) {
+ args.taskIds.forEach((taskId) => {
+ if (this.byTask[taskId]) void this.fetchForTask(taskId)
+ })
+ if (this.project.goalId === args.goalId) void this.fetchForGoal({ goalId: args.goalId })
+ },
+
+ applyUploaded(file: TvFile) {
+ file.linkedTaskIds.forEach((taskId) => {
+ const list = this.byTask[taskId]
+ if (list && !list.some((f) => f.id === file.id)) list.unshift(file)
+ })
+ if (this.project.goalId === file.goalId && !this.project.items.some((f) => f.id === file.id)) {
+ this.project.items.unshift(file)
+ }
+ },
+
+ replaceEverywhere(file: TvFile) {
+ for (const list of Object.values(this.byTask)) {
+ const index = list.findIndex((f) => f.id === file.id)
+ if (index !== -1) list[index] = file
+ }
+ const index = this.project.items.findIndex((f) => f.id === file.id)
+ if (index !== -1) this.project.items[index] = file
+ },
+
+ errorKeyFor(err: unknown): string {
+ const status = (err as { response?: { status?: number } })?.response?.status
+ if (status === 413) return 'files.errors.tooLarge'
+ if (status === 403) return 'files.errors.forbidden'
+ if (status === 404) return 'files.errors.notFound'
+ return 'files.errors.uploadFailed'
+ },
+ },
+})
diff --git a/web/src/types/files.types.ts b/web/src/types/files.types.ts
index f615e05..e65d74e 100644
--- a/web/src/types/files.types.ts
+++ b/web/src/types/files.types.ts
@@ -26,11 +26,17 @@ export type FilesProjectListState = {
loading: boolean
}
+export type FilesStorageState = {
+ enabled: boolean | null
+ maxFileSizeBytes: number | null
+}
+
export type FilesStoreState = {
byTask: Record<number, TvFile[]>
loadingTasks: Record<number, boolean>
project: FilesProjectListState
uploads: FileUploadItem[]
+ storage: FilesStorageState
}
export type FilesUploadArgs = {