Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions apps/api/src/content/files.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { eq } from 'drizzle-orm';
import { eq, sql } from 'drizzle-orm';
import { randomUUID } from 'node:crypto';
import { mkdir, rm, stat, readdir } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
Expand Down Expand Up @@ -39,14 +39,29 @@ export class FileStore {
if (!record) await rm(path, { force: true });
}
}
async upload(actor: Actor, householdId: string, taskId: string, part: MultipartFile) {
async upload(actor: Actor, householdId: string, taskId: string, part: MultipartFile, uploadId: string = randomUUID()) {
await this.service.task(actor, householdId, taskId);
// The same attempt keeps its ID after a lost response. A database lock also
// protects the original bytes from overlapping retries across API processes.
return this.service.db.transaction(async tx => {
const lock = await tx.execute(sql`select pg_try_advisory_xact_lock(hashtextextended(${uploadId}, 0)) as acquired`);
if (!lock.rows[0]?.acquired) { part.file.resume(); throw new AccountError('uploads_busy', 503); }
const [existing] = await tx.select().from(attachments).where(eq(attachments.id, uploadId));
if (existing) {
part.file.resume();
if (existing.householdId !== householdId || existing.taskId !== taskId || existing.deleted)
throw new AccountError('upload_id_conflict', 409);
return { ...existing, createdAt: existing.createdAt.toISOString() };
}
return this.store(actor, householdId, taskId, part, uploadId);
});
}
private async store(actor: Actor, householdId: string, taskId: string, part: MultipartFile, id: string) {
if (this.active >= 2) {
part.file.resume();
throw new AccountError('uploads_busy', 503);
}
this.active++;
const id = randomUUID();
try {
await mkdir(this.root, { recursive: true });
await pipeline(part.file, createWriteStream(this.path(id), { flags: 'wx', mode: 0o600 }));
Expand Down
4 changes: 2 additions & 2 deletions apps/api/src/content/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,15 +140,15 @@ export async function registerContentRoutes(
'/api/v1/households/:householdId/tasks/:taskId/attachments',
{
config: { fileUpload: true },
schema: { params: task, response: { 200: attachmentSchema } },
schema: { params: task, headers: z.object({ 'x-upload-id': z.uuid().optional() }), response: { 200: attachmentSchema } },
preHandler: async (r) => {
await service.task(await actor(r), r.params.householdId, r.params.taskId);
},
},
async (r) => {
const part = await r.file();
if (!part) throw new AccountError('empty_file');
return files.upload(await actor(r), r.params.householdId, r.params.taskId, part);
return files.upload(await actor(r), r.params.householdId, r.params.taskId, part, r.headers['x-upload-id']);
},
);
for (const mode of ['download', 'preview', 'thumbnail'] as const) {
Expand Down
7 changes: 6 additions & 1 deletion apps/api/src/content/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export async function searchContent(
)
continue;
if (matched++ >= offset)
items.push(searchHitSchema.parse({ ...row, snippet: text.slice(0, 250) }));
items.push(searchHitSchema.parse({ ...row, snippet: searchSnippet(text, needle) }));
if (items.length === 51) break;
}
if (batch.rows.length < 256) break;
Expand All @@ -77,3 +77,8 @@ export async function searchContent(
{ isolationLevel: 'repeatable read', accessMode: 'read only' },
);
}

function searchSnippet(text: string, needle: string) {
const start = Math.max(0, text.toLowerCase().indexOf(needle) - 70);
return (start ? '…' : '') + text.slice(start, start + 250) + (start + 250 < text.length ? '…' : '');
}
19 changes: 16 additions & 3 deletions apps/api/src/tasks/tasks.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,22 @@ it('preserves rich content, enforces comment authorship/versioning and scopes se
const bytes=await readFile(new URL('../../../../tests/fixtures/'+name,import.meta.url));
const boundary='tendly-test-boundary';
const payload=Buffer.concat([Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: application/octet-stream\r\n\r\n`),bytes,Buffer.from(`\r\n--${boundary}--\r\n`)]);
const upload=await app.inject({method:'POST',url:path+'/attachments',headers:{...headers(sessionA),'content-type':`multipart/form-data; boundary=${boundary}`},payload});
expect(upload.statusCode,upload.body).toBe(200);
const f=upload.json();expect(f.preview).toBe(true);
const uploadId = randomUUID();
const request = {method:'POST' as const,url:path+'/attachments',headers:{...headers(sessionA),'x-upload-id':uploadId,'content-type':`multipart/form-data; boundary=${boundary}`},payload};
const [upload, concurrent] = await Promise.all([app.inject(request), app.inject(request)]);
const succeeded = upload.statusCode === 200 ? upload : concurrent;
expect([200, 503]).toContain(upload.statusCode);
expect([200, 503]).toContain(concurrent.statusCode);
if (upload.statusCode === 200 && concurrent.statusCode === 200) expect(upload.json().id).toBe(concurrent.json().id);
const retry = await app.inject(request);
expect(retry.statusCode).toBe(200);
expect(retry.json().id).toBe(succeeded.json().id);
const listing = await app.inject({url:path+'/attachments',headers:headers(sessionA)});
expect(listing.json().filter((item: {id:string}) => item.id === uploadId)).toHaveLength(1);
const foreignRetry = await app.inject({...request, url:`/api/v1/households/${householdB}/tasks/${task.id}/attachments`,headers:{...request.headers,cookie:headers(sessionB).cookie}});
expect(foreignRetry.statusCode).toBe(404);
expect(succeeded.statusCode,succeeded.body).toBe(200);
const f=succeeded.json();expect(f.preview).toBe(true);
const url=`/api/v1/households/${householdA}/attachments/${f.id}`;
expect((await app.inject({url:url+'/download',headers:headers(sessionA)})).rawPayload).toEqual(bytes);
const preview=await app.inject({url:url+'/preview',headers:headers(sessionA)});
Expand Down
33 changes: 26 additions & 7 deletions apps/web/src/components/ui/dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,44 @@
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { useRef, type ReactNode } from 'react';
import { X } from 'lucide-react';
import { ArrowLeft, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
// shadcn/ui's Radix composition: focus trapping, Escape and focus restoration live
// in the primitive; Tendly supplies its responsive sheet treatment.
export function Dialog({ open, onOpenChange, title, children, sheet = false, wide = false }: {
export function Dialog({ open, onOpenChange, title, children, sheet = false, wide = false, className = '', headerContent, mobileBack = false, onReturnFocus, onInitialFocus }: {
open: boolean; onOpenChange: (open: boolean) => void; title: string; children: ReactNode; sheet?: boolean; wide?: boolean;
className?: string; headerContent?: ReactNode; mobileBack?: boolean;
onReturnFocus?: () => void;
onInitialFocus?: () => void;
}) {
const { t } = useTranslation();
const returnFocus = useRef(document.activeElement);
return <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="dialog-overlay" />
<DialogPrimitive.Content className={'dialog-content' + (sheet ? ' task-sheet' : '') + (wide ? ' dialog-wide' : '')} aria-describedby={undefined} onCloseAutoFocus={event => {
<DialogPrimitive.Content className={'dialog-content' + (sheet ? ' task-sheet' : '') + (wide ? ' dialog-wide' : '') + ' ' + className} aria-describedby={undefined} onOpenAutoFocus={event => {
if (onInitialFocus) { event.preventDefault(); onInitialFocus(); }
}} onCloseAutoFocus={event => {
event.preventDefault();
const target = returnFocus.current;
if (target instanceof HTMLElement && target.isConnected) target.focus();
else document.querySelector<HTMLElement>('.workspace-main')?.focus();
if (onReturnFocus) { onReturnFocus(); return; }
const closing = event.currentTarget;
requestAnimationFrame(() => {
const nextDialog = [...document.querySelectorAll<HTMLElement>('[role="dialog"]')].filter(el => el !== closing && el.getClientRects().length).at(-1);
if (nextDialog) {
if (!nextDialog.contains(document.activeElement)) (nextDialog.querySelector<HTMLElement>('input:not([disabled]), textarea:not([disabled]), button:not([disabled])') ?? nextDialog).focus({ preventScroll: true });
return;
}
const target = returnFocus.current;
if (target instanceof HTMLElement && target.isConnected) target.focus({ preventScroll: true });
else document.querySelector<HTMLElement>('.workspace-main')?.focus({ preventScroll: true });
});
}}>
<div className="dialog-heading"><DialogPrimitive.Title>{title}</DialogPrimitive.Title>
<DialogPrimitive.Close asChild><button className="icon-button quiet" aria-label={t('close')}><X size={20} /></button></DialogPrimitive.Close>
<div className="dialog-heading-actions">{headerContent}
<DialogPrimitive.Close asChild><button className={'icon-button quiet' + (mobileBack ? ' task-back' : '')} aria-label={t(mobileBack ? 'backToTasks' : 'close')}>
{mobileBack && <ArrowLeft className="task-back-arrow" size={20} />}<X className="dialog-close-icon" size={20} />
{mobileBack && <span className="task-back-label">{t('back')}</span>}
</button></DialogPrimitive.Close>
</div>
</div>
{children}
</DialogPrimitive.Content>
Expand Down
Loading
Loading