feat: avatar upload via presigned PUT URL flow
Some checks failed
CI / Scraper / Lint (push) Successful in 11s
CI / Scraper / Lint (pull_request) Successful in 9s
CI / Scraper / Test (push) Successful in 19s
CI / UI / Build (push) Successful in 21s
CI / Scraper / Test (pull_request) Successful in 9s
CI / UI / Build (pull_request) Successful in 27s
CI / Scraper / Docker Push (pull_request) Has been skipped
CI / Scraper / Docker Push (push) Successful in 47s
CI / UI / Docker Push (pull_request) Has been skipped
Release / UI / Build (push) Successful in 21s
Release / UI / Docker (push) Successful in 5m1s
iOS CI / Test (push) Has been cancelled
iOS CI / Build (push) Has been cancelled
CI / UI / Docker Push (push) Failing after 9m10s
iOS CI / Build (pull_request) Failing after 4m3s
iOS CI / Test (pull_request) Has been skipped

- Go scraper: add PresignAvatarUploadURL/PresignAvatarURL/DeleteAvatar to
  Store interface, implement on HybridStore+MinioClient, register
  GET /api/presign/avatar-upload/{userId} and /api/presign/avatar/{userId}
- SvelteKit: replace direct AWS S3 SDK in minio.ts with presign calls to
  the Go scraper; rewrite avatar +server.ts (POST=presign, PATCH=record key)
- iOS: rewrite uploadAvatar() as 3-step presigned PUT flow; refactor
  chip components into shared ChipButton in CommonViews.swift
This commit is contained in:
Admin
2026-03-10 17:05:43 +05:00
parent 72eed89f59
commit 52f876d8e8
18 changed files with 302 additions and 234 deletions

View File

@@ -9,40 +9,15 @@
import { env } from '$env/dynamic/private';
import { env as pubEnv } from '$env/dynamic/public';
import { log } from '$lib/server/logger';
import { S3Client, PutObjectCommand, DeleteObjectCommand, HeadObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const SCRAPER_URL = env.SCRAPER_API_URL ?? 'http://localhost:8080';
// Public MinIO URL — used to rewrite presigned URLs so the browser can reach MinIO directly.
// In docker-compose this would differ from the internal endpoint.
const MINIO_PUBLIC_URL = pubEnv.PUBLIC_MINIO_PUBLIC_URL ?? 'http://localhost:9000';
// MinIO direct client (for avatar uploads — not routed through Go scraper)
const MINIO_ENDPOINT = env.MINIO_ENDPOINT ?? 'localhost:9000';
const MINIO_ACCESS_KEY = env.MINIO_ACCESS_KEY ?? 'admin';
const MINIO_SECRET_KEY = env.MINIO_SECRET_KEY ?? 'changeme123';
const MINIO_USE_SSL = (env.MINIO_USE_SSL ?? 'false').toLowerCase() === 'true';
const BUCKET_AVATARS = env.MINIO_BUCKET_AVATARS ?? 'libnovel-avatars';
function makeS3Client(): S3Client {
return new S3Client({
endpoint: `${MINIO_USE_SSL ? 'https' : 'http'}://${MINIO_ENDPOINT}`,
region: 'us-east-1', // MinIO ignores region but SDK requires one
credentials: { accessKeyId: MINIO_ACCESS_KEY, secretAccessKey: MINIO_SECRET_KEY },
forcePathStyle: true // MinIO requires path-style URLs
});
}
// ─── Avatar helpers ───────────────────────────────────────────────────────────
const AVATAR_EXTS = ['jpg', 'png', 'webp', 'gif'] as const;
type AvatarExt = (typeof AVATAR_EXTS)[number];
function avatarKey(userId: string, ext: AvatarExt): string {
return `avatars/${userId}.${ext}`;
}
function extFromMime(mime: string): AvatarExt {
function extFromMime(mime: string): string {
if (mime.includes('png')) return 'png';
if (mime.includes('webp')) return 'webp';
if (mime.includes('gif')) return 'gif';
@@ -50,32 +25,19 @@ function extFromMime(mime: string): AvatarExt {
}
/**
* Upload an avatar image buffer to MinIO.
* Deletes any existing avatar for this user first, then stores the new one.
* Returns the MinIO object key (e.g. "avatars/abc123.jpg").
* Returns a short-lived presigned PUT URL for uploading an avatar directly to MinIO,
* along with the object key to record in PocketBase after upload completes.
* Routed through the Go scraper which holds MinIO credentials.
*/
export async function putAvatar(userId: string, data: Uint8Array, mimeType: string): Promise<string> {
export async function presignAvatarUploadUrl(userId: string, mimeType: string): Promise<{ uploadUrl: string; key: string }> {
const ext = extFromMime(mimeType);
const s3 = makeS3Client();
// Delete old avatars (all extensions) to avoid stale objects
await Promise.all(
AVATAR_EXTS.map((e) =>
s3.send(new DeleteObjectCommand({ Bucket: BUCKET_AVATARS, Key: avatarKey(userId, e) })).catch(() => {})
)
);
const key = avatarKey(userId, ext);
await s3.send(
new PutObjectCommand({
Bucket: BUCKET_AVATARS,
Key: key,
Body: data,
ContentType: mimeType
})
);
log.info('minio', 'avatar uploaded', { userId, key });
return key;
const res = await fetch(`${SCRAPER_URL}/api/presign/avatar-upload/${encodeURIComponent(userId)}?ext=${ext}`);
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`presign avatar upload failed: ${res.status} ${body}`);
}
const data = (await res.json()) as { upload_url: string; key: string };
return { uploadUrl: data.upload_url, key: data.key };
}
/**
@@ -83,25 +45,14 @@ export async function putAvatar(userId: string, data: Uint8Array, mimeType: stri
* Returns null if no avatar exists.
*/
export async function presignAvatarUrl(userId: string): Promise<string | null> {
const s3 = makeS3Client();
for (const ext of AVATAR_EXTS) {
const key = avatarKey(userId, ext);
try {
await s3.send(new HeadObjectCommand({ Bucket: BUCKET_AVATARS, Key: key }));
// Object exists — generate presigned URL using public endpoint
const pubS3 = new S3Client({
endpoint: MINIO_PUBLIC_URL,
region: 'us-east-1',
credentials: { accessKeyId: MINIO_ACCESS_KEY, secretAccessKey: MINIO_SECRET_KEY },
forcePathStyle: true
});
const url = await getSignedUrl(pubS3, new GetObjectCommand({ Bucket: BUCKET_AVATARS, Key: key }), { expiresIn: 86400 });
return url;
} catch {
// not found or error — try next extension
}
const res = await fetch(`${SCRAPER_URL}/api/presign/avatar/${encodeURIComponent(userId)}`);
if (res.status === 404) return null;
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`presign avatar failed: ${res.status} ${body}`);
}
return null;
const data = (await res.json()) as { url: string };
return data.url ?? null;
}
/**

View File

@@ -801,9 +801,13 @@ export async function revokeAllUserSessions(userId: string): Promise<void> {
*/
export async function updateUserAvatarUrl(userId: string, avatarUrl: string): Promise<void> {
const token = await getToken();
await fetch(`${PB_URL}/api/collections/app_users/records/${userId}`, {
const res = await fetch(`${PB_URL}/api/collections/app_users/records/${userId}`, {
method: 'PATCH',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ avatar_url: avatarUrl })
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`updateUserAvatarUrl failed: ${res.status} ${body}`);
}
}