add: delete actions for device + slightly better ui

This commit is contained in:
user
2026-03-01 18:59:43 +02:00
parent d000ccfeca
commit 48792692ff
11 changed files with 626 additions and 79 deletions

View File

@@ -3,7 +3,7 @@ import {
getFlowExecCtxForRemoteFuncs, getFlowExecCtxForRemoteFuncs,
unauthorized, unauthorized,
} from "$lib/core/server.utils"; } from "$lib/core/server.utils";
import { getRequestEvent, query } from "$app/server"; import { command, getRequestEvent, query } from "$app/server";
import * as v from "valibot"; import * as v from "valibot";
const fc = getFileController(); const fc = getFileController();
@@ -46,3 +46,33 @@ export const getFilesSQ = query(getFilesInputSchema, async (input) => {
? { data: res.value, error: null } ? { data: res.value, error: null }
: { data: null, error: res.error }; : { data: null, error: res.error };
}); });
const deleteFileInputSchema = v.object({
fileId: v.string(),
});
export const deleteFileSC = command(deleteFileInputSchema, async (input) => {
const event = getRequestEvent();
const fctx = await getFlowExecCtxForRemoteFuncs(event.locals);
if (!fctx.userId) {
return unauthorized(fctx);
}
const res = await fc.deleteFile(fctx, input.fileId, fctx.userId);
return res.isOk()
? { data: res.value, error: null }
: { data: null, error: res.error };
});
export const cleanupDanglingFilesSC = command(v.object({}), async () => {
const event = getRequestEvent();
const fctx = await getFlowExecCtxForRemoteFuncs(event.locals);
if (!fctx.userId) {
return unauthorized(fctx);
}
const res = await fc.cleanupDanglingStorageFiles(fctx, fctx.userId);
return res.isOk()
? { data: res.value, error: null }
: { data: null, error: res.error };
});

View File

@@ -1,10 +1,12 @@
import type { File } from "@pkg/logic/domains/files/data"; import type { File } from "@pkg/logic/domains/files/data";
import { getFilesSQ } from "./files.remote"; import { cleanupDanglingFilesSC, deleteFileSC, getFilesSQ } from "./files.remote";
import { toast } from "svelte-sonner"; import { toast } from "svelte-sonner";
class FilesViewModel { class FilesViewModel {
files = $state([] as File[]); files = $state([] as File[]);
loading = $state(false); loading = $state(false);
deletingFileId = $state(null as string | null);
cleanupLoading = $state(false);
search = $state(""); search = $state("");
page = $state(1); page = $state(1);
@@ -55,6 +57,53 @@ class FilesViewModel {
} }
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`; return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
} }
async deleteFile(fileId: string) {
this.deletingFileId = fileId;
try {
const result = await deleteFileSC({ fileId });
if (result?.error) {
toast.error(result.error.message || "Failed to delete file", {
description: result.error.description || "Please try again later",
});
return;
}
toast.success("File deleted");
await this.fetchFiles();
} catch (error) {
toast.error("Failed to delete file", {
description:
error instanceof Error ? error.message : "Please try again later",
});
} finally {
this.deletingFileId = null;
}
}
async cleanupDanglingFiles() {
this.cleanupLoading = true;
try {
const result = await cleanupDanglingFilesSC({});
if (result?.error || !result?.data) {
toast.error(result?.error?.message || "Cleanup failed", {
description: result?.error?.description || "Please try again later",
});
return;
}
toast.success("Storage cleanup completed", {
description: `Deleted ${result.data.deleted} dangling files (scanned ${result.data.scanned})`,
});
} catch (error) {
toast.error("Cleanup failed", {
description:
error instanceof Error ? error.message : "Please try again later",
});
} finally {
this.cleanupLoading = false;
}
}
} }
export const filesVM = new FilesViewModel(); export const filesVM = new FilesViewModel();

View File

@@ -8,7 +8,7 @@ import {
getFlowExecCtxForRemoteFuncs, getFlowExecCtxForRemoteFuncs,
unauthorized, unauthorized,
} from "$lib/core/server.utils"; } from "$lib/core/server.utils";
import { getRequestEvent, query } from "$app/server"; import { command, getRequestEvent, query } from "$app/server";
import * as v from "valibot"; import * as v from "valibot";
const mc = getMobileController(); const mc = getMobileController();
@@ -109,3 +109,21 @@ export const getDeviceMediaSQ = query(
: { data: null, error: res.error }; : { data: null, error: res.error };
}, },
); );
export const deleteDeviceSC = command(
v.object({
deviceId: v.pipe(v.number(), v.integer()),
}),
async (payload) => {
const event = getRequestEvent();
const fctx = await getFlowExecCtxForRemoteFuncs(event.locals);
if (!fctx.userId) {
return unauthorized(fctx);
}
const res = await mc.deleteDevice(fctx, payload.deviceId, fctx.userId);
return res.isOk()
? { data: res.value, error: null }
: { data: null, error: res.error };
},
);

View File

@@ -5,6 +5,7 @@ import type {
MobileSMS, MobileSMS,
} from "@pkg/logic/domains/mobile/data"; } from "@pkg/logic/domains/mobile/data";
import { import {
deleteDeviceSC,
getDeviceDetailSQ, getDeviceDetailSQ,
getDeviceMediaSQ, getDeviceMediaSQ,
getDeviceSmsSQ, getDeviceSmsSQ,
@@ -34,6 +35,7 @@ class MobileViewModel {
mediaPage = $state(1); mediaPage = $state(1);
mediaPageSize = $state(25); mediaPageSize = $state(25);
mediaTotal = $state(0); mediaTotal = $state(0);
deletingDeviceId = $state(null as number | null);
private devicesPollTimer: ReturnType<typeof setInterval> | null = null; private devicesPollTimer: ReturnType<typeof setInterval> | null = null;
private smsPollTimer: ReturnType<typeof setInterval> | null = null; private smsPollTimer: ReturnType<typeof setInterval> | null = null;
@@ -177,6 +179,38 @@ class MobileViewModel {
} }
} }
async deleteDevice(deviceId: number) {
this.deletingDeviceId = deviceId;
try {
const result = await deleteDeviceSC({ deviceId });
if (result?.error || !result?.data) {
toast.error(result?.error?.message || "Failed to delete device", {
description: result?.error?.description || "Please try again later",
});
return false;
}
this.devices = this.devices.filter((d) => d.id !== deviceId);
this.devicesTotal = Math.max(0, this.devicesTotal - 1);
if (this.selectedDeviceDetail?.device.id === deviceId) {
this.selectedDeviceDetail = null;
}
toast.success("Device deleted", {
description: `Deleted ${result.data.deletedFileCount} related file(s)`,
});
return true;
} catch (error) {
toast.error("Failed to delete device", {
description:
error instanceof Error ? error.message : "Please try again later",
});
return false;
} finally {
this.deletingDeviceId = null;
}
}
startDevicesPolling(intervalMs = 5000) { startDevicesPolling(intervalMs = 5000) {
this.stopDevicesPolling(); this.stopDevicesPolling();
this.devicesPollTimer = setInterval(() => { this.devicesPollTimer = setInterval(() => {

View File

@@ -1,17 +1,21 @@
<script lang="ts"> <script lang="ts">
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import Icon from "$lib/components/atoms/icon.svelte"; import Icon from "$lib/components/atoms/icon.svelte";
import * as AlertDialog from "$lib/components/ui/alert-dialog/index.js";
import { Button } from "$lib/components/ui/button"; import { Button } from "$lib/components/ui/button";
import { buttonVariants } from "$lib/components/ui/button";
import * as Card from "$lib/components/ui/card"; import * as Card from "$lib/components/ui/card";
import { Input } from "$lib/components/ui/input"; import { Input } from "$lib/components/ui/input";
import * as Table from "$lib/components/ui/table"; import * as Table from "$lib/components/ui/table";
import MaxWidthWrapper from "$lib/components/molecules/max-width-wrapper.svelte"; import MaxWidthWrapper from "$lib/components/molecules/max-width-wrapper.svelte";
import { mainNavTree } from "$lib/core/constants"; import { mainNavTree } from "$lib/core/constants";
import { filesVM } from "$lib/domains/files/files.vm.svelte";
import { mobileVM } from "$lib/domains/mobile/mobile.vm.svelte"; import { mobileVM } from "$lib/domains/mobile/mobile.vm.svelte";
import { breadcrumbs } from "$lib/global.stores"; import { breadcrumbs } from "$lib/global.stores";
import Smartphone from "@lucide/svelte/icons/smartphone"; import Smartphone from "@lucide/svelte/icons/smartphone";
import RefreshCw from "@lucide/svelte/icons/refresh-cw"; import RefreshCw from "@lucide/svelte/icons/refresh-cw";
import Search from "@lucide/svelte/icons/search"; import Search from "@lucide/svelte/icons/search";
import Trash2 from "@lucide/svelte/icons/trash-2";
import { onDestroy, onMount } from "svelte"; import { onDestroy, onMount } from "svelte";
breadcrumbs.set([mainNavTree[0]]); breadcrumbs.set([mainNavTree[0]]);
@@ -37,18 +41,32 @@
{mobileVM.devicesTotal} total {mobileVM.devicesTotal} total
</span> </span>
</div> </div>
<Button <div class="flex items-center gap-2">
variant="outline" <Button
size="sm" variant="outline"
onclick={() => void mobileVM.refreshDevices()} size="sm"
disabled={mobileVM.devicesLoading} onclick={() => void filesVM.cleanupDanglingFiles()}
> disabled={filesVM.cleanupLoading}
<Icon >
icon={RefreshCw} <Icon
cls={`h-4 w-4 mr-2 ${mobileVM.devicesLoading ? "animate-spin" : ""}`} icon={Trash2}
/> cls={`h-4 w-4 mr-2 ${filesVM.cleanupLoading ? "animate-spin" : ""}`}
Refresh />
</Button> Cleanup Storage
</Button>
<Button
variant="outline"
size="sm"
onclick={() => void mobileVM.refreshDevices()}
disabled={mobileVM.devicesLoading}
>
<Icon
icon={RefreshCw}
cls={`h-4 w-4 mr-2 ${mobileVM.devicesLoading ? "animate-spin" : ""}`}
/>
Refresh
</Button>
</div>
</div> </div>
<div class="relative mt-3 max-w-sm"> <div class="relative mt-3 max-w-sm">
@@ -82,6 +100,7 @@
<Table.Head>Android</Table.Head> <Table.Head>Android</Table.Head>
<Table.Head>Created</Table.Head> <Table.Head>Created</Table.Head>
<Table.Head>Last Ping</Table.Head> <Table.Head>Last Ping</Table.Head>
<Table.Head>Actions</Table.Head>
</Table.Row> </Table.Row>
</Table.Header> </Table.Header>
<Table.Body> <Table.Body>
@@ -106,6 +125,51 @@
<Table.Cell> <Table.Cell>
{mobileVM.formatLastPing(device.lastPingAt)} {mobileVM.formatLastPing(device.lastPingAt)}
</Table.Cell> </Table.Cell>
<Table.Cell>
<AlertDialog.Root>
<AlertDialog.Trigger
class={buttonVariants({
variant: "destructive",
size: "sm",
})}
disabled={mobileVM.deletingDeviceId ===
device.id}
onclick={(e) => e.stopPropagation()}
>
<Icon
icon={Trash2}
cls="h-4 w-4"
/>
Delete
</AlertDialog.Trigger>
<AlertDialog.Content>
<AlertDialog.Header>
<AlertDialog.Title>
Delete device?
</AlertDialog.Title>
<AlertDialog.Description>
This deletes the device and all related SMS/media data.
Files in storage linked to this device are also removed.
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel>
Cancel
</AlertDialog.Cancel>
<AlertDialog.Action
onclick={async (e) => {
e.stopPropagation();
await mobileVM.deleteDevice(
device.id,
);
}}
>
Delete
</AlertDialog.Action>
</AlertDialog.Footer>
</AlertDialog.Content>
</AlertDialog.Root>
</Table.Cell>
</Table.Row> </Table.Row>
{/each} {/each}
</Table.Body> </Table.Body>

View File

@@ -1,12 +1,13 @@
<script lang="ts"> <script lang="ts">
import { goto } from "$app/navigation";
import { page } from "$app/state"; import { page } from "$app/state";
import * as AlertDialog from "$lib/components/ui/alert-dialog/index.js";
import Icon from "$lib/components/atoms/icon.svelte"; import Icon from "$lib/components/atoms/icon.svelte";
import { Button } from "$lib/components/ui/button"; import { Button, buttonVariants } from "$lib/components/ui/button";
import * as Card from "$lib/components/ui/card"; import * as Card from "$lib/components/ui/card";
import * as Dialog from "$lib/components/ui/dialog/index.js"; import * as Dialog from "$lib/components/ui/dialog/index.js";
import * as Table from "$lib/components/ui/table"; import * as Table from "$lib/components/ui/table";
import * as Tabs from "$lib/components/ui/tabs/index.js"; import * as Tabs from "$lib/components/ui/tabs/index.js";
import type { MobileMediaAsset } from "@pkg/logic/domains/mobile/data";
import { mainNavTree } from "$lib/core/constants"; import { mainNavTree } from "$lib/core/constants";
import { mobileVM } from "$lib/domains/mobile/mobile.vm.svelte"; import { mobileVM } from "$lib/domains/mobile/mobile.vm.svelte";
import { breadcrumbs } from "$lib/global.stores"; import { breadcrumbs } from "$lib/global.stores";
@@ -15,7 +16,9 @@
import ImageIcon from "@lucide/svelte/icons/image"; import ImageIcon from "@lucide/svelte/icons/image";
import MessageSquare from "@lucide/svelte/icons/message-square"; import MessageSquare from "@lucide/svelte/icons/message-square";
import Smartphone from "@lucide/svelte/icons/smartphone"; import Smartphone from "@lucide/svelte/icons/smartphone";
import Trash2 from "@lucide/svelte/icons/trash-2";
import VideoIcon from "@lucide/svelte/icons/video"; import VideoIcon from "@lucide/svelte/icons/video";
import type { MobileMediaAsset } from "@pkg/logic/domains/mobile/data";
import { onDestroy, onMount } from "svelte"; import { onDestroy, onMount } from "svelte";
let selectedTab = $state("sms"); let selectedTab = $state("sms");
@@ -35,7 +38,8 @@
if (!size || size <= 0) return "-"; if (!size || size <= 0) return "-";
if (size < 1024) return `${size} B`; if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`; if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`; if (size < 1024 * 1024 * 1024)
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`; return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
} }
@@ -65,11 +69,53 @@
</script> </script>
<div class="space-y-4"> <div class="space-y-4">
<div class="flex items-center gap-2"> <div class="flex items-center justify-between gap-2">
<Button variant="outline" size="sm" href="/dashboard"> <div class="flex items-center gap-2">
<Icon icon={ArrowLeft} cls="h-4 w-4 mr-1" /> <Button variant="outline" size="sm" href="/dashboard">
Back <Icon icon={ArrowLeft} cls="h-4 w-4 mr-1" />
</Button> Back
</Button>
</div>
{#if mobileVM.selectedDeviceDetail}
<AlertDialog.Root>
<AlertDialog.Trigger
class={buttonVariants({
variant: "destructive",
size: "sm",
})}
disabled={mobileVM.deletingDeviceId ===
mobileVM.selectedDeviceDetail.device.id}
>
<Icon icon={Trash2} cls="h-4 w-4" />
Delete Device
</AlertDialog.Trigger>
<AlertDialog.Content>
<AlertDialog.Header>
<AlertDialog.Title>Delete device?</AlertDialog.Title>
<AlertDialog.Description>
This permanently removes the device with all SMS/media entries and
related files in storage.
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<AlertDialog.Action
onclick={async () => {
if (!mobileVM.selectedDeviceDetail) return;
const deleted = await mobileVM.deleteDevice(
mobileVM.selectedDeviceDetail.device.id,
);
if (deleted) {
await goto("/dashboard");
}
}}
>
Delete Device
</AlertDialog.Action>
</AlertDialog.Footer>
</AlertDialog.Content>
</AlertDialog.Root>
{/if}
</div> </div>
<Card.Root> <Card.Root>
@@ -83,38 +129,75 @@
</Card.Header> </Card.Header>
<Card.Content> <Card.Content>
{#if mobileVM.selectedDeviceDetail} {#if mobileVM.selectedDeviceDetail}
<div class="grid grid-cols-1 gap-3 text-sm md:grid-cols-2"> <div class="grid grid-cols-1 gap-4 lg:grid-cols-3">
<div> <div class="rounded-xl border bg-muted/30 p-4 lg:col-span-2">
<span class="text-muted-foreground">External ID:</span> <div class="flex flex-wrap items-start justify-between gap-3">
<div class="font-mono"> <div>
{mobileVM.selectedDeviceDetail.device.externalDeviceId} <p class="text-lg font-semibold">
{mobileVM.selectedDeviceDetail.device.name}
</p>
<p class="font-mono text-xs text-muted-foreground">
{mobileVM.selectedDeviceDetail.device.externalDeviceId}
</p>
</div>
<div class="text-right text-xs text-muted-foreground">
<p>Created</p>
<p class="text-foreground">
{new Date(
mobileVM.selectedDeviceDetail.device.createdAt,
).toLocaleString()}
</p>
</div>
</div>
<div class="mt-4 grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
<div>
<p class="text-xs text-muted-foreground">Manufacturer</p>
<p class="font-medium">
{mobileVM.selectedDeviceDetail.device.manufacturer}
</p>
</div>
<div>
<p class="text-xs text-muted-foreground">Model</p>
<p class="font-medium">
{mobileVM.selectedDeviceDetail.device.model}
</p>
</div>
<div>
<p class="text-xs text-muted-foreground">Android Version</p>
<p class="font-medium">
{mobileVM.selectedDeviceDetail.device.androidVersion}
</p>
</div>
<div>
<p class="text-xs text-muted-foreground">Last Ping</p>
<p class="font-medium">
{mobileVM.formatLastPing(
mobileVM.selectedDeviceDetail.device.lastPingAt,
)}
</p>
</div>
</div> </div>
</div> </div>
<div>
<span class="text-muted-foreground">Last Ping:</span> <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
<div> <div class="rounded-xl border bg-background p-4">
{mobileVM.formatLastPing( <div class="flex items-center gap-2 text-muted-foreground">
mobileVM.selectedDeviceDetail.device.lastPingAt, <Icon icon={MessageSquare} cls="h-4 w-4" />
)} <p class="text-xs">Total SMS</p>
</div>
<p class="mt-2 text-2xl font-semibold">
{mobileVM.selectedDeviceDetail.smsCount}
</p>
</div> </div>
</div> <div class="rounded-xl border bg-background p-4">
<div> <div class="flex items-center gap-2 text-muted-foreground">
<span class="text-muted-foreground">Manufacturer:</span> <Icon icon={ImageIcon} cls="h-4 w-4" />
<div>{mobileVM.selectedDeviceDetail.device.manufacturer}</div> <p class="text-xs">Total Media</p>
</div> </div>
<div> <p class="mt-2 text-2xl font-semibold">
<span class="text-muted-foreground">Model:</span> {mobileVM.selectedDeviceDetail.mediaCount}
<div>{mobileVM.selectedDeviceDetail.device.model}</div> </p>
</div>
<div>
<span class="text-muted-foreground">Android:</span>
<div>{mobileVM.selectedDeviceDetail.device.androidVersion}</div>
</div>
<div>
<span class="text-muted-foreground">Counts:</span>
<div>
SMS: {mobileVM.selectedDeviceDetail.smsCount}, Media:
{mobileVM.selectedDeviceDetail.mediaCount}
</div> </div>
</div> </div>
</div> </div>
@@ -141,11 +224,15 @@
</Card.Header> </Card.Header>
<Card.Content> <Card.Content>
{#if !mobileVM.smsLoading && mobileVM.sms.length === 0} {#if !mobileVM.smsLoading && mobileVM.sms.length === 0}
<div class="py-8 text-center text-sm text-muted-foreground"> <div
class="py-8 text-center text-sm text-muted-foreground"
>
No SMS records yet. No SMS records yet.
</div> </div>
{:else} {:else}
<div class="max-h-[65vh] overflow-auto rounded-md border"> <div
class="max-h-[55vh] overflow-auto rounded-md border"
>
<Table.Root> <Table.Root>
<Table.Header> <Table.Header>
<Table.Row> <Table.Row>
@@ -158,15 +245,21 @@
<Table.Body> <Table.Body>
{#each mobileVM.sms as message (message.id)} {#each mobileVM.sms as message (message.id)}
<Table.Row> <Table.Row>
<Table.Cell>{message.sender}</Table.Cell> <Table.Cell
>{message.sender}</Table.Cell
>
<Table.Cell> <Table.Cell>
{message.recipient || "-"} {message.recipient || "-"}
</Table.Cell> </Table.Cell>
<Table.Cell class="max-w-[520px] truncate"> <Table.Cell
class="max-w-[520px] truncate"
>
{message.body} {message.body}
</Table.Cell> </Table.Cell>
<Table.Cell> <Table.Cell>
{new Date(message.sentAt).toLocaleString()} {new Date(
message.sentAt,
).toLocaleString()}
</Table.Cell> </Table.Cell>
</Table.Row> </Table.Row>
{/each} {/each}
@@ -185,11 +278,15 @@
</Card.Header> </Card.Header>
<Card.Content> <Card.Content>
{#if !mobileVM.mediaLoading && mobileVM.media.length === 0} {#if !mobileVM.mediaLoading && mobileVM.media.length === 0}
<div class="py-8 text-center text-sm text-muted-foreground"> <div
class="py-8 text-center text-sm text-muted-foreground"
>
No media assets yet. No media assets yet.
</div> </div>
{:else} {:else}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4"> <div
class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4"
>
{#each mobileVM.media as asset (asset.id)} {#each mobileVM.media as asset (asset.id)}
<button <button
type="button" type="button"
@@ -197,26 +294,43 @@
onclick={() => openMediaPreview(asset)} onclick={() => openMediaPreview(asset)}
disabled={!asset.r2Url} disabled={!asset.r2Url}
> >
<div class="bg-muted relative aspect-square"> <div
class="bg-muted relative aspect-square"
>
{#if isImageAsset(asset) && asset.r2Url} {#if isImageAsset(asset) && asset.r2Url}
<img <img
src={asset.r2Url} src={asset.r2Url}
alt={asset.filename || asset.fileId} alt={asset.filename ||
asset.fileId}
class="h-full w-full object-cover" class="h-full w-full object-cover"
loading="lazy" loading="lazy"
/> />
{:else if isVideoAsset(asset)} {:else if isVideoAsset(asset)}
<div class="flex h-full w-full items-center justify-center text-muted-foreground"> <div
class="flex h-full w-full items-center justify-center text-muted-foreground"
>
<div class="text-center"> <div class="text-center">
<Icon icon={VideoIcon} cls="mx-auto h-10 w-10" /> <Icon
<p class="mt-2 text-xs">Video file</p> icon={VideoIcon}
cls="mx-auto h-10 w-10"
/>
<p class="mt-2 text-xs">
Video file
</p>
</div> </div>
</div> </div>
{:else} {:else}
<div class="flex h-full w-full items-center justify-center text-muted-foreground"> <div
class="flex h-full w-full items-center justify-center text-muted-foreground"
>
<div class="text-center"> <div class="text-center">
<Icon icon={FileIcon} cls="mx-auto h-10 w-10" /> <Icon
<p class="mt-2 text-xs">File</p> icon={FileIcon}
cls="mx-auto h-10 w-10"
/>
<p class="mt-2 text-xs">
File
</p>
</div> </div>
</div> </div>
{/if} {/if}
@@ -225,14 +339,24 @@
<p class="truncate text-sm font-medium"> <p class="truncate text-sm font-medium">
{asset.filename || "Untitled"} {asset.filename || "Untitled"}
</p> </p>
<p class="text-muted-foreground truncate text-xs"> <p
class="text-muted-foreground truncate text-xs"
>
{asset.mimeType} {asset.mimeType}
</p> </p>
<div class="flex items-center justify-between text-xs text-muted-foreground"> <div
<span>{formatSize(asset.sizeBytes)}</span> class="flex items-center justify-between text-xs text-muted-foreground"
>
<span
>{formatSize(
asset.sizeBytes,
)}</span
>
<span> <span>
{asset.capturedAt {asset.capturedAt
? new Date(asset.capturedAt).toLocaleDateString() ? new Date(
asset.capturedAt,
).toLocaleDateString()
: "-"} : "-"}
</span> </span>
</div> </div>
@@ -251,8 +375,11 @@
<Dialog.Content class="max-w-6xl p-8"> <Dialog.Content class="max-w-6xl p-8">
{#if selectedMedia} {#if selectedMedia}
<Dialog.Header> <Dialog.Header>
<Dialog.Title>{selectedMedia.filename || "Media Preview"}</Dialog.Title> <Dialog.Title
<Dialog.Description>{selectedMedia.mimeType}</Dialog.Description> >{selectedMedia.filename || "Media Preview"}</Dialog.Title
>
<Dialog.Description>{selectedMedia.mimeType}</Dialog.Description
>
</Dialog.Header> </Dialog.Header>
<div class="mt-2"> <div class="mt-2">
@@ -263,17 +390,25 @@
class="max-h-[80vh] w-full rounded-md object-contain" class="max-h-[80vh] w-full rounded-md object-contain"
/> />
{:else if isVideoAsset(selectedMedia)} {:else if isVideoAsset(selectedMedia)}
<div class="bg-muted flex h-[60vh] items-center justify-center rounded-md text-center text-sm text-muted-foreground"> <div
class="bg-muted flex h-[60vh] items-center justify-center rounded-md text-center text-sm text-muted-foreground"
>
<div> <div>
<Icon icon={VideoIcon} cls="mx-auto h-10 w-10" /> <Icon icon={VideoIcon} cls="mx-auto h-10 w-10" />
<p class="mt-2">Video preview opens in a new tab.</p> <p class="mt-2">
Video preview opens in a new tab.
</p>
</div> </div>
</div> </div>
{:else} {:else}
<div class="bg-muted flex h-[60vh] items-center justify-center rounded-md text-center text-sm text-muted-foreground"> <div
class="bg-muted flex h-[60vh] items-center justify-center rounded-md text-center text-sm text-muted-foreground"
>
<div> <div>
<Icon icon={FileIcon} cls="mx-auto h-10 w-10" /> <Icon icon={FileIcon} cls="mx-auto h-10 w-10" />
<p class="mt-2">Preview unavailable for this file type.</p> <p class="mt-2">
Preview unavailable for this file type.
</p>
</div> </div>
</div> </div>
{/if} {/if}
@@ -283,7 +418,12 @@
{#if selectedMedia.r2Url} {#if selectedMedia.r2Url}
<Button <Button
variant="outline" variant="outline"
onclick={() => window.open(selectedMedia?.r2Url, "_blank", "noopener,noreferrer")} onclick={() =>
window.open(
selectedMedia?.r2Url,
"_blank",
"noopener,noreferrer",
)}
> >
Open Raw File Open Raw File
</Button> </Button>

View File

@@ -11,6 +11,7 @@
import FileArchive from "@lucide/svelte/icons/file-archive"; import FileArchive from "@lucide/svelte/icons/file-archive";
import RefreshCw from "@lucide/svelte/icons/refresh-cw"; import RefreshCw from "@lucide/svelte/icons/refresh-cw";
import Search from "@lucide/svelte/icons/search"; import Search from "@lucide/svelte/icons/search";
import Trash2 from "@lucide/svelte/icons/trash-2";
import { onMount } from "svelte"; import { onMount } from "svelte";
const filesNavItem = mainNavTree.find((item) => item.url === "/files"); const filesNavItem = mainNavTree.find((item) => item.url === "/files");
@@ -78,6 +79,7 @@
<Table.Head>Status</Table.Head> <Table.Head>Status</Table.Head>
<Table.Head>Uploaded</Table.Head> <Table.Head>Uploaded</Table.Head>
<Table.Head>R2 URL</Table.Head> <Table.Head>R2 URL</Table.Head>
<Table.Head>Actions</Table.Head>
</Table.Row> </Table.Row>
</Table.Header> </Table.Header>
<Table.Body> <Table.Body>
@@ -105,6 +107,17 @@
Open Open
</a> </a>
</Table.Cell> </Table.Cell>
<Table.Cell>
<Button
variant="destructive"
size="sm"
disabled={filesVM.deletingFileId === item.id}
onclick={() => void filesVM.deleteFile(item.id)}
>
<Icon icon={Trash2} cls="h-4 w-4" />
Delete
</Button>
</Table.Cell>
</Table.Row> </Table.Row>
{/each} {/each}
</Table.Body> </Table.Body>

View File

@@ -10,7 +10,7 @@ import { FlowExecCtx } from "@core/flow.execution.context";
import { StorageRepository } from "./storage.repository"; import { StorageRepository } from "./storage.repository";
import { FileRepository } from "./repository"; import { FileRepository } from "./repository";
import { settings } from "@core/settings"; import { settings } from "@core/settings";
import { ResultAsync } from "neverthrow"; import { okAsync, ResultAsync } from "neverthrow";
import { traceResultAsync } from "@core/observability"; import { traceResultAsync } from "@core/observability";
import { db } from "@pkg/db"; import { db } from "@pkg/db";
@@ -198,6 +198,65 @@ export class FileController {
}); });
} }
deleteFile(fctx: FlowExecCtx, fileId: string, userId: string) {
return traceResultAsync({
name: "logic.files.controller.deleteFile",
fctx,
attributes: { "app.user.id": userId, "app.file.id": fileId },
fn: () => this.deleteFiles(fctx, [fileId], userId),
});
}
cleanupDanglingStorageFiles(fctx: FlowExecCtx, userId: string) {
return traceResultAsync({
name: "logic.files.controller.cleanupDanglingStorageFiles",
fctx,
attributes: { "app.user.id": userId },
fn: () =>
this.fileRepo
.listReferencedObjectKeysForUser(fctx, userId)
.andThen((referencedKeys) => {
const referencedSet = new Set(referencedKeys);
return ResultAsync.combine([
this.storageRepo.listObjectKeys(
fctx,
`uploads/${userId}/`,
),
this.storageRepo.listObjectKeys(
fctx,
`thumbnails/${userId}/`,
),
]).andThen(([uploadKeys, thumbnailKeys]) => {
const existingStorageKeys = [
...new Set([...uploadKeys, ...thumbnailKeys]),
];
const danglingKeys = existingStorageKeys.filter(
(key) => !referencedSet.has(key),
);
if (danglingKeys.length === 0) {
return okAsync({
scanned: existingStorageKeys.length,
referenced: referencedKeys.length,
dangling: 0,
deleted: 0,
});
}
return this.storageRepo
.deleteFiles(fctx, danglingKeys)
.map(() => ({
scanned: existingStorageKeys.length,
referenced: referencedKeys.length,
dangling: danglingKeys.length,
deleted: danglingKeys.length,
}));
});
}),
});
}
shareFile( shareFile(
fctx: FlowExecCtx, fctx: FlowExecCtx,
fileId: string, fileId: string,

View File

@@ -381,6 +381,47 @@ export class FileRepository {
}); });
} }
listReferencedObjectKeysForUser(
fctx: FlowExecCtx,
userId: string,
): ResultAsync<string[], Err> {
return ResultAsync.fromPromise(
this.db
.select({
objectKey: file.objectKey,
metadata: file.metadata,
})
.from(file)
.where(eq(file.userId, userId)),
(error) =>
fileErrors.getFilesFailed(
fctx,
error instanceof Error ? error.message : String(error),
),
).map((rows) => {
const keys = new Set<string>();
for (const row of rows) {
if (row.objectKey) {
keys.add(row.objectKey);
}
const thumbnailKey =
row.metadata &&
typeof row.metadata === "object" &&
"thumbnailKey" in row.metadata
? (row.metadata as Record<string, unknown>).thumbnailKey
: undefined;
if (typeof thumbnailKey === "string" && thumbnailKey.length > 0) {
keys.add(thumbnailKey);
}
}
return [...keys];
});
}
updateFileStatus( updateFileStatus(
fctx: FlowExecCtx, fctx: FlowExecCtx,
fileId: string, fileId: string,

View File

@@ -284,4 +284,55 @@ export class StorageRepository {
return true; return true;
}); });
} }
listObjectKeys(
fctx: FlowExecCtx,
prefix?: string,
): ResultAsync<string[], Err> {
const startedAt = Date.now();
logDomainEvent({
event: "files.storage.list.started",
fctx,
meta: { prefix: prefix || null },
});
return ResultAsync.fromPromise(
this.storageClient.listObjectKeys(prefix),
(error) => {
logDomainEvent({
level: "error",
event: "files.storage.list.failed",
fctx,
durationMs: Date.now() - startedAt,
error,
meta: { prefix: prefix || null },
});
return fileErrors.storageError(
fctx,
error instanceof Error ? error.message : String(error),
);
},
).andThen((result) => {
if (result.error) {
logDomainEvent({
level: "error",
event: "files.storage.list.failed",
fctx,
durationMs: Date.now() - startedAt,
error: result.error,
meta: { prefix: prefix || null, stage: "storage_response" },
});
return errAsync(fileErrors.storageError(fctx, String(result.error)));
}
const keys = result.data || [];
logDomainEvent({
event: "files.storage.list.succeeded",
fctx,
durationMs: Date.now() - startedAt,
meta: { prefix: prefix || null, count: keys.length },
});
return okAsync(keys);
});
}
} }

View File

@@ -3,6 +3,7 @@ import {
DeleteObjectCommand, DeleteObjectCommand,
GetObjectCommand, GetObjectCommand,
HeadObjectCommand, HeadObjectCommand,
ListObjectsV2Command,
PutObjectCommand, PutObjectCommand,
S3Client, S3Client,
} from "@aws-sdk/client-s3"; } from "@aws-sdk/client-s3";
@@ -481,4 +482,51 @@ export class R2StorageClient {
}; };
} }
} }
/**
* List object keys in R2 bucket, optionally filtered by prefix
*/
async listObjectKeys(prefix?: string): Promise<Result<string[]>> {
try {
const keys: string[] = [];
let continuationToken: string | undefined = undefined;
do {
const command = new ListObjectsV2Command({
Bucket: this.config.bucketName,
Prefix: prefix,
ContinuationToken: continuationToken,
});
const response = await this.s3Client.send(command);
const pageKeys =
response.Contents?.map((item) => item.Key).filter(
(key): key is string => Boolean(key),
) || [];
keys.push(...pageKeys);
continuationToken = response.IsTruncated
? response.NextContinuationToken
: undefined;
} while (continuationToken);
logger.info(
`Listed ${keys.length} objects${prefix ? ` with prefix ${prefix}` : ""}`,
);
return { data: keys };
} catch (error) {
logger.error("Failed to list object keys:", error);
return {
error: getError(
{
code: ERROR_CODES.STORAGE_ERROR,
message: "Failed to list objects",
description: "Could not list objects in storage",
detail: "S3 list operation failed",
},
error,
),
};
}
}
} }