After adding the fonctionality for apk publish3

This commit is contained in:
Your Name 2026-10-30 19:19:21 +02:00
parent a838e3d5c8
commit 8cdbf38f5a
8 changed files with 183 additions and 24 deletions

View File

@ -216,10 +216,25 @@ export async function listReleases(filters: {
return { items: rows.map(mapRelease), total };
}
export async function findByPlatformChannelVersionCode(
platform: MobilePlatform,
channel: MobileChannel,
versionCode: number
): Promise<MobileAppRelease | null> {
const rows = await query<ReleaseRow[]>(
`SELECT ${RELEASE_COLS} FROM mobile_app_releases
WHERE platform = $1 AND channel = $2 AND version_code = $3
LIMIT 1`,
[platform, channel, versionCode]
);
return rows[0] ? mapRelease(rows[0]) : null;
}
export async function updateRelease(
id: string,
patch: Partial<{
versionName: string;
versionCode: number;
previousVersionName: string | null;
whatsNew: string;
bugFixes: string;
@ -237,24 +252,26 @@ export async function updateRelease(
const rows = await query<ReleaseRow[]>(
`UPDATE mobile_app_releases SET
version_name = COALESCE($2, version_name),
previous_version_name = CASE WHEN $3::boolean THEN $4 ELSE previous_version_name END,
whats_new = COALESCE($5, whats_new),
bug_fixes = COALESCE($6, bug_fixes),
update_policy = COALESCE($7, update_policy),
rollout_percent = COALESCE($8, rollout_percent),
status = COALESCE($9, status),
package_name = CASE WHEN $10::boolean THEN $11 ELSE package_name END,
storage_key = CASE WHEN $12::boolean THEN $13 ELSE storage_key END,
file_size_bytes = CASE WHEN $14::boolean THEN $15 ELSE file_size_bytes END,
sha256 = CASE WHEN $16::boolean THEN $17 ELSE sha256 END,
signing_cert_sha256 = CASE WHEN $18::boolean THEN $19 ELSE signing_cert_sha256 END,
published_at = CASE WHEN $20::boolean THEN $21 ELSE published_at END,
version_code = COALESCE($3, version_code),
previous_version_name = CASE WHEN $4::boolean THEN $5 ELSE previous_version_name END,
whats_new = COALESCE($6, whats_new),
bug_fixes = COALESCE($7, bug_fixes),
update_policy = COALESCE($8, update_policy),
rollout_percent = COALESCE($9, rollout_percent),
status = COALESCE($10, status),
package_name = CASE WHEN $11::boolean THEN $12 ELSE package_name END,
storage_key = CASE WHEN $13::boolean THEN $14 ELSE storage_key END,
file_size_bytes = CASE WHEN $15::boolean THEN $16 ELSE file_size_bytes END,
sha256 = CASE WHEN $17::boolean THEN $18 ELSE sha256 END,
signing_cert_sha256 = CASE WHEN $19::boolean THEN $20 ELSE signing_cert_sha256 END,
published_at = CASE WHEN $21::boolean THEN $22 ELSE published_at END,
updated_at = NOW()
WHERE id = $1
RETURNING ${RELEASE_COLS}`,
[
id,
patch.versionName ?? null,
patch.versionCode ?? null,
patch.previousVersionName !== undefined,
patch.previousVersionName ?? null,
patch.whatsNew ?? null,

View File

@ -659,7 +659,20 @@ router.post(
requireRoles('admin'),
requirePermissions('admin.mobile_releases.manage'),
validateParams(mobileReleaseIdParamSchema),
apkUpload.single('file'),
(req, res, next) => {
apkUpload.single('file')(req, res, (err: unknown) => {
if (!err) {
next();
return;
}
const multerErr = err as { code?: string; message?: string };
if (multerErr.code === 'LIMIT_FILE_SIZE') {
res.status(413).json({ error: 'APK exceeds maximum upload size' });
return;
}
res.status(400).json({ error: multerErr.message || 'APK upload failed' });
});
},
mobileAppReleaseController.adminUploadApk
);
router.post(

View File

@ -199,12 +199,22 @@ export async function attachApk(id: string, uploadedAbsolutePath: string): Promi
);
}
// Draft/pending: adopt APK versionCode/name when they differ (admin often mistypes the form).
let nextVersionCode = release.versionCode;
if (parsed.versionCode !== release.versionCode) {
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
throw new MobileReleaseError(
400,
`APK versionCode ${parsed.versionCode} does not match release versionCode ${release.versionCode}`
const conflict = await repo.findByPlatformChannelVersionCode(
release.platform,
release.channel,
parsed.versionCode
);
if (conflict && conflict.id !== release.id) {
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
throw new MobileReleaseError(
409,
`APK versionCode ${parsed.versionCode} is already used by another release (${conflict.versionName})`
);
}
nextVersionCode = parsed.versionCode;
}
const expectedCert = config.mobileReleases.expectedCertSha256;
@ -227,6 +237,7 @@ export async function attachApk(id: string, uploadedAbsolutePath: string): Promi
const updated = await repo.updateRelease(id, {
packageName: parsed.packageName,
versionName: parsed.versionName || release.versionName,
versionCode: nextVersionCode,
storageKey: stagingKey,
fileSizeBytes: stat.size,
sha256: fileSha,

View File

@ -12,6 +12,7 @@ import {
DialogTitle,
FormControl,
InputLabel,
LinearProgress,
MenuItem,
Select,
Stack,
@ -46,6 +47,7 @@ import {
uploadMobileApk,
type MobileAppRelease,
type MobileUpdatePolicy,
type UploadProgress,
} from './api/mobileVersionsApi';
function formatBytes(n: number | null): string {
@ -55,6 +57,15 @@ function formatBytes(n: number | null): string {
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
}
function formatEta(seconds: number | null, t: (k: string, o?: Record<string, unknown>) => string): string {
if (seconds == null) return t('admin.mobileVersions.etaCalculating');
if (seconds < 5) return t('admin.mobileVersions.etaAlmostDone');
if (seconds < 60) return t('admin.mobileVersions.etaSeconds', { count: seconds });
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return t('admin.mobileVersions.etaMinutes', { minutes: m, seconds: s });
}
function statusColor(status: string): 'default' | 'success' | 'warning' | 'error' | 'info' {
switch (status) {
case 'published':
@ -91,7 +102,15 @@ const emptyCreate: CreateForm = {
};
function errMsg(e: unknown, fallback: string): string {
return (e as { response?: { data?: { error?: string } } })?.response?.data?.error || fallback;
const ax = e as {
response?: { status?: number; data?: { error?: string; message?: string } };
message?: string;
code?: string;
};
if (ax.response?.status === 413) {
return 'APK too large for the server (nginx/body limit).';
}
return ax.response?.data?.error || ax.response?.data?.message || ax.message || fallback;
}
export function MobileVersionsAdminPage() {
@ -108,6 +127,8 @@ export function MobileVersionsAdminPage() {
const [form, setForm] = useState<CreateForm>(emptyCreate);
const [selected, setSelected] = useState<MobileAppRelease | null>(null);
const [error, setError] = useState<string | null>(null);
const [uploadProgress, setUploadProgress] = useState<UploadProgress | null>(null);
const [uploadPhase, setUploadPhase] = useState<'idle' | 'uploading' | 'processing'>('idle');
const [settingsForm, setSettingsForm] = useState({
minSupportedVersionCode: '1',
checkIntervalSeconds: '21600',
@ -169,7 +190,19 @@ export function MobileVersionsAdminPage() {
patch?: Parameters<typeof updateMobileRelease>[1];
}) => {
const { action, id, file, patch } = args;
if (action === 'upload' && file) return uploadMobileApk(id, file);
if (action === 'upload' && file) {
setUploadPhase('uploading');
setUploadProgress({ percent: 0, loaded: 0, total: file.size, etaSeconds: null });
try {
const result = await uploadMobileApk(id, file, (p) => {
setUploadProgress(p);
if (p.percent >= 100) setUploadPhase('processing');
});
return result;
} finally {
/* phase cleared in onSettled */
}
}
if (action === 'submit') return submitMobileRelease(id);
if (action === 'publish') return publishMobileRelease(id);
if (action === 'suspend') return suspendMobileRelease(id);
@ -183,6 +216,10 @@ export function MobileVersionsAdminPage() {
invalidate();
},
onError: (e: unknown) => setError(errMsg(e, t('admin.mobileVersions.actionFailed'))),
onSettled: () => {
setUploadPhase('idle');
setUploadProgress(null);
},
});
const settingsMut = useMutation({
@ -340,6 +377,31 @@ export function MobileVersionsAdminPage() {
</Typography>
<PermissionGate permission="admin.mobile_releases.manage">
{uploadPhase !== 'idle' && uploadProgress && (
<Box sx={{ mb: 2, p: 1.5, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
<Stack direction="row" justifyContent="space-between" sx={{ mb: 0.75 }}>
<Typography variant="body2" sx={{ fontWeight: 700 }}>
{uploadPhase === 'processing'
? t('admin.mobileVersions.uploadProcessing')
: t('admin.mobileVersions.uploading')}
</Typography>
<Typography variant="body2" color="text.secondary">
{uploadProgress.percent}% · {formatBytes(uploadProgress.loaded)} /{' '}
{formatBytes(uploadProgress.total)}
</Typography>
</Stack>
<LinearProgress
variant={uploadPhase === 'processing' ? 'indeterminate' : 'determinate'}
value={uploadProgress.percent}
sx={{ height: 8, borderRadius: 999 }}
/>
<Typography variant="caption" color="text.secondary" sx={{ mt: 0.75, display: 'block' }}>
{uploadPhase === 'processing'
? t('admin.mobileVersions.uploadProcessingHint')
: formatEta(uploadProgress.etaSeconds, t)}
</Typography>
</Box>
)}
<Stack direction="row" flexWrap="wrap" gap={1}>
<input
ref={fileInputRef}
@ -348,7 +410,10 @@ export function MobileVersionsAdminPage() {
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) actionMut.mutate({ action: 'upload', id: detail.id, file });
if (file) {
setError(null);
actionMut.mutate({ action: 'upload', id: detail.id, file });
}
e.target.value = '';
}}
/>
@ -357,7 +422,9 @@ export function MobileVersionsAdminPage() {
disabled={!canManage || actionMut.isPending}
onClick={() => fileInputRef.current?.click()}
>
{t('admin.mobileVersions.uploadApk')}
{actionMut.isPending && uploadPhase !== 'idle'
? t('admin.mobileVersions.uploading')
: t('admin.mobileVersions.uploadApk')}
</Button>
<Button
variant="outlined"

View File

@ -58,6 +58,15 @@ export type MobileReleaseStats = {
eventCounts: Array<{ eventType: string; count: number }>;
};
export type UploadProgress = {
/** 0–100 */
percent: number;
loaded: number;
total: number;
/** Estimated remaining seconds; null when unknown */
etaSeconds: number | null;
};
export async function listMobileReleases(params?: {
status?: string;
search?: string;
@ -104,12 +113,31 @@ export async function updateMobileRelease(
return data;
}
export async function uploadMobileApk(id: string, file: File) {
export async function uploadMobileApk(
id: string,
file: File,
onProgress?: (p: UploadProgress) => void
) {
const form = new FormData();
form.append('file', file);
const startedAt = Date.now();
const { data } = await api.post<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}/apk`, form, {
headers: { 'Content-Type': 'multipart/form-data' },
timeout: 300_000,
timeout: 600_000,
maxBodyLength: Infinity,
maxContentLength: Infinity,
onUploadProgress: (evt) => {
if (!onProgress) return;
const total = evt.total && evt.total > 0 ? evt.total : file.size;
const loaded = evt.loaded ?? 0;
const percent = total > 0 ? Math.min(100, Math.round((loaded / total) * 100)) : 0;
const elapsedSec = (Date.now() - startedAt) / 1000;
let etaSeconds: number | null = null;
if (loaded > 0 && percent < 100 && elapsedSec > 0.25) {
const rate = loaded / elapsedSec;
etaSeconds = Math.max(0, Math.round((total - loaded) / rate));
}
onProgress({ percent, loaded, total, etaSeconds });
},
});
return data;
}

View File

@ -1176,6 +1176,13 @@ export const en = {
whatsNew: "What's new",
bugFixes: 'Bug fixes',
uploadApk: 'Upload APK',
uploading: 'Uploading…',
uploadProcessing: 'Processing APK on server…',
uploadProcessingHint: 'Validating package, signature and checksum…',
etaCalculating: 'Estimating remaining time…',
etaAlmostDone: 'Almost done…',
etaSeconds: '~{{count}}s remaining',
etaMinutes: '~{{minutes}}m {{seconds}}s remaining',
submit: 'Submit for validation',
publish: 'Publish',
suspend: 'Suspend',

View File

@ -1194,6 +1194,13 @@ export const fr = {
whatsNew: 'Nouveautés',
bugFixes: 'Corrections',
uploadApk: 'Importer l’APK',
uploading: 'Téléversement…',
uploadProcessing: 'Traitement de l’APK sur le serveur…',
uploadProcessingHint: 'Validation du package, de la signature et de l’empreinte…',
etaCalculating: 'Estimation du temps restant…',
etaAlmostDone: 'Presque terminé…',
etaSeconds: '~{{count}} s restantes',
etaMinutes: '~{{minutes}} min {{seconds}} s restantes',
submit: 'Soumettre à validation',
publish: 'Publier',
suspend: 'Suspendre',

View File

@ -23,6 +23,15 @@ api.interceptors.request.use((config) => {
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
// Let the browser set multipart boundary — a forced JSON Content-Type breaks file uploads.
if (typeof FormData !== 'undefined' && config.data instanceof FormData) {
const headers = config.headers as { delete?: (k: string) => void; [k: string]: unknown };
if (typeof headers.delete === 'function') {
headers.delete('Content-Type');
} else {
delete headers['Content-Type'];
}
}
try {
config.headers['X-Support-Visitor-Token'] = getOrCreateVisitorToken();
} catch {