fix and update

This commit is contained in:
lendry
2026-07-07 10:14:37 +03:00
parent 29306eb2ec
commit bd6cd0d798
22 changed files with 1544 additions and 53 deletions

View File

@@ -0,0 +1,319 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Download, Loader2, Monitor, Smartphone, Trash2, Upload } from 'lucide-react';
import { useAuth } from '@/components/id/auth-provider';
import { AdminShell } from '@/components/id/admin-shell';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
AppRelease,
AppReleasePlatform,
deleteAdminAppRelease,
fetchAdminAppReleases,
getApiErrorMessage,
updateAdminAppRelease,
uploadAdminAppRelease
} from '@/lib/api';
import { cn } from '@/lib/utils';
function formatBytes(value: string) {
const size = Number(value);
if (!Number.isFinite(size) || size <= 0) return '—';
const units = ['Б', 'КБ', 'МБ', 'ГБ'];
let amount = size;
let unit = 0;
while (amount >= 1024 && unit < units.length - 1) {
amount /= 1024;
unit += 1;
}
return `${amount.toFixed(amount >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`;
}
function formatDate(value: string) {
return new Intl.DateTimeFormat('ru-RU', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(new Date(value));
}
const platformMeta: Record<AppReleasePlatform, { label: string; icon: typeof Smartphone; accept: string }> = {
ANDROID: { label: 'Android', icon: Smartphone, accept: '.apk,application/vnd.android.package-archive' },
WINDOWS: { label: 'Windows', icon: Monitor, accept: '.exe,application/vnd.microsoft.portable-executable' }
};
export default function AdminReleasesPage() {
const { token, user } = useAuth();
const { showToast } = useToast();
const [releases, setReleases] = useState<AppRelease[]>([]);
const [loading, setLoading] = useState(true);
const [uploading, setUploading] = useState(false);
const [platform, setPlatform] = useState<AppReleasePlatform>('ANDROID');
const [version, setVersion] = useState('');
const [versionCode, setVersionCode] = useState('');
const [releaseNotes, setReleaseNotes] = useState('');
const [file, setFile] = useState<File | null>(null);
const canManage = Boolean(user?.canManageSettings);
const loadReleases = useCallback(async () => {
if (!token || !canManage) return;
setLoading(true);
try {
const response = await fetchAdminAppReleases(token);
setReleases(response.releases ?? []);
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось загрузить релизы') ?? 'Ошибка');
} finally {
setLoading(false);
}
}, [canManage, showToast, token]);
useEffect(() => {
void loadReleases();
}, [loadReleases]);
const grouped = useMemo(() => {
const android = releases.filter((item) => item.platform === 'ANDROID');
const windows = releases.filter((item) => item.platform === 'WINDOWS');
return { android, windows };
}, [releases]);
async function handleUpload(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!token || !file) {
showToast('Выберите файл релиза');
return;
}
const parsedVersionCode = Number(versionCode);
if (!version.trim() || !Number.isInteger(parsedVersionCode) || parsedVersionCode < 1) {
showToast('Укажите версию и положительный код версии');
return;
}
setUploading(true);
try {
const created = await uploadAdminAppRelease(token, {
platform,
version: version.trim(),
versionCode: parsedVersionCode,
releaseNotes: releaseNotes.trim() || undefined,
file
});
setReleases((current) => [created, ...current]);
setVersion('');
setVersionCode('');
setReleaseNotes('');
setFile(null);
showToast('Релиз загружен и опубликован');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось загрузить релиз') ?? 'Ошибка');
} finally {
setUploading(false);
}
}
async function togglePublished(release: AppRelease) {
if (!token) return;
try {
const updated = await updateAdminAppRelease(token, release.id, { isPublished: !release.isPublished });
setReleases((current) => current.map((item) => (item.id === release.id ? updated : item)));
showToast(updated.isPublished ? 'Релиз опубликован' : 'Релиз скрыт');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось обновить релиз') ?? 'Ошибка');
}
}
async function removeRelease(release: AppRelease) {
if (!token) return;
if (!window.confirm(`Удалить версию ${release.version} (${platformMeta[release.platform].label})?`)) return;
try {
await deleteAdminAppRelease(token, release.id);
setReleases((current) => current.filter((item) => item.id !== release.id));
showToast('Релиз удалён');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось удалить релиз') ?? 'Ошибка');
}
}
function renderReleaseList(items: AppRelease[], emptyLabel: string) {
if (loading) {
return <div className="rounded-[20px] bg-[#f4f5f8] px-4 py-5 text-[#667085]">Загружаем релизы...</div>;
}
if (!items.length) {
return <div className="rounded-[20px] bg-[#f4f5f8] px-4 py-5 text-[#667085]">{emptyLabel}</div>;
}
return (
<div className="space-y-3">
{items.map((release, index) => {
const Icon = platformMeta[release.platform].icon;
const isLatest = index === 0 && release.isPublished;
return (
<div key={release.id} className="rounded-[20px] border border-[#eceef4] bg-white p-4 shadow-sm">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex min-w-0 items-start gap-3">
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl bg-[#f4f5f8]">
<Icon className="h-5 w-5 text-[#3390ec]" />
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-lg font-semibold">v{release.version}</h3>
<span className="rounded-full bg-[#eef4ff] px-2 py-0.5 text-xs font-medium text-[#3390ec]">
build {release.versionCode}
</span>
{isLatest ? (
<span className="rounded-full bg-[#e8f8ee] px-2 py-0.5 text-xs font-medium text-[#1a7f37]">
Последняя
</span>
) : null}
{!release.isPublished ? (
<span className="rounded-full bg-[#fff4e5] px-2 py-0.5 text-xs font-medium text-[#b54708]">
Скрыта
</span>
) : null}
</div>
<p className="mt-1 text-sm text-[#667085]">
{release.fileName} · {formatBytes(release.fileSize)} · {formatDate(release.createdAt)}
</p>
<p className="mt-1 break-all font-mono text-xs text-[#8f92a0]">SHA-256: {release.sha256}</p>
{release.releaseNotes ? (
<p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed text-[#1f2430]">{release.releaseNotes}</p>
) : null}
</div>
</div>
<div className="flex shrink-0 flex-wrap gap-2">
<Button variant="outline" size="sm" className="rounded-xl" asChild>
<a href={`/downloads/${release.platform === 'ANDROID' ? 'android' : 'windows'}`} target="_blank" rel="noreferrer">
<Download className="mr-2 h-4 w-4" />
Скачать
</a>
</Button>
<Button variant="outline" size="sm" className="rounded-xl" onClick={() => void togglePublished(release)}>
{release.isPublished ? 'Скрыть' : 'Опубликовать'}
</Button>
<Button
variant="ghost"
size="sm"
className="rounded-xl text-red-600 hover:bg-red-50 hover:text-red-700"
onClick={() => void removeRelease(release)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</div>
);
})}
</div>
);
}
if (!canManage) {
return (
<AdminShell active="/admin/releases">
<div className="rounded-[20px] bg-[#f4f5f8] px-4 py-6 text-[#667085]">Недостаточно прав для управления релизами.</div>
</AdminShell>
);
}
const PlatformIcon = platformMeta[platform].icon;
return (
<AdminShell active="/admin/releases">
<div className="grid gap-8 xl:grid-cols-[380px_minmax(0,1fr)]">
<section className="rounded-[24px] border border-[#eceef4] bg-white p-6 shadow-sm">
<div className="mb-5 flex items-center gap-3">
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[#eef4ff] text-[#3390ec]">
<Upload className="h-6 w-6" />
</div>
<div>
<h2 className="text-xl font-semibold">Новая версия</h2>
<p className="text-sm text-[#667085]">Загрузите APK или EXE с подписью SHA-256</p>
</div>
</div>
<form className="space-y-4" onSubmit={(event) => void handleUpload(event)}>
<div className="grid grid-cols-2 gap-2">
{(['ANDROID', 'WINDOWS'] as AppReleasePlatform[]).map((item) => {
const meta = platformMeta[item];
const Icon = meta.icon;
return (
<button
key={item}
type="button"
className={cn(
'flex items-center justify-center gap-2 rounded-2xl border px-3 py-3 text-sm font-medium transition',
platform === item
? 'border-[#3390ec] bg-[#eef4ff] text-[#1f2430]'
: 'border-[#eceef4] bg-[#f8f9fb] text-[#667085] hover:bg-[#f1f2f6]'
)}
onClick={() => setPlatform(item)}
>
<Icon className="h-4 w-4" />
{meta.label}
</button>
);
})}
</div>
<Input
placeholder="Версия, например 1.2.0"
value={version}
onChange={(event) => setVersion(event.target.value)}
required
/>
<Input
type="number"
min={1}
placeholder="Код версии (versionCode), например 120"
value={versionCode}
onChange={(event) => setVersionCode(event.target.value)}
required
/>
<textarea
className="min-h-[110px] w-full rounded-2xl border border-[#eceef4] bg-[#f8f9fb] px-4 py-3 text-sm outline-none transition focus:border-[#3390ec]"
placeholder="Что нового в этой версии"
value={releaseNotes}
onChange={(event) => setReleaseNotes(event.target.value)}
/>
<label className="flex cursor-pointer flex-col items-center justify-center rounded-[20px] border border-dashed border-[#c7d2fe] bg-[#f8faff] px-4 py-8 text-center transition hover:bg-[#eef4ff]">
<PlatformIcon className="mb-3 h-8 w-8 text-[#3390ec]" />
<span className="text-sm font-medium text-[#1f2430]">
{file ? file.name : `Выберите файл ${platform === 'ANDROID' ? '.apk' : '.exe'}`}
</span>
<span className="mt-1 text-xs text-[#667085]">До 350 МБ</span>
<input
type="file"
className="hidden"
accept={platformMeta[platform].accept}
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
/>
</label>
<Button type="submit" className="w-full rounded-xl" disabled={uploading || !file}>
{uploading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Upload className="mr-2 h-4 w-4" />}
{uploading ? 'Загружаем...' : 'Загрузить релиз'}
</Button>
</form>
</section>
<div className="space-y-8">
<section>
<h2 className="mb-4 text-xl font-semibold">Android</h2>
{renderReleaseList(grouped.android, 'Релизы Android пока не загружены')}
</section>
<section>
<h2 className="mb-4 text-xl font-semibold">Windows</h2>
{renderReleaseList(grouped.windows, 'Релизы Windows пока не загружены')}
</section>
</div>
</div>
</AdminShell>
);
}

View File

@@ -1521,7 +1521,7 @@ function LoginPageContent() {
<ProjectTagline className="mt-9 text-center text-sm font-semibold" />
<a
href="/download/android"
href="/downloads/android"
className="mx-auto mt-3 flex w-fit items-center gap-1 rounded-full px-3 py-1.5 text-xs font-medium text-[#b9bdc9] transition hover:bg-white/10 hover:text-white"
>
<Download className="h-3.5 w-3.5" />

View File

@@ -1,49 +1,8 @@
import { createReadStream, existsSync, statSync } from 'node:fs';
import path from 'node:path';
import { Readable } from 'node:stream';
import { NextRequest, NextResponse } from 'next/server';
export const runtime = 'nodejs';
const APK_CANDIDATES = [
process.env.TAURI_ANDROID_APK_PATH,
path.resolve(process.cwd(), 'public/downloads/lendry-id.apk'),
path.resolve(process.cwd(), 'apps/frontend/public/downloads/lendry-id.apk'),
'/app/apps/frontend/public/downloads/lendry-id.apk',
'/app/public/downloads/lendry-id.apk',
path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk'),
path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/universal/debug/app-universal-debug.apk'),
path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/arm64/release/app-arm64-release.apk'),
path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/arm64/debug/app-arm64-debug.apk')
].filter((candidate): candidate is string => Boolean(candidate));
function resolveApkPath() {
return APK_CANDIDATES.find((candidate) => existsSync(candidate) && statSync(candidate).isFile());
}
export async function GET() {
const apkPath = resolveApkPath();
if (!apkPath) {
return new Response(
'APK ещё не собран. Запустите: ./install.sh --build-apk (или пункт 12 в меню). После сборки файл появится как apps/frontend/public/downloads/lendry-id.apk.',
{
status: 404,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-store'
}
},
);
}
const stat = statSync(apkPath);
const stream = Readable.toWeb(createReadStream(apkPath)) as ReadableStream;
return new Response(stream, {
headers: {
'Content-Type': 'application/vnd.android.package-archive',
'Content-Length': String(stat.size),
'Content-Disposition': 'attachment; filename="lendry-id.apk"',
'Cache-Control': 'no-store'
}
});
export async function GET(request: NextRequest) {
const target = new URL('/downloads/android', request.nextUrl.origin);
return NextResponse.redirect(target, 302);
}

View File

@@ -0,0 +1,15 @@
import { NextRequest, NextResponse } from 'next/server';
export const runtime = 'nodejs';
function resolveApiBase(request: NextRequest) {
const internal = process.env.INTERNAL_API_URL?.replace(/\/$/, '');
if (internal) return internal;
const origin = request.nextUrl.origin;
return `${origin}/idp-api`;
}
export async function GET(request: NextRequest) {
const target = `${resolveApiBase(request)}/releases/download/android`;
return NextResponse.redirect(target, 302);
}

View File

@@ -0,0 +1,254 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { ArrowRight, Download, Monitor, ShieldCheck, Smartphone, Sparkles } from 'lucide-react';
import { BrandLogo } from '@/components/id/brand-logo';
import { usePublicSettings } from '@/components/id/public-settings-provider';
import { Button } from '@/components/ui/button';
import {
AppRelease,
AppReleasePlatform,
buildAppReleaseDownloadUrl,
fetchPublicAppReleases
} from '@/lib/api';
function formatBytes(value: string) {
const size = Number(value);
if (!Number.isFinite(size) || size <= 0) return '—';
const units = ['Б', 'КБ', 'МБ', 'ГБ'];
let amount = size;
let unit = 0;
while (amount >= 1024 && unit < units.length - 1) {
amount /= 1024;
unit += 1;
}
return `${amount.toFixed(amount >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`;
}
function formatDate(value: string) {
return new Intl.DateTimeFormat('ru-RU', {
day: '2-digit',
month: 'long',
year: 'numeric'
}).format(new Date(value));
}
const platformCards: Array<{
platform: AppReleasePlatform;
slug: 'android' | 'windows';
title: string;
subtitle: string;
icon: typeof Smartphone;
gradient: string;
}> = [
{
platform: 'ANDROID',
slug: 'android',
title: 'Android',
subtitle: 'Скачайте APK для телефона или планшета',
icon: Smartphone,
gradient: 'from-[#34c759] to-[#0f9d58]'
},
{
platform: 'WINDOWS',
slug: 'windows',
title: 'Windows',
subtitle: 'Установщик для компьютера',
icon: Monitor,
gradient: 'from-[#3390ec] to-[#1d4ed8]'
}
];
export default function DownloadsPage() {
const { projectName } = usePublicSettings();
const [releases, setReleases] = useState<AppRelease[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
void (async () => {
try {
const response = await fetchPublicAppReleases();
setReleases(response.releases ?? []);
} finally {
setLoading(false);
}
})();
}, []);
const latestByPlatform = useMemo(() => {
const map = new Map<AppReleasePlatform, AppRelease>();
for (const release of releases) {
if (!map.has(release.platform)) {
map.set(release.platform, release);
}
}
return map;
}, [releases]);
const historyByPlatform = useMemo(() => ({
ANDROID: releases.filter((item) => item.platform === 'ANDROID'),
WINDOWS: releases.filter((item) => item.platform === 'WINDOWS')
}), [releases]);
return (
<main className="min-h-screen bg-[linear-gradient(180deg,#f7f9fc_0%,#ffffff_42%,#f4f7fb_100%)]">
<div className="mx-auto max-w-6xl px-4 py-10 sm:px-6 lg:py-14">
<div className="mb-10 flex flex-wrap items-center justify-between gap-4">
<BrandLogo />
<Button variant="outline" className="rounded-full" asChild>
<Link href="/auth/login">Войти в аккаунт</Link>
</Button>
</div>
<section className="relative overflow-hidden rounded-[32px] border border-[#e8edf5] bg-white px-6 py-10 shadow-[0_24px_80px_rgba(31,36,48,0.08)] sm:px-10 sm:py-12">
<div className="absolute -right-16 -top-16 h-56 w-56 rounded-full bg-[#eef4ff] blur-3xl" />
<div className="absolute -bottom-20 left-10 h-48 w-48 rounded-full bg-[#e8f8ee] blur-3xl" />
<div className="relative max-w-3xl">
<div className="mb-4 inline-flex items-center gap-2 rounded-full bg-[#eef4ff] px-3 py-1 text-sm font-medium text-[#3390ec]">
<Sparkles className="h-4 w-4" />
Официальные сборки {projectName}
</div>
<h1 className="text-4xl font-semibold tracking-tight text-[#1f2430] sm:text-5xl">
Скачайте приложение
</h1>
<p className="mt-4 max-w-2xl text-base leading-relaxed text-[#667085] sm:text-lg">
Актуальные версии для Android и Windows. Каждый релиз подписан SHA-256 мобильное приложение может
автоматически проверять обновления по коду версии.
</p>
</div>
</section>
<section className="mt-8 grid gap-5 lg:grid-cols-2">
{platformCards.map((card) => {
const latest = latestByPlatform.get(card.platform);
const Icon = card.icon;
return (
<div
key={card.platform}
className="overflow-hidden rounded-[28px] border border-[#eceef4] bg-white shadow-[0_18px_50px_rgba(31,36,48,0.06)]"
>
<div className={`bg-gradient-to-br ${card.gradient} px-6 py-8 text-white`}>
<div className="flex items-center gap-3">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white/15 backdrop-blur">
<Icon className="h-7 w-7" />
</div>
<div>
<h2 className="text-2xl font-semibold">{card.title}</h2>
<p className="mt-1 text-sm text-white/85">{card.subtitle}</p>
</div>
</div>
</div>
<div className="space-y-5 px-6 py-6">
{loading ? (
<p className="text-sm text-[#667085]">Проверяем доступные версии...</p>
) : latest ? (
<>
<div>
<p className="text-sm text-[#667085]">Последняя версия</p>
<div className="mt-2 flex flex-wrap items-center gap-2">
<span className="text-2xl font-semibold text-[#1f2430]">v{latest.version}</span>
<span className="rounded-full bg-[#eef4ff] px-2.5 py-1 text-xs font-medium text-[#3390ec]">
build {latest.versionCode}
</span>
</div>
<p className="mt-2 text-sm text-[#667085]">
{formatBytes(latest.fileSize)} · {formatDate(latest.createdAt)}
</p>
</div>
{latest.releaseNotes ? (
<p className="rounded-2xl bg-[#f8f9fb] px-4 py-3 text-sm leading-relaxed text-[#1f2430]">
{latest.releaseNotes}
</p>
) : null}
<div className="flex flex-col gap-3 sm:flex-row">
<Button className="flex-1 rounded-xl" asChild>
<a href={`/downloads/${card.slug}`}>
<Download className="mr-2 h-4 w-4" />
Скачать последнюю
</a>
</Button>
<Button variant="outline" className="flex-1 rounded-xl" asChild>
<a href={buildAppReleaseDownloadUrl(card.platform, latest.id)}>
Прямая ссылка
<ArrowRight className="ml-2 h-4 w-4" />
</a>
</Button>
</div>
</>
) : (
<p className="text-sm text-[#667085]">Сборка для этой платформы пока не опубликована.</p>
)}
</div>
</div>
);
})}
</section>
<section className="mt-10 grid gap-6 lg:grid-cols-2">
{platformCards.map((card) => {
const history = historyByPlatform[card.platform];
return (
<div key={`history-${card.platform}`} className="rounded-[24px] border border-[#eceef4] bg-white p-6 shadow-sm">
<h3 className="text-xl font-semibold">История версий · {card.title}</h3>
<div className="mt-4 space-y-3">
{loading ? (
<p className="text-sm text-[#667085]">Загружаем список версий...</p>
) : history.length ? (
history.map((release, index) => (
<div
key={release.id}
className="flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-[#f8f9fb] px-4 py-3"
>
<div>
<div className="flex items-center gap-2">
<span className="font-medium text-[#1f2430]">v{release.version}</span>
<span className="text-xs text-[#667085]">build {release.versionCode}</span>
{index === 0 ? (
<span className="rounded-full bg-[#e8f8ee] px-2 py-0.5 text-[11px] font-medium text-[#1a7f37]">
Актуальная
</span>
) : null}
</div>
<p className="mt-1 text-xs text-[#667085]">
{formatDate(release.createdAt)} · {formatBytes(release.fileSize)}
</p>
</div>
<Button variant="outline" size="sm" className="rounded-xl" asChild>
<a href={buildAppReleaseDownloadUrl(card.platform, release.id)}>Скачать</a>
</Button>
</div>
))
) : (
<p className="text-sm text-[#667085]">Версии пока не опубликованы.</p>
)}
</div>
</div>
);
})}
</section>
<section className="mt-10 rounded-[24px] border border-[#eceef4] bg-white p-6 shadow-sm">
<div className="flex items-start gap-3">
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl bg-[#eef4ff] text-[#3390ec]">
<ShieldCheck className="h-5 w-5" />
</div>
<div>
<h3 className="text-lg font-semibold">Проверка обновлений в приложении</h3>
<p className="mt-2 text-sm leading-relaxed text-[#667085]">
Мобильный клиент может запрашивать{' '}
<code className="rounded bg-[#f4f5f8] px-1.5 py-0.5">GET /idp-api/releases/check?platform=ANDROID&amp;versionCode=...</code>{' '}
и сравнивать SHA-256 перед установкой. Постоянные ссылки на последнюю версию:
<span className="mt-2 block font-medium text-[#1f2430]">/downloads/android</span>
<span className="block font-medium text-[#1f2430]">/downloads/windows</span>
</p>
</div>
</div>
</section>
</div>
</main>
);
}

View File

@@ -0,0 +1,15 @@
import { NextRequest, NextResponse } from 'next/server';
export const runtime = 'nodejs';
function resolveApiBase(request: NextRequest) {
const internal = process.env.INTERNAL_API_URL?.replace(/\/$/, '');
if (internal) return internal;
const origin = request.nextUrl.origin;
return `${origin}/idp-api`;
}
export async function GET(request: NextRequest) {
const target = `${resolveApiBase(request)}/releases/download/windows`;
return NextResponse.redirect(target, 302);
}

View File

@@ -1,7 +1,7 @@
'use client';
import Link from 'next/link';
import { Bot, Boxes, Settings2, ShieldCheck, Users } from 'lucide-react';
import { Bot, Boxes, Download, Settings2, ShieldCheck, Users } from 'lucide-react';
import { cn } from '@/lib/utils';
import { PublicUser } from '@/lib/api';
@@ -36,6 +36,12 @@ const links = [
label: 'Настройки',
icon: Settings2,
permissions: ['canManageSettings'] as const
},
{
href: '/admin/releases',
label: 'Приложения',
icon: Download,
permissions: ['canManageSettings'] as const
}
];

View File

@@ -26,7 +26,7 @@ export function getAdminLandingPath(user: PublicUser): string {
return '/admin/oauth';
}
export function canAccessAdminSection(user: PublicUser, section: 'users' | 'oauth' | 'settings' | 'rbac' | 'bots') {
export function canAccessAdminSection(user: PublicUser, section: 'users' | 'oauth' | 'settings' | 'rbac' | 'bots' | 'releases') {
switch (section) {
case 'users':
return Boolean(user.canViewUsers || user.canManageUsers);
@@ -35,6 +35,7 @@ export function canAccessAdminSection(user: PublicUser, section: 'users' | 'oaut
case 'oauth':
return Boolean(user.canViewOAuth || user.canManageOAuth);
case 'settings':
case 'releases':
return Boolean(user.canManageSettings);
case 'rbac':
return Boolean(user.canManageRoles);

View File

@@ -1727,5 +1727,111 @@ export async function fetchFamilyPresence(groupId: string, token?: string | null
return apiFetch<FamilyPresence>(`/family/groups/${groupId}/presence`, {}, accessToken, true, { silent: true });
}
export type AppReleasePlatform = 'ANDROID' | 'WINDOWS';
export interface AppRelease {
id: string;
platform: AppReleasePlatform;
version: string;
versionCode: number;
fileName: string;
storageKey: string;
fileSize: string;
sha256: string;
releaseNotes?: string;
isPublished: boolean;
createdAt: string;
updatedAt: string;
}
export interface AppUpdateCheckResponse {
updateAvailable: boolean;
latest?: AppRelease;
}
export async function fetchPublicAppReleases(platform?: AppReleasePlatform) {
const query = platform ? `?platform=${platform}` : '';
return apiFetch<{ releases: AppRelease[] }>(`/releases${query}`, {}, null, true, { silent: true });
}
export async function fetchLatestAppRelease(platform: AppReleasePlatform) {
return apiFetch<AppRelease>(`/releases/latest/${platform.toLowerCase()}`, {}, null, true, { silent: true });
}
export async function checkAppUpdate(platform: AppReleasePlatform, versionCode: number) {
return apiFetch<AppUpdateCheckResponse>(
`/releases/check?platform=${platform}&versionCode=${versionCode}`,
{},
null,
true,
{ silent: true }
);
}
export function buildAppReleaseDownloadUrl(platform: AppReleasePlatform, releaseId?: string) {
const base = getApiUrl().replace(/\/$/, '');
const slug = platform.toLowerCase();
return releaseId ? `${base}/releases/download/${slug}/${releaseId}` : `${base}/releases/download/${slug}`;
}
export async function fetchAdminAppReleases(token: string, platform?: AppReleasePlatform) {
const query = platform ? `?platform=${platform}` : '';
return apiFetch<{ releases: AppRelease[] }>(`/admin/releases${query}`, {}, token);
}
export async function uploadAdminAppRelease(
token: string,
payload: {
platform: AppReleasePlatform;
version: string;
versionCode: number;
releaseNotes?: string;
file: File;
},
onProgress?: (percent: number) => void
) {
const formData = new FormData();
formData.append('platform', payload.platform);
formData.append('version', payload.version.trim());
formData.append('versionCode', String(payload.versionCode));
if (payload.releaseNotes?.trim()) {
formData.append('releaseNotes', payload.releaseNotes.trim());
}
formData.append('file', payload.file, payload.file.name);
const apiBase = getApiUrl().replace(/\/$/, '');
const response = await platformFetch(`${apiBase}/admin/releases/upload`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`
},
body: formData
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
const message = typeof body?.message === 'string' ? body.message : 'Не удалось загрузить релиз';
throw new ApiError(message, response.status, 'UPLOAD_FAILED');
}
onProgress?.(100);
return (await response.json()) as AppRelease;
}
export async function updateAdminAppRelease(
token: string,
releaseId: string,
patch: { isPublished?: boolean; releaseNotes?: string }
) {
return apiFetch<AppRelease>(`/admin/releases/${releaseId}`, {
method: 'PATCH',
body: JSON.stringify(patch)
}, token);
}
export async function deleteAdminAppRelease(token: string, releaseId: string) {
return apiFetch<{ deleted: boolean }>(`/admin/releases/${releaseId}`, { method: 'DELETE' }, token);
}
/** @deprecated Используйте getWsUrl() — URL может переключаться на same-origin /idp-api/ws в браузере */
export const WS_URL = configuredWsUrl;