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

View File

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

View File

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

View File

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

View File

@@ -1734,6 +1734,7 @@ export interface AppRelease {
platform: AppReleasePlatform; platform: AppReleasePlatform;
version: string; version: string;
versionCode: number; versionCode: number;
variant: string;
fileName: string; fileName: string;
storageKey: string; storageKey: string;
fileSize: string; fileSize: string;
@@ -1747,6 +1748,7 @@ export interface AppRelease {
export interface AppUpdateCheckResponse { export interface AppUpdateCheckResponse {
updateAvailable: boolean; updateAvailable: boolean;
latest?: AppRelease; latest?: AppRelease;
variants?: AppRelease[];
} }
export async function fetchPublicAppReleases(platform?: AppReleasePlatform) { 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(); 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) { export async function fetchAdminAppReleases(token: string, platform?: AppReleasePlatform) {
@@ -1784,6 +1788,7 @@ export async function uploadAdminAppRelease(
platform: AppReleasePlatform; platform: AppReleasePlatform;
version: string; version: string;
versionCode: number; versionCode: number;
variant?: string;
releaseNotes?: string; releaseNotes?: string;
file: File; file: File;
}, },
@@ -1793,6 +1798,9 @@ export async function uploadAdminAppRelease(
formData.append('platform', payload.platform); formData.append('platform', payload.platform);
formData.append('version', payload.version.trim()); formData.append('version', payload.version.trim());
formData.append('versionCode', String(payload.versionCode)); formData.append('versionCode', String(payload.versionCode));
if (payload.variant?.trim()) {
formData.append('variant', payload.variant.trim());
}
if (payload.releaseNotes?.trim()) { if (payload.releaseNotes?.trim()) {
formData.append('releaseNotes', 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', 'content-disposition',
'x-release-version', 'x-release-version',
'x-release-version-code', 'x-release-version-code',
'x-release-variant',
'x-release-sha256', 'x-release-sha256',
'cache-control' 'cache-control'
] as const; ] as const;
@@ -22,9 +23,10 @@ export async function proxyReleaseDownload(
releaseId?: string releaseId?: string
) { ) {
const apiBase = resolveServerApiBase(request); const apiBase = resolveServerApiBase(request);
const variant = request.nextUrl.searchParams.get('variant');
const path = releaseId const path = releaseId
? `/releases/download/${platform}/${releaseId}` ? `/releases/download/${platform}/${releaseId}`
: `/releases/download/${platform}`; : `/releases/download/${platform}${variant ? `?variant=${encodeURIComponent(variant)}` : ''}`;
const upstream = await fetch(`${apiBase}${path}`, { const upstream = await fetch(`${apiBase}${path}`, {
method: 'GET', 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 platform AppReleasePlatform
version String version String
versionCode Int versionCode Int
variant String @default("universal")
fileName String fileName String
storageKey String @unique storageKey String @unique
fileSize BigInt fileSize BigInt
@@ -61,9 +62,9 @@ model AppRelease {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@unique([platform, version]) @@unique([platform, versionCode, variant])
@@unique([platform, versionCode])
@@index([platform, isPublished, createdAt]) @@index([platform, isPublished, createdAt])
@@index([platform, versionCode, isPublished])
} }
model User { model User {

View File

@@ -4,7 +4,16 @@ import { AppReleasePlatform, Prisma } from '../generated/prisma/client';
import { PrismaService } from '../infra/prisma.service'; import { PrismaService } from '../infra/prisma.service';
import { MinioService } from '../infra/minio.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() @Injectable()
export class AppReleaseService { export class AppReleaseService {
@@ -13,6 +22,36 @@ export class AppReleaseService {
private readonly minio: MinioService 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 { private normalizePlatform(platform: string): AppReleasePlatform {
const normalized = platform.trim().toUpperCase(); const normalized = platform.trim().toUpperCase();
if (normalized === 'ANDROID' || normalized === 'WINDOWS') { if (normalized === 'ANDROID' || normalized === 'WINDOWS') {
@@ -26,6 +65,7 @@ export class AppReleaseService {
platform: AppReleasePlatform; platform: AppReleasePlatform;
version: string; version: string;
versionCode: number; versionCode: number;
variant: string;
fileName: string; fileName: string;
storageKey: string; storageKey: string;
fileSize: bigint; fileSize: bigint;
@@ -40,6 +80,7 @@ export class AppReleaseService {
platform: release.platform, platform: release.platform,
version: release.version, version: release.version,
versionCode: release.versionCode, versionCode: release.versionCode,
variant: release.variant,
fileName: release.fileName, fileName: release.fileName,
storageKey: release.storageKey, storageKey: release.storageKey,
fileSize: release.fileSize.toString(), 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 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, '_'); 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) { async listReleases(platform?: string) {
@@ -84,7 +148,7 @@ export class AppReleaseService {
: {}; : {};
const releases = await this.prisma.appRelease.findMany({ const releases = await this.prisma.appRelease.findMany({
where, 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)) }; return { releases: releases.map((release) => this.toResponse(release)) };
} }
@@ -96,7 +160,7 @@ export class AppReleaseService {
}; };
const releases = await this.prisma.appRelease.findMany({ const releases = await this.prisma.appRelease.findMany({
where, 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)) }; return { releases: releases.map((release) => this.toResponse(release)) };
} }
@@ -105,6 +169,7 @@ export class AppReleaseService {
platform: string; platform: string;
version: string; version: string;
versionCode: number; versionCode: number;
variant?: string;
fileName: string; fileName: string;
storageKey: string; storageKey: string;
fileSize: string | number | bigint; fileSize: string | number | bigint;
@@ -114,6 +179,7 @@ export class AppReleaseService {
}) { }) {
const platform = this.normalizePlatform(input.platform); const platform = this.normalizePlatform(input.platform);
const version = input.version.trim(); const version = input.version.trim();
const variant = this.normalizeVariant(input.variant, input.fileName);
if (!/^\d+(?:\.\d+){0,3}(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) { if (!/^\d+(?:\.\d+){0,3}(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
throw new BadRequestException('Версия должна быть в формате semver, например 1.2.3'); throw new BadRequestException('Версия должна быть в формате semver, например 1.2.3');
} }
@@ -142,6 +208,7 @@ export class AppReleaseService {
platform, platform,
version, version,
versionCode: input.versionCode, versionCode: input.versionCode,
variant,
fileName: input.fileName.trim(), fileName: input.fileName.trim(),
storageKey: input.storageKey, storageKey: input.storageKey,
fileSize: BigInt(input.fileSize), fileSize: BigInt(input.fileSize),
@@ -153,7 +220,9 @@ export class AppReleaseService {
return this.toResponse(release); return this.toResponse(release);
} catch (error) { } catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') { if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
throw new BadRequestException('Релиз с такой версией или кодом версии уже существует для этой платформы'); throw new BadRequestException(
`Сборка «${variant}» для версии ${version} (код ${input.versionCode}) уже загружена. Выберите другой вариант или удалите существующий файл.`
);
} }
throw error; throw error;
} }
@@ -183,10 +252,13 @@ export class AppReleaseService {
async getLatestRelease(platform: string) { async getLatestRelease(platform: string) {
const normalized = this.normalizePlatform(platform); const normalized = this.normalizePlatform(platform);
const release = await this.prisma.appRelease.findFirst({ const versionCode = await this.getLatestPublishedVersionCode(normalized);
where: { platform: normalized, isPublished: true }, if (versionCode === null) {
orderBy: [{ versionCode: 'desc' }, { createdAt: 'desc' }] throw new NotFoundException('Опубликованный релиз для этой платформы не найден');
}); }
const variants = await this.listPublishedVariants(normalized, versionCode);
const release = this.preferVariant(variants);
if (!release) { if (!release) {
throw new NotFoundException('Опубликованный релиз для этой платформы не найден'); throw new NotFoundException('Опубликованный релиз для этой платформы не найден');
} }
@@ -194,29 +266,75 @@ export class AppReleaseService {
} }
async checkUpdate(platform: string, versionCode: number) { async checkUpdate(platform: string, versionCode: number) {
const latest = await this.getLatestRelease(platform); const normalized = this.normalizePlatform(platform);
const updateAvailable = versionCode < latest.versionCode; 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 { return {
updateAvailable, updateAvailable: true,
latest: updateAvailable ? latest : undefined 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 normalized = this.normalizePlatform(platform);
const release = releaseId
? await this.prisma.appRelease.findFirst({ if (releaseId) {
const release = await this.prisma.appRelease.findFirst({
where: { id: releaseId, platform: normalized, isPublished: true } where: { id: releaseId, platform: normalized, isPublished: true }
})
: await this.prisma.appRelease.findFirst({
where: { platform: normalized, isPublished: true },
orderBy: [{ versionCode: 'desc' }, { createdAt: 'desc' }]
}); });
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) { if (!release) {
throw new NotFoundException('Файл релиза не найден'); 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 { return {
storageKey: release.storageKey, storageKey: release.storageKey,
fileName: release.fileName, fileName: release.fileName,
@@ -224,7 +342,8 @@ export class AppReleaseService {
fileSize: release.fileSize.toString(), fileSize: release.fileSize.toString(),
sha256: release.sha256, sha256: release.sha256,
version: release.version, version: release.version,
versionCode: release.versionCode versionCode: release.versionCode,
variant: release.variant
}; };
} }
} }

View File

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

View File

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