feat: implement shared-album multi-user photo album

Backend (Go/Gin/pgx): env config, pgx pool with retries, Garage S3 client
(path-style, region garage), embedded golang-migrate migrations, JWT auth with
refresh rotation, albums CRUD, members/roles/invites with no-escalation matrix,
photo upload + async imaging/goexif WebP variants, cursor pagination, presigned
URLs, likes/comments, SSE hub (album + personal), notifications, share links.

Frontend (SvelteKit 2 + Svelte 5 + Tailwind v4): API wrapper with 401 refresh,
auth store, all screens, Uploader/PhotoGrid/Lightbox/Comments, SSE client with
reconnect + REST catch-up, three themes + system via data-theme.

Deploy without Docker: Makefile builds the frontend into backend/static and
embeds it (go:embed) into a single statically linked binary; systemd unit and
nginx SSE example included.

Use gen2brain/webp (-tags nodynamic) instead of cgo kolesa-team/go-webp to keep
CGO_ENABLED=0 static builds; design.md/proposal.md updated accordingly.
This commit is contained in:
iu
2026-10-10 12:50:33 +03:00
commit 2b2b342492
105 changed files with 12494 additions and 0 deletions
+101
View File
@@ -0,0 +1,101 @@
import { goto } from '$app/navigation';
import { auth, type Tokens, type User } from './stores/auth.svelte';
export class ApiError extends Error {
status: number;
code: string;
constructor(status: number, code: string, message: string) {
super(message);
this.status = status;
this.code = code;
}
}
interface RequestOptions {
method?: string;
body?: unknown;
form?: FormData;
}
let refreshing: Promise<boolean> | null = null;
async function raw(path: string, opts: RequestOptions): Promise<Response> {
const headers = new Headers();
if (auth.access) headers.set('Authorization', `Bearer ${auth.access}`);
let body: BodyInit | undefined;
if (opts.form) {
body = opts.form;
} else if (opts.body !== undefined) {
headers.set('Content-Type', 'application/json');
body = JSON.stringify(opts.body);
}
return fetch(`/api${path}`, { method: opts.method ?? 'GET', headers, body });
}
async function doRefresh(): Promise<boolean> {
if (!auth.refresh) return false;
try {
const res = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: auth.refresh })
});
if (!res.ok) return false;
const data = await res.json();
auth.setTokens(data.tokens as Tokens);
return true;
} catch {
return false;
}
}
export async function api<T = unknown>(path: string, opts: RequestOptions = {}): Promise<T> {
let res = await raw(path, opts);
if (res.status === 401 && auth.refresh) {
if (!refreshing) {
refreshing = doRefresh().finally(() => {
refreshing = null;
});
}
const ok = await refreshing;
if (ok) res = await raw(path, opts);
}
if (!res.ok) {
let code = 'error';
let message = res.statusText;
try {
const body = await res.json();
if (body?.error) {
code = body.error.code ?? code;
message = body.error.message ?? message;
}
} catch {
/* ignore */
}
if (res.status === 401) {
auth.clear();
goto('/login');
}
throw new ApiError(res.status, code, message);
}
if (res.status === 204) return null as T;
const ct = res.headers.get('content-type') ?? '';
if (ct.includes('application/json')) return (await res.json()) as T;
return (await res.text()) as unknown as T;
}
export const authApi = {
register: (email: string, password: string, name: string) =>
api<{ user: User; tokens: Tokens }>('/auth/register', {
method: 'POST',
body: { email, password, name }
}),
login: (email: string, password: string) =>
api<{ user: User; tokens: Tokens }>('/auth/login', {
method: 'POST',
body: { email, password }
}),
logout: (refresh_token: string) =>
api('/auth/logout', { method: 'POST', body: { refresh_token } }),
me: () => api<{ user: User }>('/auth/me')
};
@@ -0,0 +1,86 @@
<script lang="ts">
import { api } from '$lib/api';
import { auth } from '$lib/stores/auth.svelte';
import type { Comment } from '$lib/types';
interface Props {
photoId: string;
}
let { photoId }: Props = $props();
let comments = $state<Comment[]>([]);
let text = $state('');
let error = $state('');
async function load() {
try {
const data = await api<{ comments: Comment[] }>(`/photos/${photoId}/comments`);
comments = data.comments;
} catch (e) {
error = (e as Error).message;
}
}
$effect(() => {
photoId;
load();
});
async function submit(ev: Event) {
ev.preventDefault();
if (!text.trim()) return;
try {
const data = await api<{ comment: Comment }>(`/photos/${photoId}/comments`, {
method: 'POST',
body: { text }
});
comments = [...comments, data.comment];
text = '';
} catch (e) {
error = (e as Error).message;
}
}
async function remove(id: string) {
try {
await api(`/comments/${id}`, { method: 'DELETE' });
comments = comments.filter((c) => c.id !== id);
} catch (e) {
error = (e as Error).message;
}
}
</script>
<div class="mt-2">
{#each comments as comment (comment.id)}
<div class="border-border mb-1 flex items-start justify-between gap-2 border-b py-1 text-sm">
<span class="text-text">
<strong>{comment.user.name}</strong>: {comment.text}
</span>
{#if auth.user?.id === comment.user_id}
<button
type="button"
class="text-text-subtle hover:text-danger text-xs"
onclick={() => remove(comment.id)}>удалить</button
>
{/if}
</div>
{/each}
{#if auth.isAuthenticated}
<form class="mt-2 flex gap-2" onsubmit={submit}>
<input
bind:value={text}
placeholder="Комментарий…"
class="border-border bg-bg text-text flex-1 rounded-lg border px-3 py-1.5 text-sm"
/>
<button class="bg-primary text-primary-fg rounded-lg px-3 py-1.5 text-sm" type="submit"
>Отправить</button
>
</form>
{/if}
{#if error}
<p class="text-danger mt-1 text-xs">{error}</p>
{/if}
</div>
+110
View File
@@ -0,0 +1,110 @@
<script lang="ts">
import { api } from '$lib/api';
import type { Photo } from '$lib/types';
import Comments from './Comments.svelte';
interface Props {
photos: Photo[];
index: number;
onClose: () => void;
onIndexChange: (index: number) => void;
}
let { photos, index, onClose, onIndexChange }: Props = $props();
let fresh = $state<Photo | null>(null);
let touchX = 0;
const current = $derived(photos[index]);
$effect(() => {
const id = current?.id;
fresh = null;
if (!id) return;
api<{ photo: Photo }>(`/photos/${id}`)
.then((data) => (fresh = data.photo))
.catch(() => {});
});
function prev() {
if (index > 0) onIndexChange(index - 1);
}
function next() {
if (index < photos.length - 1) onIndexChange(index + 1);
}
function onKey(ev: KeyboardEvent) {
if (ev.key === 'Escape') onClose();
if (ev.key === 'ArrowLeft') prev();
if (ev.key === 'ArrowRight') next();
}
function onTouchStart(ev: TouchEvent) {
touchX = ev.changedTouches[0].clientX;
}
function onTouchEnd(ev: TouchEvent) {
const dx = ev.changedTouches[0].clientX - touchX;
if (dx > 50) prev();
else if (dx < -50) next();
}
</script>
<svelte:window onkeydown={onKey} />
<div
class="bg-bg/95 fixed inset-0 z-50 flex flex-col"
role="dialog"
aria-modal="true"
onclick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
ontouchstart={onTouchStart}
ontouchend={onTouchEnd}
>
<div class="flex items-center justify-between p-3">
<span class="text-text-muted text-sm">{index + 1} / {photos.length}</span>
<div class="flex gap-2">
{#if fresh?.download_url}
<a
href={fresh.download_url}
class="border-border text-text rounded-lg border px-3 py-1.5 text-sm"
target="_blank"
rel="noreferrer">Скачать</a
>
{/if}
<button
type="button"
onclick={onClose}
class="border-border text-text rounded-lg border px-3 py-1.5 text-sm">✕</button
>
</div>
</div>
<div class="flex flex-1 items-center justify-center overflow-hidden px-2 pb-2">
<button type="button" class="text-text-muted px-2 text-3xl" onclick={prev} disabled={index === 0}
>‹</button
>
{#if current}
<img
src={fresh?.preview_url ?? fresh?.original_url ?? current.preview_url ?? current.original_url}
alt={current.original_filename}
class="max-h-[75vh] max-w-full rounded-lg object-contain"
/>
{/if}
<button
type="button"
class="text-text-muted px-2 text-3xl"
onclick={next}
disabled={index === photos.length - 1}>›</button
>
</div>
{#if current}
<div class="border-border bg-bg-elevated max-h-56 overflow-y-auto border-t p-3">
<p class="text-text text-sm">
{current.uploader.name} · {current.original_filename}
</p>
<Comments photoId={current.id} />
</div>
{/if}
</div>
@@ -0,0 +1,45 @@
<script lang="ts">
import type { Photo } from '$lib/types';
interface Props {
photos: Photo[];
onOpen?: (index: number) => void;
}
let { photos, onOpen }: Props = $props();
</script>
{#if photos.length === 0}
<p class="text-text-muted p-8 text-center">Пока нет фотографий.</p>
{:else}
<ul class="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{#each photos as photo, i (photo.id)}
<li>
<button
type="button"
class="border-border bg-bg-muted group relative block aspect-square w-full overflow-hidden rounded-lg border"
onclick={() => onOpen?.(i)}
>
{#if photo.thumb_url}
<img
src={photo.thumb_url}
alt={photo.original_filename}
loading="lazy"
decoding="async"
class="h-full w-full object-cover transition-transform duration-200 group-hover:scale-105"
/>
{:else}
<span class="text-text-subtle flex h-full w-full items-center justify-center text-xs">
обработка…
</span>
{/if}
<span
class="bg-bg/70 text-text absolute right-1 bottom-1 rounded px-1.5 py-0.5 text-xs"
>
♥ {photo.likes_count} · 💬 {photo.comments_count}
</span>
</button>
</li>
{/each}
</ul>
{/if}
@@ -0,0 +1,27 @@
<script lang="ts">
import { theme, type Theme } from '$lib/stores/theme.svelte';
const options: { value: Theme; label: string; icon: string }[] = [
{ value: 'light', label: 'Light', icon: '☀️' },
{ value: 'dark', label: 'Dark', icon: '🌙' },
{ value: 'neutral', label: 'Neutral', icon: '🌾' },
{ value: 'system', label: 'System', icon: '💻' }
];
</script>
<div class="border-border bg-bg-elevated inline-flex gap-1 rounded-lg border p-1" role="group" aria-label="Theme">
{#each options as option (option.value)}
<button
type="button"
title={option.label}
aria-label={option.label}
aria-pressed={theme.current === option.value}
onclick={() => theme.set(option.value)}
class="rounded-md px-2 py-1 text-sm transition-colors {theme.current === option.value
? 'bg-primary text-primary-fg'
: 'text-text-muted hover:bg-bg-muted'}"
>
{option.icon}
</button>
{/each}
</div>
+117
View File
@@ -0,0 +1,117 @@
<script lang="ts">
import { auth } from '$lib/stores/auth.svelte';
import type { Photo } from '$lib/types';
interface Props {
albumId: string;
onUploaded?: (photos: Photo[]) => void;
}
let { albumId, onUploaded }: Props = $props();
let dragging = $state(false);
let progress = $state(0);
let busy = $state(false);
let error = $state('');
function pick() {
fileInput?.click();
}
let fileInput: HTMLInputElement | undefined = $state();
function onDrop(ev: DragEvent) {
ev.preventDefault();
dragging = false;
if (ev.dataTransfer?.files?.length) {
upload(ev.dataTransfer.files);
}
}
function onChange(ev: Event) {
const target = ev.target as HTMLInputElement;
if (target.files?.length) upload(target.files);
target.value = '';
}
function upload(files: FileList) {
error = '';
busy = true;
progress = 0;
const form = new FormData();
for (const file of Array.from(files)) {
form.append('files', file);
}
const xhr = new XMLHttpRequest();
xhr.open('POST', `/api/albums/${albumId}/photos`);
if (auth.access) xhr.setRequestHeader('Authorization', `Bearer ${auth.access}`);
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) progress = Math.round((e.loaded / e.total) * 100);
};
xhr.onload = () => {
busy = false;
if (xhr.status >= 200 && xhr.status < 300) {
try {
const data = JSON.parse(xhr.responseText);
onUploaded?.(data.photos ?? []);
} catch {
onUploaded?.([]);
}
} else {
try {
error = JSON.parse(xhr.responseText)?.error?.message ?? 'Ошибка загрузки';
} catch {
error = 'Ошибка загрузки';
}
}
};
xhr.onerror = () => {
busy = false;
error = 'Сетевая ошибка';
};
xhr.send(form);
}
</script>
<div
class="border-border rounded-xl border-2 border-dashed p-6 text-center transition-colors {dragging
? 'bg-bg-muted border-primary'
: 'bg-bg-elevated'}"
ondragover={(e) => {
e.preventDefault();
dragging = true;
}}
ondragleave={() => (dragging = false)}
ondrop={onDrop}
ondragenter={(e) => e.preventDefault()}
role="region"
aria-label="Загрузка фотографий"
>
<input
bind:this={fileInput}
type="file"
accept="image/*"
multiple
class="hidden"
onchange={onChange}
/>
<p class="text-text mb-3 text-sm">Перетащите фото сюда или</p>
<button
type="button"
onclick={pick}
disabled={busy}
class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm font-medium disabled:opacity-50"
>
{busy ? 'Загрузка…' : 'Выбрать файлы'}
</button>
{#if busy}
<div class="bg-bg-muted mt-4 h-2 w-full overflow-hidden rounded">
<div class="bg-primary h-full transition-all" style="width: {progress}%"></div>
</div>
{/if}
{#if error}
<p class="text-danger mt-3 text-sm">{error}</p>
{/if}
</div>
+77
View File
@@ -0,0 +1,77 @@
export interface SSEEvent {
type: string;
data: unknown;
}
export interface SSEClientOptions {
path: string;
onEvent: (event: SSEEvent) => void;
onReconnect?: () => void;
}
// Wrapper над EventSource с экспоненциальным backoff и догоном через REST.
export class SSEClient {
private es: EventSource | null = null;
private stopped = false;
private attempt = 0;
private readonly knownEvents = [
'photo.created',
'photo.deleted',
'comment.created',
'like.added',
'like.removed',
'member.joined',
'member.left',
'member.updated',
'album.updated',
'album.deleted',
'notification'
];
constructor(private opts: SSEClientOptions) {}
connect(token: string) {
this.stopped = false;
this.open(token);
}
private open(token: string) {
if (this.stopped) return;
const url = `${this.opts.path}?token=${encodeURIComponent(token)}`;
this.es = new EventSource(url);
this.es.onopen = () => {
if (this.attempt > 0) {
this.opts.onReconnect?.();
}
this.attempt = 0;
};
for (const name of this.knownEvents) {
this.es.addEventListener(name, (ev) => {
let data: unknown = null;
try {
data = JSON.parse((ev as MessageEvent).data);
} catch {
data = (ev as MessageEvent).data;
}
this.opts.onEvent({ type: name, data });
});
}
this.es.onerror = () => {
this.es?.close();
this.es = null;
if (this.stopped) return;
const delay = Math.min(1000 * 2 ** this.attempt, 30000);
this.attempt += 1;
setTimeout(() => this.open(token), delay);
};
}
close() {
this.stopped = true;
this.es?.close();
this.es = null;
}
}
+71
View File
@@ -0,0 +1,71 @@
export interface User {
id: string;
email: string;
name: string;
avatar_url?: string;
}
export interface Tokens {
access_token: string;
refresh_token: string;
token_type: string;
expires_in: number;
}
const ACCESS_KEY = 'galo.access';
const REFRESH_KEY = 'galo.refresh';
const USER_KEY = 'galo.user';
class AuthStore {
access = $state<string | null>(null);
refresh = $state<string | null>(null);
user = $state<User | null>(null);
constructor() {
if (typeof localStorage !== 'undefined') {
this.access = localStorage.getItem(ACCESS_KEY);
this.refresh = localStorage.getItem(REFRESH_KEY);
const raw = localStorage.getItem(USER_KEY);
if (raw) {
try {
this.user = JSON.parse(raw);
} catch {
this.user = null;
}
}
}
}
get isAuthenticated(): boolean {
return !!this.access;
}
setTokens(tokens: Tokens) {
this.access = tokens.access_token;
this.refresh = tokens.refresh_token;
if (typeof localStorage !== 'undefined') {
localStorage.setItem(ACCESS_KEY, tokens.access_token);
localStorage.setItem(REFRESH_KEY, tokens.refresh_token);
}
}
setUser(user: User) {
this.user = user;
if (typeof localStorage !== 'undefined') {
localStorage.setItem(USER_KEY, JSON.stringify(user));
}
}
clear() {
this.access = null;
this.refresh = null;
this.user = null;
if (typeof localStorage !== 'undefined') {
localStorage.removeItem(ACCESS_KEY);
localStorage.removeItem(REFRESH_KEY);
localStorage.removeItem(USER_KEY);
}
}
}
export const auth = new AuthStore();
+44
View File
@@ -0,0 +1,44 @@
export type Theme = 'light' | 'dark' | 'neutral' | 'system';
type Resolved = 'light' | 'dark' | 'neutral';
const KEY = 'theme';
function resolve(theme: Theme): Resolved {
if (theme === 'system') {
if (typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
return 'light';
}
return theme;
}
class ThemeStore {
current = $state<Theme>('system');
resolved = $state<Resolved>('light');
private media: MediaQueryList | null = null;
init() {
if (typeof window === 'undefined') return;
const stored = (localStorage.getItem(KEY) as Theme | null) ?? 'system';
this.current = stored;
this.apply();
this.media = window.matchMedia('(prefers-color-scheme: dark)');
this.media.addEventListener('change', () => {
if (this.current === 'system') this.apply();
});
}
set(theme: Theme) {
this.current = theme;
localStorage.setItem(KEY, theme);
this.apply();
}
private apply() {
this.resolved = resolve(this.current);
document.documentElement.setAttribute('data-theme', this.resolved);
}
}
export const theme = new ThemeStore();
+88
View File
@@ -0,0 +1,88 @@
export interface User {
id: string;
email?: string;
name: string;
avatar_url?: string;
}
export interface Album {
id: string;
owner_id: string;
title: string;
description: string;
cover_photo_id?: string | null;
created_at: string;
updated_at: string;
}
export interface AlbumMember {
album_id: string;
user_id: string;
role: string;
joined_at: string;
user: User;
}
export interface Photo {
id: string;
album_id: string;
uploader_id: string;
original_filename: string;
size: number;
width: number;
height: number;
mime_type: string;
taken_at?: string | null;
latitude?: number | null;
longitude?: number | null;
caption: string;
created_at: string;
uploader: User;
likes_count: number;
comments_count: number;
liked_by_me: boolean;
thumb_url?: string;
preview_url?: string;
original_url?: string;
download_url?: string;
}
export interface Comment {
id: string;
photo_id: string;
user_id: string;
text: string;
created_at: string;
updated_at: string;
user: User;
}
export interface Invite {
id: string;
album_id: string;
token: string;
role: string;
expires_at: string;
max_uses: number;
uses: number;
created_at: string;
}
export interface ShareLink {
id: string;
album_id: string;
token: string;
created_by: string;
created_at: string;
expires_at: string;
revoked_at?: string | null;
}
export interface Notification {
id: string;
user_id: string;
type: string;
payload: Record<string, unknown>;
read_at?: string | null;
created_at: string;
}