Обновить публичные идентификаторы файлов

This commit is contained in:
AidarKC
2026-11-15 15:45:33 +03:00
parent ac6a2e5b3f
commit 4a6e072946
65 changed files with 292 additions and 457 deletions
+10 -78
View File
@@ -2,7 +2,7 @@ import { t } from '../i18n/index.js';
import { preparePublicFile, R2_MAX_FILE_BYTES } from './file-preparation-service.js';
import { validatePublicPiecesRoot } from './public-pieces-root.js';
import { importPkcs8Ed25519, signBase64 } from './crypto-utils.js';
import { sha256HexFromArrayBuffer, validateSha256Hex } from './arweave-file-service.js';
import { validateSha256Hex } from './arweave-file-service.js';
import { loadSessionMaterial } from './key-vault.js';
import {
DEFAULT_SHINE_SERVER_HTTP,
@@ -75,86 +75,18 @@ async function createUploadContext({ login, sessionId, wsUrl }) {
};
}
/** Avatars share the same PR/Base58 R2 namespace and upload protocol as other public files. */
export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus = null, purpose = 'attachment' } = {}) {
if (purpose !== 'avatar') return uploadR2PublicFile({ file, login, sessionId, wsUrl, onStatus });
if (!(file instanceof File)) throw new Error(t('remaining.file_upload.no_file_selected'));
if (Number(file.size || 0) <= 0) throw new Error(t('remaining.file_upload.cannot_upload_an_empty_file'));
onStatus?.(t('remaining.file_upload.calculating_sha_256'));
const bytes = await file.arrayBuffer();
const sha256 = await sha256HexFromArrayBuffer(bytes);
const context = await createUploadContext({ login, sessionId, wsUrl });
const url = publicFileUrl(context.serverBase, sha256);
onStatus?.(t('remaining.file_upload.checking_whether_the_file_is_on_the_server'));
try {
const existing = await fetch(url, { method: 'HEAD', cache: 'no-store' });
if (existing.ok) {
const storedSize = Number(existing.headers.get('Content-Length') || -1);
if (storedSize < 0 || storedSize === file.size) {
return {
v: 1,
name: String(file.name || 'file'),
size: Number(file.size),
sha256,
ar: '',
uploadedAtMs: Date.now(),
alreadyExists: true,
};
}
}
} catch {
// HEAD — только оптимизация. PUT сам проверит hash и дедупликацию.
if (purpose === 'avatar' && (!(file instanceof Blob) || !file.size || file.size > 10 * 1024 * 1024
|| !['image/webp', 'image/jpeg'].includes(file.type))) {
throw new Error('Аватар должен быть оптимизированным WebP/JPEG размером до 10 МиБ');
}
return uploadR2PublicFile({ file, login, sessionId, wsUrl, onStatus });
}
const timeMs = Date.now();
const signature = await signBase64(context.privateKey, uploadPreimage({
sessionId: context.sessionId,
sha256,
size: file.size,
timeMs,
}));
onStatus?.(t('remaining.file_upload.uploading_to_access_server'));
let response;
try {
response = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/octet-stream',
'X-Shine-Session-Id': context.sessionId,
'X-Shine-Time-Ms': String(timeMs),
'X-Shine-Content-Length': String(file.size),
'X-Shine-Signature': signature,
},
body: bytes,
cache: 'no-store',
});
} catch (error) {
throw new Error(`Не удалось загрузить файл на сервер доступа: ${error?.message || 'network error'}`);
}
if (!response.ok) {
const detail = await readErrorMessage(response);
throw new Error(detail || `Сервер отклонил файл (HTTP ${response.status}).`);
}
let alreadyExists = false;
try {
const payload = await response.clone().json();
alreadyExists = Boolean(payload?.alreadyExists);
} catch {
// Успешного HTTP достаточно.
}
return {
v: 1,
name: String(file.name || 'file'),
size: Number(file.size),
sha256,
ar: '',
uploadedAtMs: Date.now(),
alreadyExists,
};
/** Canonical public object URL; avatars do not have a special prefix. */
export function avatarR2Url(pr) {
return publicR2Url(pr);
}
export async function resolvePublicFileUrl({