fix file size limit

This commit is contained in:
lendry
2026-07-07 17:36:01 +03:00
parent b90017aad0
commit f36a8d7456
12 changed files with 482 additions and 159 deletions

View File

@@ -83,6 +83,7 @@ export class AdminAppReleaseController {
platform: { type: 'string', enum: ['ANDROID', 'WINDOWS'] },
version: { type: 'string', example: '1.2.0' },
versionCode: { type: 'integer', example: 120 },
variant: { type: 'string', example: 'arm64-v8a', description: 'Вариант сборки. Если пусто — определяется из имени файла.' },
releaseNotes: { type: 'string' },
file: { type: 'string', format: 'binary' }
},
@@ -96,6 +97,7 @@ export class AdminAppReleaseController {
@Body('platform') platform: string,
@Body('version') version: string,
@Body('versionCode') versionCodeRaw: string,
@Body('variant') variant: string | undefined,
@Body('releaseNotes') releaseNotes?: string
) {
assertAdminPermission(admin, 'canManageSettings');
@@ -124,7 +126,12 @@ export class AdminAppReleaseController {
const safeVersion = version.trim().replace(/[^a-zA-Z0-9._-]+/g, '_');
const safeName = fileName.replace(/[^a-zA-Z0-9._-]+/g, '_');
const storageKey = `releases/${normalizedPlatform.toLowerCase()}/${safeVersion}/${randomUUID()}-${safeName}`;
const normalizedVariant = (variant?.trim() || fileName.replace(/\.apk$/i, ''))
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9._-]/g, '')
.slice(0, 64) || 'universal';
const storageKey = `releases/${normalizedPlatform.toLowerCase()}/${safeVersion}/${normalizedVariant}/${randomUUID()}-${safeName}`;
const sha256 = createHash('sha256').update(file.buffer).digest('hex');
const contentType =
normalizedPlatform === 'ANDROID'
@@ -146,6 +153,7 @@ export class AdminAppReleaseController {
platform: normalizedPlatform,
version: version.trim(),
versionCode,
variant: variant?.trim() || undefined,
fileName,
storageKey,
fileSize: String(file.size),

View File

@@ -79,14 +79,19 @@ export class AppReleaseController {
@Get('download/:platform')
@ApiOperation({ summary: 'Скачать последний релиз', description: 'Отдаёт файл последней опубликованной версии.' })
@ApiParam({ name: 'platform', enum: ['android', 'windows', 'ANDROID', 'WINDOWS'] })
@ApiQuery({ name: 'variant', required: false, description: 'Вариант сборки, например universal или arm64-v8a' })
@ApiResponse({ status: 200, description: 'Файл релиза' })
async downloadLatest(@Param('platform') platform: string, @Res({ passthrough: false }) response: StreamResponse) {
async downloadLatest(
@Param('platform') platform: string,
@Query('variant') variant: string | undefined,
@Res({ passthrough: false }) response: StreamResponse
) {
const normalized = this.normalizePlatform(platform);
if (!normalized) {
response.status(400).json({ message: 'Некорректная платформа' });
return;
}
await this.streamRelease(response, normalized);
await this.streamRelease(response, normalized, undefined, variant);
}
@Get('download/:platform/:releaseId')
@@ -104,9 +109,14 @@ export class AppReleaseController {
await this.streamRelease(response, normalized, releaseId);
}
private async streamRelease(response: StreamResponse, platform: string, releaseId?: string) {
private async streamRelease(
response: StreamResponse,
platform: string,
releaseId?: string,
variant?: string
) {
const resolved = (await firstValueFrom(
this.core.appRelease.ResolveAppReleaseDownload({ platform, releaseId })
this.core.appRelease.ResolveAppReleaseDownload({ platform, releaseId, variant })
)) as {
storageKey: string;
fileName: string;
@@ -115,6 +125,7 @@ export class AppReleaseController {
sha256: string;
version: string;
versionCode: number;
variant: string;
};
const bucket = process.env.MINIO_BUCKET ?? 'lendry-id';
@@ -129,6 +140,7 @@ export class AppReleaseController {
response.setHeader('Content-Length', resolved.fileSize);
response.setHeader('X-Release-Version', resolved.version);
response.setHeader('X-Release-Version-Code', String(resolved.versionCode));
response.setHeader('X-Release-Variant', resolved.variant);
response.setHeader('X-Release-Sha256', resolved.sha256);
response.setHeader('Cache-Control', 'public, max-age=300');
response.setHeader('Content-Disposition', buildContentDisposition('attachment', resolved.fileName));

View File

@@ -15,6 +15,11 @@ import {
updateAdminAppRelease,
uploadAdminAppRelease
} from '@/lib/api';
import {
detectVariantFromFileName,
formatReleaseVariantLabel,
groupReleasesByVersion
} from '@/lib/app-release-variants';
const ANDROID_PLATFORM = 'ANDROID' as const;
const APK_ACCEPT = '.apk,application/vnd.android.package-archive';
@@ -52,7 +57,7 @@ export default function AdminReleasesPage() {
const [version, setVersion] = useState('');
const [versionCode, setVersionCode] = useState('');
const [releaseNotes, setReleaseNotes] = useState('');
const [file, setFile] = useState<File | null>(null);
const [files, setFiles] = useState<File[]>([]);
const canManage = Boolean(user?.canManageSettings);
@@ -78,16 +83,26 @@ export default function AdminReleasesPage() {
[releases]
);
const groupedReleases = useMemo(() => groupReleasesByVersion(androidReleases), [androidReleases]);
const detectedVariants = useMemo(
() => files.map((file) => ({ file, variant: detectVariantFromFileName(file.name) })),
[files]
);
async function handleUpload(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!token || !file) {
showToast('Выберите файл релиза');
if (!token || !files.length) {
showToast('Выберите один или несколько APK');
return;
}
if (file.size > MAX_RELEASE_FILE_BYTES) {
showToast('APK не должен превышать 350 МБ');
const oversized = files.find((file) => file.size > MAX_RELEASE_FILE_BYTES);
if (oversized) {
showToast(`Файл ${oversized.name} превышает лимит 350 МБ`);
return;
}
const parsedVersionCode = Number(versionCode);
if (!version.trim() || !Number.isInteger(parsedVersionCode) || parsedVersionCode < 1) {
showToast('Укажите версию и положительный код версии');
@@ -95,21 +110,34 @@ export default function AdminReleasesPage() {
}
setUploading(true);
const created: AppRelease[] = [];
try {
const created = await uploadAdminAppRelease(token, {
platform: ANDROID_PLATFORM,
version: version.trim(),
versionCode: parsedVersionCode,
releaseNotes: releaseNotes.trim() || undefined,
file
});
setReleases((current) => [created, ...current]);
for (const file of files) {
const item = await uploadAdminAppRelease(token, {
platform: ANDROID_PLATFORM,
version: version.trim(),
versionCode: parsedVersionCode,
variant: detectVariantFromFileName(file.name),
releaseNotes: releaseNotes.trim() || undefined,
file
});
created.push(item);
}
setReleases((current) => [...created, ...current]);
setVersion('');
setVersionCode('');
setReleaseNotes('');
setFile(null);
showToast('Релиз загружен и опубликован');
setFiles([]);
showToast(
created.length === 1
? `Загружена сборка ${formatReleaseVariantLabel(created[0].variant)}`
: `Загружено сборок: ${created.length}`
);
} catch (error) {
if (created.length) {
setReleases((current) => [...created, ...current]);
}
showToast(getApiErrorMessage(error, 'Не удалось загрузить релиз') ?? 'Ошибка');
} finally {
setUploading(false);
@@ -129,80 +157,102 @@ export default function AdminReleasesPage() {
async function removeRelease(release: AppRelease) {
if (!token) return;
if (!window.confirm(`Удалить версию ${release.version} (Android)?`)) return;
if (!window.confirm(`Удалить сборку ${formatReleaseVariantLabel(release.variant)} для v${release.version}?`)) return;
try {
await deleteAdminAppRelease(token, release.id);
setReleases((current) => current.filter((item) => item.id !== release.id));
showToast('Релиз удалён');
showToast('Сборка удалена');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось удалить релиз') ?? 'Ошибка');
}
}
function renderReleaseList(items: AppRelease[], emptyLabel: string) {
function renderReleaseList(emptyLabel: string) {
if (loading) {
return <div className="rounded-[20px] bg-[#f4f5f8] px-4 py-5 text-[#667085]">Загружаем релизы...</div>;
}
if (!items.length) {
if (!groupedReleases.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 isLatest = index === 0 && release.isPublished;
<div className="space-y-4">
{groupedReleases.map((group, groupIndex) => {
const publishedVariants = group.variants.filter((item) => item.isPublished);
const isLatest = groupIndex === 0 && publishedVariants.length > 0;
const notes = group.variants.find((item) => item.releaseNotes)?.releaseNotes;
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]">
<Smartphone 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/android" 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)}
<div key={group.key} className="rounded-[20px] border border-[#eceef4] bg-white p-4 shadow-sm">
<div className="mb-4 flex flex-wrap items-center gap-2">
<h3 className="text-lg font-semibold">v{group.version}</h3>
<span className="rounded-full bg-[#eef4ff] px-2 py-0.5 text-xs font-medium text-[#3390ec]">
build {group.versionCode}
</span>
<span className="rounded-full bg-[#f4f5f8] px-2 py-0.5 text-xs font-medium text-[#667085]">
{group.variants.length} {group.variants.length === 1 ? 'сборка' : 'сборки'}
</span>
{isLatest ? (
<span className="rounded-full bg-[#e8f8ee] px-2 py-0.5 text-xs font-medium text-[#1a7f37]">
Последняя версия
</span>
) : null}
</div>
{notes ? (
<p className="mb-4 whitespace-pre-wrap rounded-2xl bg-[#f8f9fb] px-4 py-3 text-sm leading-relaxed text-[#1f2430]">
{notes}
</p>
) : null}
<div className="space-y-3">
{group.variants.map((release) => (
<div
key={release.id}
className="flex flex-wrap items-start justify-between gap-3 rounded-2xl bg-[#f8f9fb] px-4 py-3"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<div className="flex min-w-0 items-start gap-3">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white">
<Smartphone className="h-4 w-4 text-[#3390ec]" />
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-[#1f2430]">
{formatReleaseVariantLabel(release.variant)}
</span>
{!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>
</div>
</div>
<div className="flex shrink-0 flex-wrap gap-2">
<Button variant="outline" size="sm" className="rounded-xl" asChild>
<a href={`/downloads/android/${release.id}`} 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>
);
@@ -229,7 +279,7 @@ export default function AdminReleasesPage() {
</div>
<div>
<h2 className="text-xl font-semibold">Новая версия Android</h2>
<p className="text-sm text-[#667085]">Загрузите APK с подписью SHA-256</p>
<p className="text-sm text-[#667085]">Можно загрузить несколько APK одной версии</p>
</div>
</div>
@@ -257,26 +307,45 @@ export default function AdminReleasesPage() {
<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]">
<Smartphone className="mb-3 h-8 w-8 text-[#3390ec]" />
<span className="text-sm font-medium text-[#1f2430]">{file ? file.name : 'Выберите файл .apk'}</span>
<span className="mt-1 text-xs text-[#667085]">До 350 МБ</span>
<span className="text-sm font-medium text-[#1f2430]">
{files.length ? `Выбрано файлов: ${files.length}` : 'Выберите один или несколько .apk'}
</span>
<span className="mt-1 text-xs text-[#667085]">
universal-release, arm64-v8a-release и другие варианты одной версии
</span>
<input
type="file"
className="hidden"
multiple
accept={APK_ACCEPT}
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
onChange={(event) => setFiles([...(event.target.files ?? [])])}
/>
</label>
<Button type="submit" className="w-full rounded-xl" disabled={uploading || !file}>
{detectedVariants.length ? (
<div className="rounded-2xl bg-[#f8f9fb] px-4 py-3">
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-[#667085]">Определённые варианты</p>
<div className="space-y-1">
{detectedVariants.map((item) => (
<p key={`${item.file.name}-${item.variant}`} className="text-sm text-[#1f2430]">
<span className="font-medium">{formatReleaseVariantLabel(item.variant)}</span>
<span className="text-[#667085]"> · {item.file.name}</span>
</p>
))}
</div>
</div>
) : null}
<Button type="submit" className="w-full rounded-xl" disabled={uploading || !files.length}>
{uploading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Upload className="mr-2 h-4 w-4" />}
{uploading ? 'Загружаем...' : 'Загрузить релиз'}
{uploading ? 'Загружаем...' : files.length > 1 ? `Загрузить ${files.length} сборки` : 'Загрузить релиз'}
</Button>
</form>
</section>
<section>
<h2 className="mb-4 text-xl font-semibold">Версии Android</h2>
{renderReleaseList(androidReleases, 'Релизы Android пока не загружены')}
{renderReleaseList('Релизы Android пока не загружены')}
</section>
</div>
</AdminShell>

View File

@@ -11,6 +11,7 @@ import {
buildAppReleaseDownloadUrl,
fetchPublicAppReleases
} from '@/lib/api';
import { formatReleaseVariantLabel, groupReleasesByVersion } from '@/lib/app-release-variants';
function formatBytes(value: string) {
const size = Number(value);
@@ -49,15 +50,15 @@ export default function DownloadsPage() {
})();
}, []);
const latestRelease = useMemo(
() => releases.find((item) => item.platform === 'ANDROID') ?? null,
const groupedReleases = useMemo(
() => groupReleasesByVersion(releases.filter((item) => item.platform === 'ANDROID')),
[releases]
);
const androidHistory = useMemo(
() => releases.filter((item) => item.platform === 'ANDROID'),
[releases]
);
const latestGroup = groupedReleases[0] ?? null;
const latestVariants = latestGroup?.variants ?? [];
const preferredLatest =
latestVariants.find((item) => item.variant === 'universal') ?? latestVariants[0] ?? null;
return (
<main className="min-h-screen bg-[linear-gradient(180deg,#f7f9fc_0%,#ffffff_42%,#f4f7fb_100%)]">
@@ -81,8 +82,8 @@ export default function DownloadsPage() {
Скачайте приложение
</h1>
<p className="mt-4 max-w-2xl text-base leading-relaxed text-[#667085] sm:text-lg">
Актуальная версия для Android. Каждый релиз подписан SHA-256 мобильное приложение может
автоматически проверять обновления по коду версии.
Актуальная версия для Android. Доступны разные сборки: universal, arm64-v8a и другие.
Каждый файл подписан SHA-256.
</p>
</div>
</section>
@@ -96,7 +97,7 @@ export default function DownloadsPage() {
</div>
<div>
<h2 className="text-2xl font-semibold">Android</h2>
<p className="mt-1 text-sm text-white/85">Скачайте APK для телефона или планшета</p>
<p className="mt-1 text-sm text-white/85">Выберите подходящую сборку APK</p>
</div>
</div>
</div>
@@ -104,37 +105,64 @@ export default function DownloadsPage() {
<div className="space-y-5 px-6 py-6">
{loading ? (
<p className="text-sm text-[#667085]">Проверяем доступные версии...</p>
) : latestRelease ? (
) : latestGroup && preferredLatest ? (
<>
<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{latestRelease.version}</span>
<span className="text-2xl font-semibold text-[#1f2430]">v{latestGroup.version}</span>
<span className="rounded-full bg-[#eef4ff] px-2.5 py-1 text-xs font-medium text-[#3390ec]">
build {latestRelease.versionCode}
build {latestGroup.versionCode}
</span>
{latestVariants.length > 1 ? (
<span className="rounded-full bg-[#f4f5f8] px-2.5 py-1 text-xs font-medium text-[#667085]">
{latestVariants.length} сборки
</span>
) : null}
</div>
<p className="mt-2 text-sm text-[#667085]">
{formatBytes(latestRelease.fileSize)} · {formatDate(latestRelease.createdAt)}
{formatDate(preferredLatest.createdAt)}
</p>
</div>
{latestRelease.releaseNotes ? (
{preferredLatest.releaseNotes ? (
<p className="rounded-2xl bg-[#f8f9fb] px-4 py-3 text-sm leading-relaxed text-[#1f2430]">
{latestRelease.releaseNotes}
{preferredLatest.releaseNotes}
</p>
) : null}
<div className="grid gap-3 sm:grid-cols-2">
{latestVariants.map((release) => (
<div
key={release.id}
className="flex flex-col justify-between rounded-2xl border border-[#eceef4] bg-[#f8f9fb] p-4"
>
<div>
<p className="font-medium text-[#1f2430]">{formatReleaseVariantLabel(release.variant)}</p>
<p className="mt-1 text-xs text-[#667085]">
{formatBytes(release.fileSize)} · {release.fileName}
</p>
</div>
<Button className="mt-4 rounded-xl" asChild>
<a href={buildAppReleaseDownloadUrl('ANDROID', release.id)}>
<Download className="mr-2 h-4 w-4" />
Скачать
</a>
</Button>
</div>
))}
</div>
<div className="flex flex-col gap-3 sm:flex-row">
<Button className="flex-1 rounded-xl" asChild>
<a href="/downloads/android">
<a href={buildAppReleaseDownloadUrl('ANDROID', preferredLatest.id)}>
<Download className="mr-2 h-4 w-4" />
Скачать последнюю
Скачать рекомендуемую
</a>
</Button>
<Button variant="outline" className="flex-1 rounded-xl" asChild>
<a href={buildAppReleaseDownloadUrl('ANDROID', latestRelease.id)}>
Прямая ссылка
<a href={buildAppReleaseDownloadUrl('ANDROID', undefined, 'universal')}>
Universal по ссылке
<ArrowRight className="ml-2 h-4 w-4" />
</a>
</Button>
@@ -149,32 +177,38 @@ export default function DownloadsPage() {
<section className="mt-10 rounded-[24px] border border-[#eceef4] bg-white p-6 shadow-sm">
<h3 className="text-xl font-semibold">История версий</h3>
<div className="mt-4 space-y-3">
<div className="mt-4 space-y-4">
{loading ? (
<p className="text-sm text-[#667085]">Загружаем список версий...</p>
) : androidHistory.length ? (
androidHistory.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>
) : groupedReleases.length ? (
groupedReleases.map((group, groupIndex) => (
<div key={group.key} className="rounded-2xl bg-[#f8f9fb] px-4 py-4">
<div className="mb-3 flex flex-wrap items-center gap-2">
<span className="font-medium text-[#1f2430]">v{group.version}</span>
<span className="text-xs text-[#667085]">build {group.versionCode}</span>
{groupIndex === 0 ? (
<span className="rounded-full bg-[#e8f8ee] px-2 py-0.5 text-[11px] font-medium text-[#1a7f37]">
Актуальная
</span>
) : null}
</div>
<div className="space-y-2">
{group.variants.map((release) => (
<div key={release.id} className="flex flex-wrap items-center justify-between gap-3 rounded-xl bg-white px-3 py-2">
<div>
<p className="text-sm font-medium text-[#1f2430]">
{formatReleaseVariantLabel(release.variant)}
</p>
<p className="text-xs text-[#667085]">
{formatDate(release.createdAt)} · {formatBytes(release.fileSize)}
</p>
</div>
<Button variant="outline" size="sm" className="rounded-xl" asChild>
<a href={buildAppReleaseDownloadUrl('ANDROID', release.id)}>Скачать</a>
</Button>
</div>
))}
</div>
<Button variant="outline" size="sm" className="rounded-xl" asChild>
<a href={buildAppReleaseDownloadUrl('ANDROID', release.id)}>Скачать</a>
</Button>
</div>
))
) : (
@@ -193,8 +227,9 @@ export default function DownloadsPage() {
<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>
и получать список всех сборок последней версии в поле <code className="rounded bg-[#f4f5f8] px-1.5 py-0.5">variants</code>.
Для конкретной архитектуры используйте{' '}
<code className="rounded bg-[#f4f5f8] px-1.5 py-0.5">/downloads/android?variant=arm64-v8a</code>.
</p>
</div>
</div>

View File

@@ -1734,6 +1734,7 @@ export interface AppRelease {
platform: AppReleasePlatform;
version: string;
versionCode: number;
variant: string;
fileName: string;
storageKey: string;
fileSize: string;
@@ -1747,6 +1748,7 @@ export interface AppRelease {
export interface AppUpdateCheckResponse {
updateAvailable: boolean;
latest?: AppRelease;
variants?: AppRelease[];
}
export async function fetchPublicAppReleases(platform?: AppReleasePlatform) {
@@ -1768,9 +1770,11 @@ export async function checkAppUpdate(platform: AppReleasePlatform, versionCode:
);
}
export function buildAppReleaseDownloadUrl(platform: AppReleasePlatform, releaseId?: string) {
export function buildAppReleaseDownloadUrl(platform: AppReleasePlatform, releaseId?: string, variant?: string) {
const slug = platform.toLowerCase();
return releaseId ? `/downloads/${slug}/${releaseId}` : `/downloads/${slug}`;
if (releaseId) return `/downloads/${slug}/${releaseId}`;
if (variant) return `/downloads/${slug}?variant=${encodeURIComponent(variant)}`;
return `/downloads/${slug}`;
}
export async function fetchAdminAppReleases(token: string, platform?: AppReleasePlatform) {
@@ -1784,6 +1788,7 @@ export async function uploadAdminAppRelease(
platform: AppReleasePlatform;
version: string;
versionCode: number;
variant?: string;
releaseNotes?: string;
file: File;
},
@@ -1793,6 +1798,9 @@ export async function uploadAdminAppRelease(
formData.append('platform', payload.platform);
formData.append('version', payload.version.trim());
formData.append('versionCode', String(payload.versionCode));
if (payload.variant?.trim()) {
formData.append('variant', payload.variant.trim());
}
if (payload.releaseNotes?.trim()) {
formData.append('releaseNotes', payload.releaseNotes.trim());
}

View File

@@ -0,0 +1,56 @@
const FILENAME_VARIANT_RULES: Array<{ pattern: RegExp; variant: string }> = [
{ pattern: /arm64[-_]?v8a/i, variant: 'arm64-v8a' },
{ pattern: /armeabi[-_]?v7a/i, variant: 'armeabi-v7a' },
{ pattern: /x86[-_]?64/i, variant: 'x86_64' },
{ pattern: /(?<![a-z0-9])x86(?![a-z0-9])/i, variant: 'x86' },
{ pattern: /universal/i, variant: 'universal' }
];
const VARIANT_LABELS: Record<string, string> = {
universal: 'Universal',
'arm64-v8a': 'ARM64 (arm64-v8a)',
'armeabi-v7a': 'ARMv7 (armeabi-v7a)',
x86_64: 'x86_64',
x86: 'x86'
};
export function detectVariantFromFileName(fileName: string) {
const baseName = fileName.trim().replace(/\.apk$/i, '');
for (const rule of FILENAME_VARIANT_RULES) {
if (rule.pattern.test(baseName)) {
return rule.variant;
}
}
const normalized = baseName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 64);
return normalized || 'universal';
}
export function formatReleaseVariantLabel(variant: string) {
return VARIANT_LABELS[variant] ?? variant;
}
export function groupReleasesByVersion<T extends { version: string; versionCode: number }>(releases: T[]) {
const groups = new Map<string, T[]>();
for (const release of releases) {
const key = `${release.versionCode}:${release.version}`;
const list = groups.get(key) ?? [];
list.push(release);
groups.set(key, list);
}
return [...groups.entries()]
.sort((left, right) => Number(right[0].split(':')[0]) - Number(left[0].split(':')[0]))
.map(([key, items]) => ({
key,
version: items[0]?.version ?? '',
versionCode: items[0]?.versionCode ?? 0,
variants: [...items].sort((a, b) => {
const left = 'variant' in a ? String((a as { variant?: string }).variant ?? '') : '';
const right = 'variant' in b ? String((b as { variant?: string }).variant ?? '') : '';
return left.localeCompare(right, 'ru');
})
}));
}

View File

@@ -12,6 +12,7 @@ const PASSTHROUGH_HEADERS = [
'content-disposition',
'x-release-version',
'x-release-version-code',
'x-release-variant',
'x-release-sha256',
'cache-control'
] as const;
@@ -22,9 +23,10 @@ export async function proxyReleaseDownload(
releaseId?: string
) {
const apiBase = resolveServerApiBase(request);
const variant = request.nextUrl.searchParams.get('variant');
const path = releaseId
? `/releases/download/${platform}/${releaseId}`
: `/releases/download/${platform}`;
: `/releases/download/${platform}${variant ? `?variant=${encodeURIComponent(variant)}` : ''}`;
const upstream = await fetch(`${apiBase}${path}`, {
method: 'GET',

View File

@@ -0,0 +1,8 @@
-- Add variant column for multiple APK builds per version (universal, arm64-v8a, etc.)
ALTER TABLE "AppRelease" ADD COLUMN "variant" TEXT NOT NULL DEFAULT 'universal';
DROP INDEX IF EXISTS "AppRelease_platform_version_key";
DROP INDEX IF EXISTS "AppRelease_platform_versionCode_key";
CREATE UNIQUE INDEX "AppRelease_platform_versionCode_variant_key" ON "AppRelease"("platform", "versionCode", "variant");
CREATE INDEX "AppRelease_platform_versionCode_isPublished_idx" ON "AppRelease"("platform", "versionCode", "isPublished");

View File

@@ -51,6 +51,7 @@ model AppRelease {
platform AppReleasePlatform
version String
versionCode Int
variant String @default("universal")
fileName String
storageKey String @unique
fileSize BigInt
@@ -61,9 +62,9 @@ model AppRelease {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([platform, version])
@@unique([platform, versionCode])
@@unique([platform, versionCode, variant])
@@index([platform, isPublished, createdAt])
@@index([platform, versionCode, isPublished])
}
model User {

View File

@@ -4,7 +4,16 @@ import { AppReleasePlatform, Prisma } from '../generated/prisma/client';
import { PrismaService } from '../infra/prisma.service';
import { MinioService } from '../infra/minio.service';
type PlatformInput = 'ANDROID' | 'WINDOWS';
const VARIANT_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const FILENAME_VARIANT_RULES: Array<{ pattern: RegExp; variant: string }> = [
{ pattern: /arm64[-_]?v8a/i, variant: 'arm64-v8a' },
{ pattern: /armeabi[-_]?v7a/i, variant: 'armeabi-v7a' },
{ pattern: /x86[-_]?64/i, variant: 'x86_64' },
{ pattern: /(?<![a-z0-9])x86(?![a-z0-9])/i, variant: 'x86' },
{ pattern: /universal/i, variant: 'universal' },
{ pattern: /aab/i, variant: 'aab' }
];
@Injectable()
export class AppReleaseService {
@@ -13,6 +22,36 @@ export class AppReleaseService {
private readonly minio: MinioService
) {}
detectVariantFromFileName(fileName: string) {
const baseName = fileName.trim().replace(/\.apk$/i, '');
for (const rule of FILENAME_VARIANT_RULES) {
if (rule.pattern.test(baseName)) {
return rule.variant;
}
}
const normalized = baseName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 64);
return normalized || 'universal';
}
normalizeVariant(raw?: string, fileName?: string) {
const trimmed = raw?.trim().toLowerCase();
if (trimmed) {
const normalized = trimmed.replace(/\s+/g, '-').replace(/[^a-z0-9._-]/g, '');
if (!normalized || !VARIANT_PATTERN.test(normalized)) {
throw new BadRequestException('Вариант сборки должен содержать только латиницу, цифры, точки и дефисы');
}
return normalized;
}
if (fileName?.trim()) {
return this.detectVariantFromFileName(fileName);
}
return 'universal';
}
private normalizePlatform(platform: string): AppReleasePlatform {
const normalized = platform.trim().toUpperCase();
if (normalized === 'ANDROID' || normalized === 'WINDOWS') {
@@ -26,6 +65,7 @@ export class AppReleaseService {
platform: AppReleasePlatform;
version: string;
versionCode: number;
variant: string;
fileName: string;
storageKey: string;
fileSize: bigint;
@@ -40,6 +80,7 @@ export class AppReleaseService {
platform: release.platform,
version: release.version,
versionCode: release.versionCode,
variant: release.variant,
fileName: release.fileName,
storageKey: release.storageKey,
fileSize: release.fileSize.toString(),
@@ -72,10 +113,33 @@ export class AppReleaseService {
}
}
buildStorageKey(platform: AppReleasePlatform, version: string, fileName: string) {
buildStorageKey(platform: AppReleasePlatform, version: string, variant: string, fileName: string) {
const safeVersion = version.replace(/[^a-zA-Z0-9._-]+/g, '_');
const safeVariant = variant.replace(/[^a-zA-Z0-9._-]+/g, '_');
const safeName = fileName.replace(/[^a-zA-Z0-9._-]+/g, '_');
return `releases/${platform.toLowerCase()}/${safeVersion}/${randomUUID()}-${safeName}`;
return `releases/${platform.toLowerCase()}/${safeVersion}/${safeVariant}/${randomUUID()}-${safeName}`;
}
private preferVariant<T extends { variant: string }>(releases: T[]) {
if (!releases.length) return null;
return releases.find((item) => item.variant === 'universal') ?? releases[0];
}
private async getLatestPublishedVersionCode(platform: AppReleasePlatform) {
const latest = await this.prisma.appRelease.findFirst({
where: { platform, isPublished: true },
orderBy: [{ versionCode: 'desc' }, { createdAt: 'desc' }],
select: { versionCode: true }
});
return latest?.versionCode ?? null;
}
private async listPublishedVariants(platform: AppReleasePlatform, versionCode: number) {
const releases = await this.prisma.appRelease.findMany({
where: { platform, isPublished: true, versionCode },
orderBy: [{ variant: 'asc' }, { createdAt: 'desc' }]
});
return releases;
}
async listReleases(platform?: string) {
@@ -84,7 +148,7 @@ export class AppReleaseService {
: {};
const releases = await this.prisma.appRelease.findMany({
where,
orderBy: [{ platform: 'asc' }, { versionCode: 'desc' }, { createdAt: 'desc' }]
orderBy: [{ platform: 'asc' }, { versionCode: 'desc' }, { variant: 'asc' }, { createdAt: 'desc' }]
});
return { releases: releases.map((release) => this.toResponse(release)) };
}
@@ -96,7 +160,7 @@ export class AppReleaseService {
};
const releases = await this.prisma.appRelease.findMany({
where,
orderBy: [{ platform: 'asc' }, { versionCode: 'desc' }, { createdAt: 'desc' }]
orderBy: [{ platform: 'asc' }, { versionCode: 'desc' }, { variant: 'asc' }, { createdAt: 'desc' }]
});
return { releases: releases.map((release) => this.toResponse(release)) };
}
@@ -105,6 +169,7 @@ export class AppReleaseService {
platform: string;
version: string;
versionCode: number;
variant?: string;
fileName: string;
storageKey: string;
fileSize: string | number | bigint;
@@ -114,6 +179,7 @@ export class AppReleaseService {
}) {
const platform = this.normalizePlatform(input.platform);
const version = input.version.trim();
const variant = this.normalizeVariant(input.variant, input.fileName);
if (!/^\d+(?:\.\d+){0,3}(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
throw new BadRequestException('Версия должна быть в формате semver, например 1.2.3');
}
@@ -142,6 +208,7 @@ export class AppReleaseService {
platform,
version,
versionCode: input.versionCode,
variant,
fileName: input.fileName.trim(),
storageKey: input.storageKey,
fileSize: BigInt(input.fileSize),
@@ -153,7 +220,9 @@ export class AppReleaseService {
return this.toResponse(release);
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
throw new BadRequestException('Релиз с такой версией или кодом версии уже существует для этой платформы');
throw new BadRequestException(
`Сборка «${variant}» для версии ${version} (код ${input.versionCode}) уже загружена. Выберите другой вариант или удалите существующий файл.`
);
}
throw error;
}
@@ -183,10 +252,13 @@ export class AppReleaseService {
async getLatestRelease(platform: string) {
const normalized = this.normalizePlatform(platform);
const release = await this.prisma.appRelease.findFirst({
where: { platform: normalized, isPublished: true },
orderBy: [{ versionCode: 'desc' }, { createdAt: 'desc' }]
});
const versionCode = await this.getLatestPublishedVersionCode(normalized);
if (versionCode === null) {
throw new NotFoundException('Опубликованный релиз для этой платформы не найден');
}
const variants = await this.listPublishedVariants(normalized, versionCode);
const release = this.preferVariant(variants);
if (!release) {
throw new NotFoundException('Опубликованный релиз для этой платформы не найден');
}
@@ -194,29 +266,75 @@ export class AppReleaseService {
}
async checkUpdate(platform: string, versionCode: number) {
const latest = await this.getLatestRelease(platform);
const updateAvailable = versionCode < latest.versionCode;
const normalized = this.normalizePlatform(platform);
const latestVersionCode = await this.getLatestPublishedVersionCode(normalized);
if (latestVersionCode === null || versionCode >= latestVersionCode) {
return { updateAvailable: false, variants: [] };
}
const variants = await this.listPublishedVariants(normalized, latestVersionCode);
const preferred = this.preferVariant(variants);
if (!preferred) {
return { updateAvailable: false, variants: [] };
}
return {
updateAvailable,
latest: updateAvailable ? latest : undefined
updateAvailable: true,
latest: this.toResponse(preferred),
variants: variants.map((item) => this.toResponse(item))
};
}
async resolveDownload(platform: string, releaseId?: string) {
async resolveDownload(platform: string, releaseId?: string, variant?: string) {
const normalized = this.normalizePlatform(platform);
const release = releaseId
? await this.prisma.appRelease.findFirst({
where: { id: releaseId, platform: normalized, isPublished: true }
})
: await this.prisma.appRelease.findFirst({
where: { platform: normalized, isPublished: true },
orderBy: [{ versionCode: 'desc' }, { createdAt: 'desc' }]
});
if (releaseId) {
const release = await this.prisma.appRelease.findFirst({
where: { id: releaseId, platform: normalized, isPublished: true }
});
if (!release) {
throw new NotFoundException('Файл релиза не найден');
}
return this.toDownloadResponse(release);
}
const latestVersionCode = await this.getLatestPublishedVersionCode(normalized);
if (latestVersionCode === null) {
throw new NotFoundException('Файл релиза не найден');
}
const normalizedVariant = variant?.trim() ? this.normalizeVariant(variant) : 'universal';
let release = await this.prisma.appRelease.findFirst({
where: {
platform: normalized,
isPublished: true,
versionCode: latestVersionCode,
variant: normalizedVariant
}
});
if (!release) {
const variants = await this.listPublishedVariants(normalized, latestVersionCode);
release = this.preferVariant(variants);
}
if (!release) {
throw new NotFoundException('Файл релиза не найден');
}
return this.toDownloadResponse(release);
}
private toDownloadResponse(release: {
storageKey: string;
fileName: string;
platform: AppReleasePlatform;
fileSize: bigint;
sha256: string;
version: string;
versionCode: number;
variant: string;
}) {
return {
storageKey: release.storageKey,
fileName: release.fileName,
@@ -224,7 +342,8 @@ export class AppReleaseService {
fileSize: release.fileSize.toString(),
sha256: release.sha256,
version: release.version,
versionCode: release.versionCode
versionCode: release.versionCode,
variant: release.variant
};
}
}

View File

@@ -1411,6 +1411,7 @@ export class AuthGrpcController {
platform: string;
version: string;
versionCode: number;
variant?: string;
fileName: string;
storageKey: string;
fileSize: string;
@@ -1445,7 +1446,7 @@ export class AuthGrpcController {
}
@GrpcMethod('AppReleaseService', 'ResolveAppReleaseDownload')
resolveAppReleaseDownload(command: { platform: string; releaseId?: string }) {
return this.appRelease.resolveDownload(command.platform, command.releaseId);
resolveAppReleaseDownload(command: { platform: string; releaseId?: string; variant?: string }) {
return this.appRelease.resolveDownload(command.platform, command.releaseId, command.variant);
}
}

View File

@@ -28,6 +28,7 @@ message AppRelease {
bool isPublished = 10;
string createdAt = 11;
string updatedAt = 12;
string variant = 13;
}
message ListAppReleasesRequest {
@@ -52,6 +53,7 @@ message CreateAppReleaseRequest {
string sha256 = 7;
optional string releaseNotes = 8;
optional string createdById = 9;
optional string variant = 10;
}
message UpdateAppReleaseRequest {
@@ -76,11 +78,13 @@ message CheckAppUpdateRequest {
message CheckAppUpdateResponse {
bool updateAvailable = 1;
optional AppRelease latest = 2;
repeated AppRelease variants = 3;
}
message ResolveAppReleaseDownloadRequest {
string platform = 1;
optional string releaseId = 2;
optional string variant = 3;
}
message AppReleaseDownloadResponse {