SHA256
WIP: добавить MVP загрузки вложений в Cloudflare R2
Работа ещё не готова: предпросмотр публичных R2-вложений в UI пока не завершён.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { preparePublicFile, R2_MAX_FILE_BYTES } from './file-preparation-service.js';
|
||||
import { importPkcs8Ed25519, signBase64 } from './crypto-utils.js';
|
||||
import { sha256HexFromArrayBuffer, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { loadSessionMaterial } from './key-vault.js';
|
||||
@@ -73,7 +74,8 @@ async function createUploadContext({ login, sessionId, wsUrl }) {
|
||||
};
|
||||
}
|
||||
|
||||
export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus = null } = {}) {
|
||||
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'));
|
||||
|
||||
@@ -155,11 +157,13 @@ export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus
|
||||
}
|
||||
|
||||
export async function resolvePublicFileUrl({
|
||||
pr,
|
||||
sha256,
|
||||
authorLogin,
|
||||
solanaEndpoint,
|
||||
fallbackServerLogin = '',
|
||||
} = {}) {
|
||||
if (pr) return publicR2Url(pr);
|
||||
// Сначала – сервер, к которому подключены сейчас (у большинства читателей он же сервер автора),
|
||||
// затем сервер сборки по умолчанию; только потом ищем сервер автора через его PDA.
|
||||
const nearbyBases = [...new Set([state.entrySettings?.shineServerHttp, DEFAULT_SHINE_SERVER_HTTP]
|
||||
@@ -185,3 +189,50 @@ export async function resolvePublicFileUrl({
|
||||
accessServerCache.set(cacheKey, { atMs: Date.now(), httpBase: resolved.httpBase });
|
||||
return publicFileUrl(resolved.httpBase, sha256);
|
||||
}
|
||||
|
||||
/** Uploads one public attachment directly from the browser to Cloudflare R2. */
|
||||
async function uploadR2PublicFile({ file, login, sessionId, wsUrl, onStatus }) {
|
||||
if (!(file instanceof File) || file.size < 1) throw new Error('Выберите непустой файл');
|
||||
if (file.size > R2_MAX_FILE_BYTES) throw new Error('Превышен лимит 500 МиБ');
|
||||
onStatus?.('Подготовка файла…');
|
||||
const prepared = await preparePublicFile(file);
|
||||
const context = await createUploadContext({ login, sessionId, wsUrl });
|
||||
const timeMs = Date.now();
|
||||
const preimage = `PUBLIC_R2_PREPARE_V1:${context.sessionId}:${prepared.pr}:${prepared.size}:${prepared.mm}:${timeMs}`;
|
||||
const signature = await signBase64(context.privateKey, preimage);
|
||||
onStatus?.('Проверка файла в R2…');
|
||||
const response = await fetch(`${context.serverBase}/api/files/prepare`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Shine-Session-Id': context.sessionId,
|
||||
'X-Shine-Time-Ms': String(timeMs),
|
||||
'X-Shine-Signature': signature,
|
||||
},
|
||||
body: JSON.stringify({ pr: prepared.pr, size: prepared.size, mm: prepared.mm }),
|
||||
});
|
||||
if (!response.ok) throw new Error((await readErrorMessage(response)) || `R2 prepare HTTP ${response.status}`);
|
||||
const payload = await response.json();
|
||||
if (!payload.exists) {
|
||||
if (!payload.uploadUrl) throw new Error('Сервер не предоставил адрес загрузки');
|
||||
onStatus?.('Загрузка в Cloudflare R2…');
|
||||
const put = await fetch(payload.uploadUrl, {
|
||||
method: 'PUT',
|
||||
headers: payload.requiredHeaders || { 'Content-Type': prepared.mm, 'If-None-Match': '*' },
|
||||
body: file,
|
||||
});
|
||||
if (!put.ok && put.status !== 412) throw new Error(`Cloudflare R2: HTTP ${put.status}`);
|
||||
if (put.status === 412) {
|
||||
const check = await fetch(payload.fileUrl, { method: 'HEAD', cache: 'no-store' });
|
||||
if (!check.ok || Number(check.headers.get('Content-Length')) !== file.size) throw new Error('Конфликт при загрузке объекта R2');
|
||||
}
|
||||
}
|
||||
return { v: 1, name: prepared.name, size: prepared.size, pr: prepared.pr, mm: prepared.mm,
|
||||
ar: '', uploadedAtMs: Date.now(), alreadyExists: Boolean(payload.exists) };
|
||||
}
|
||||
|
||||
export function publicR2Url(pr) {
|
||||
const root = String(pr || '').trim();
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(root)) throw new Error('Некорректный Pieces Root');
|
||||
return `https://files.shineup.me/${root}`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user