SHA256
Полностью поддерживает английский язык
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
buildArweaveDataUrl,
|
||||
sha256HexFromArrayBuffer,
|
||||
@@ -14,7 +15,7 @@ const MAX_BYTES = 50 * 1024 * 1024;
|
||||
function openDb() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof indexedDB === 'undefined') {
|
||||
reject(new Error('IndexedDB недоступен'));
|
||||
reject(new Error(t('remaining.avatar_errors.indexeddb_is_unavailable')));
|
||||
return;
|
||||
}
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
@@ -25,7 +26,7 @@ function openDb() {
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error || new Error('Ошибка открытия IndexedDB'));
|
||||
request.onerror = () => reject(request.error || new Error(t('remaining.avatar_errors.could_not_open_indexeddb')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -37,7 +38,7 @@ async function withStore(mode, runner) {
|
||||
const store = tx.objectStore(STORE);
|
||||
const result = runner(store, tx, resolve, reject);
|
||||
if (result !== undefined) resolve(result);
|
||||
tx.onerror = () => reject(tx.error || new Error('Ошибка транзакции IndexedDB'));
|
||||
tx.onerror = () => reject(tx.error || new Error(t('remaining.avatar_errors.indexeddb_transaction_failed')));
|
||||
});
|
||||
} finally {
|
||||
db.close();
|
||||
@@ -48,7 +49,7 @@ async function getRecord(txId) {
|
||||
return withStore('readonly', (store, _tx, resolve, reject) => {
|
||||
const req = store.get(txId);
|
||||
req.onsuccess = () => resolve(req.result || null);
|
||||
req.onerror = () => reject(req.error || new Error('Ошибка чтения кэша аватарки'));
|
||||
req.onerror = () => reject(req.error || new Error(t('remaining.avatar_errors.could_not_read_avatar_cache')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -56,7 +57,7 @@ async function putRecord(record) {
|
||||
return withStore('readwrite', (store, tx, resolve, reject) => {
|
||||
store.put(record);
|
||||
tx.oncomplete = () => resolve(true);
|
||||
tx.onerror = () => reject(tx.error || new Error('Ошибка записи кэша аватарки'));
|
||||
tx.onerror = () => reject(tx.error || new Error(t('remaining.avatar_errors.could_not_write_avatar_cache')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -72,7 +73,7 @@ async function getAllRecords() {
|
||||
return withStore('readonly', (store, _tx, resolve, reject) => {
|
||||
const req = store.getAll();
|
||||
req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []);
|
||||
req.onerror = () => reject(req.error || new Error('Ошибка чтения списка кэша аватарок'));
|
||||
req.onerror = () => reject(req.error || new Error(t('remaining.avatar_errors.could_not_read_avatar_cache_entries')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -81,7 +82,7 @@ async function deleteRecords(keys) {
|
||||
await withStore('readwrite', (store, tx, resolve, reject) => {
|
||||
keys.forEach((key) => store.delete(key));
|
||||
tx.oncomplete = () => resolve(true);
|
||||
tx.onerror = () => reject(tx.error || new Error('Ошибка очистки кэша аватарок'));
|
||||
tx.onerror = () => reject(tx.error || new Error(t('remaining.avatar_errors.could_not_clear_avatar_cache')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -208,7 +209,7 @@ async function getBlobFromCacheOrGateway({ gateway, txId, expectedSha256Hex = ''
|
||||
export async function getCachedAvatarObjectUrl({ gateway, txId, expectedSha256Hex = '' }) {
|
||||
const cleanTxId = String(txId || '').trim();
|
||||
if (!validateArweaveTxId(cleanTxId)) {
|
||||
throw new Error('Некорректный Transaction ID Arweave');
|
||||
throw new Error(t('remaining.avatar_errors.invalid_arweave_transaction_id'));
|
||||
}
|
||||
const blob = await getBlobFromCacheOrGateway({
|
||||
gateway,
|
||||
@@ -222,6 +223,6 @@ export async function clearAvatarCache() {
|
||||
await withStore('readwrite', (store, tx, resolve, reject) => {
|
||||
store.clear();
|
||||
tx.oncomplete = () => resolve(true);
|
||||
tx.onerror = () => reject(tx.error || new Error('Ошибка очистки кэша аватарок'));
|
||||
tx.onerror = () => reject(tx.error || new Error(t('remaining.avatar_errors.could_not_clear_avatar_cache')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
const DEFAULT_ARWEAVE_GATEWAY = 'https://arweave.net';
|
||||
const WINSTON_PER_AR = 1_000_000_000_000n;
|
||||
const MAX_AVATAR_SOURCE_BYTES = 10 * 1024 * 1024;
|
||||
@@ -16,10 +17,10 @@ function normalizeGateway(rawGateway) {
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
} catch {
|
||||
throw new Error('Некорректный Arweave gateway URL');
|
||||
throw new Error(t('remaining.arweave_file_errors.invalid_arweave_gateway_url'));
|
||||
}
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error('Arweave gateway должен использовать http или https');
|
||||
throw new Error(t('remaining.arweave_file_errors.arweave_gateway_must_use_http_or_https'));
|
||||
}
|
||||
const normalized = `${parsed.protocol}//${parsed.host}${parsed.pathname}`.replace(/\/+$/g, '');
|
||||
return normalized || DEFAULT_ARWEAVE_GATEWAY;
|
||||
@@ -30,11 +31,11 @@ function parseGatewayForArweaveInit(gateway) {
|
||||
try {
|
||||
parsed = new URL(gateway);
|
||||
} catch {
|
||||
throw new Error('Некорректный Arweave gateway URL');
|
||||
throw new Error(t('remaining.arweave_file_errors.invalid_arweave_gateway_url'));
|
||||
}
|
||||
const protocol = parsed.protocol.replace(':', '');
|
||||
if (protocol !== 'http' && protocol !== 'https') {
|
||||
throw new Error('Arweave gateway должен использовать http или https');
|
||||
throw new Error(t('remaining.arweave_file_errors.arweave_gateway_must_use_http_or_https'));
|
||||
}
|
||||
const port = parsed.port
|
||||
? Number(parsed.port)
|
||||
@@ -79,7 +80,7 @@ async function createBitmapWithFallback(file) {
|
||||
const image = await new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = () => reject(new Error('Не удалось прочитать изображение'));
|
||||
img.onerror = () => reject(new Error(t('remaining.arweave_files.could_not_read_image')));
|
||||
img.src = url;
|
||||
});
|
||||
return image;
|
||||
@@ -109,7 +110,7 @@ export function validateSha256Hex(sha256Hex) {
|
||||
}
|
||||
|
||||
export async function sha256HexFromArrayBuffer(buffer) {
|
||||
if (!(buffer instanceof ArrayBuffer)) throw new Error('Некорректные данные для SHA256');
|
||||
if (!(buffer instanceof ArrayBuffer)) throw new Error(t('remaining.arweave_file_errors.invalid_data_for_sha_256'));
|
||||
const digest = await crypto.subtle.digest('SHA-256', buffer);
|
||||
return bytesToHex(new Uint8Array(digest));
|
||||
}
|
||||
@@ -117,12 +118,12 @@ export async function sha256HexFromArrayBuffer(buffer) {
|
||||
export function buildArweaveAvatarValue(txId, sha256Hex = '') {
|
||||
const cleanTxId = String(txId || '').trim();
|
||||
if (!validateArweaveTxId(cleanTxId)) {
|
||||
throw new Error('Некорректный Transaction ID Arweave');
|
||||
throw new Error(t('remaining.arweave_file_errors.invalid_arweave_transaction_id'));
|
||||
}
|
||||
const cleanSha = String(sha256Hex || '').trim().toLowerCase();
|
||||
if (!cleanSha) return `AR:${cleanTxId}`;
|
||||
if (!validateSha256Hex(cleanSha)) {
|
||||
throw new Error('Некорректный SHA256 хэш аватара');
|
||||
throw new Error(t('remaining.arweave_file_errors.invalid_avatar_sha_256_hash'));
|
||||
}
|
||||
return `SHA256:${cleanSha},AR:${cleanTxId}`;
|
||||
}
|
||||
@@ -158,7 +159,7 @@ export function buildArweaveDataUrl({ gateway, txId }) {
|
||||
const normalizedGateway = normalizeGateway(gateway);
|
||||
const cleanTxId = String(txId || '').trim();
|
||||
if (!validateArweaveTxId(cleanTxId)) {
|
||||
throw new Error('Некорректный Transaction ID Arweave');
|
||||
throw new Error(t('remaining.arweave_file_errors.invalid_arweave_transaction_id'));
|
||||
}
|
||||
return `${normalizedGateway}/${cleanTxId}`;
|
||||
}
|
||||
@@ -167,7 +168,7 @@ export async function getArweaveUploadPrice({ gateway, byteLength }) {
|
||||
const normalizedGateway = normalizeGateway(gateway);
|
||||
const bytes = Number(byteLength);
|
||||
if (!Number.isInteger(bytes) || bytes <= 0) {
|
||||
throw new Error('Некорректный размер файла');
|
||||
throw new Error(t('remaining.arweave_file_errors.invalid_file_size'));
|
||||
}
|
||||
|
||||
const response = await fetch(`${normalizedGateway}/price/${bytes}`, { method: 'GET' });
|
||||
@@ -176,7 +177,7 @@ export async function getArweaveUploadPrice({ gateway, byteLength }) {
|
||||
throw new Error(`Не удалось получить цену загрузки (${response.status} ${response.statusText})`);
|
||||
}
|
||||
if (!/^\d+$/.test(raw)) {
|
||||
throw new Error('Arweave gateway вернул некорректную цену');
|
||||
throw new Error(t('remaining.arweave_file_errors.arweave_gateway_returned_an_invalid_price'));
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -193,13 +194,13 @@ export function isSupportedAvatarImageType(type) {
|
||||
|
||||
export function validateAvatarSourceFile(file) {
|
||||
if (!(file instanceof File)) {
|
||||
throw new Error('Выберите файл изображения.');
|
||||
throw new Error(t('remaining.arweave_files.select_an_image_file'));
|
||||
}
|
||||
if (!isSupportedAvatarImageType(file.type)) {
|
||||
throw new Error('Поддерживаются только JPEG, PNG или WebP.');
|
||||
throw new Error(t('remaining.arweave_files.only_jpeg_png_and_webp_files_are_supported'));
|
||||
}
|
||||
if (Number(file.size || 0) > MAX_AVATAR_SOURCE_BYTES) {
|
||||
throw new Error('Файл слишком большой. Максимум 10 MB.');
|
||||
throw new Error(t('remaining.arweave_files.file_too_large_maximum_size_10_mb'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,14 +211,14 @@ export async function prepareAvatarImageFile(file) {
|
||||
try {
|
||||
bitmap = await createBitmapWithFallback(file);
|
||||
} catch {
|
||||
throw new Error('Не удалось подготовить изображение.');
|
||||
throw new Error(t('remaining.arweave_files.could_not_process_the_image'));
|
||||
}
|
||||
|
||||
try {
|
||||
const originalWidth = Number(bitmap.width || 0);
|
||||
const originalHeight = Number(bitmap.height || 0);
|
||||
if (!originalWidth || !originalHeight) {
|
||||
throw new Error('Не удалось подготовить изображение.');
|
||||
throw new Error(t('remaining.arweave_files.could_not_process_the_image'));
|
||||
}
|
||||
|
||||
const scale = Math.min(1, MAX_AVATAR_SIDE_PX / Math.max(originalWidth, originalHeight));
|
||||
@@ -229,7 +230,7 @@ export async function prepareAvatarImageFile(file) {
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) {
|
||||
throw new Error('Не удалось подготовить изображение.');
|
||||
throw new Error(t('remaining.arweave_files.could_not_process_the_image'));
|
||||
}
|
||||
ctx.drawImage(bitmap, 0, 0, width, height);
|
||||
|
||||
@@ -242,7 +243,7 @@ export async function prepareAvatarImageFile(file) {
|
||||
blob = await canvasToBlob(canvas, contentType, AVATAR_QUALITY);
|
||||
}
|
||||
if (!blob) {
|
||||
throw new Error('Не удалось подготовить изображение.');
|
||||
throw new Error(t('remaining.arweave_files.could_not_process_the_image'));
|
||||
}
|
||||
|
||||
const optimizedFile = blobToFile(blob, fileName, contentType);
|
||||
@@ -261,7 +262,7 @@ export async function prepareAvatarImageFile(file) {
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error) throw error;
|
||||
throw new Error('Не удалось подготовить изображение.');
|
||||
throw new Error(t('remaining.arweave_files.could_not_process_the_image'));
|
||||
} finally {
|
||||
if (bitmap && typeof bitmap.close === 'function') {
|
||||
bitmap.close();
|
||||
@@ -301,10 +302,10 @@ export async function loadArweaveFileMetadata({ gateway, txId, maxBytes = MAX_AR
|
||||
|
||||
export async function uploadArweaveFile({ gateway, jwk, file, tags = [], shineType = 'avatar' }) {
|
||||
if (!jwk || typeof jwk !== 'object') {
|
||||
throw new Error('Arweave-кошелёк не инициализирован.');
|
||||
throw new Error(t('remaining.arweave_files.arweave_wallet_is_not_initialized'));
|
||||
}
|
||||
if (!(file instanceof File)) {
|
||||
throw new Error('Выберите файл.');
|
||||
throw new Error(t('remaining.arweave_files.select_a_file'));
|
||||
}
|
||||
|
||||
const normalizedGateway = normalizeGateway(gateway);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { formatNumber } from '../i18n/format.js';
|
||||
import { loadEncryptedUserSecrets, updateEncryptedUserSecrets } from './key-vault.js';
|
||||
import { extractEd25519Seed32FromStoredValue } from './client-key-utils.js';
|
||||
import { deriveArweaveWalletFromBlockchainKey32 } from './sawd-v1.js';
|
||||
@@ -15,10 +17,10 @@ function normalizeGateway(rawGateway) {
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
} catch {
|
||||
throw new Error('Некорректный Arweave gateway URL');
|
||||
throw new Error(t('remaining.arweave_wallet_errors.invalid_arweave_gateway_url'));
|
||||
}
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error('Arweave gateway должен использовать http или https');
|
||||
throw new Error(t('remaining.arweave_wallet_errors.arweave_gateway_must_use_http_or_https'));
|
||||
}
|
||||
const normalized = `${parsed.protocol}//${parsed.host}${parsed.pathname}`.replace(/\/+$/g, '');
|
||||
return normalized || DEFAULT_ARWEAVE_GATEWAY;
|
||||
@@ -29,11 +31,11 @@ function parseGatewayForArweaveInit(gateway) {
|
||||
try {
|
||||
parsed = new URL(gateway);
|
||||
} catch {
|
||||
throw new Error('Некорректный Arweave gateway URL');
|
||||
throw new Error(t('remaining.arweave_wallet_errors.invalid_arweave_gateway_url'));
|
||||
}
|
||||
const protocol = parsed.protocol.replace(':', '');
|
||||
if (protocol !== 'http' && protocol !== 'https') {
|
||||
throw new Error('Arweave gateway должен использовать http или https');
|
||||
throw new Error(t('remaining.arweave_wallet_errors.arweave_gateway_must_use_http_or_https'));
|
||||
}
|
||||
const port = parsed.port
|
||||
? Number(parsed.port)
|
||||
@@ -49,18 +51,18 @@ function parseArToWinston(amountAr) {
|
||||
const raw = String(amountAr ?? '').trim().replace(',', '.');
|
||||
const match = raw.match(/^(\d+)(?:\.(\d+))?$/);
|
||||
if (!match) {
|
||||
throw new Error('Сумма перевода должна быть числом');
|
||||
throw new Error(t('remaining.arweave_wallet.the_transfer_amount_must_be_a_number'));
|
||||
}
|
||||
|
||||
const intPart = BigInt(match[1] || '0');
|
||||
const frac = String(match[2] || '');
|
||||
if (frac.length > 12) {
|
||||
throw new Error('Слишком много знаков после запятой (максимум 12)');
|
||||
throw new Error(t('remaining.arweave_wallet.too_many_decimal_places_maximum_12'));
|
||||
}
|
||||
const fracPadded = `${frac}${'0'.repeat(12 - frac.length)}`;
|
||||
const winston = (intPart * WINSTON_PER_AR) + BigInt(fracPadded || '0');
|
||||
if (winston <= 0n) {
|
||||
throw new Error('Сумма перевода должна быть больше 0');
|
||||
throw new Error(t('remaining.arweave_wallet.the_transfer_amount_must_be_greater_than_zero'));
|
||||
}
|
||||
return winston.toString();
|
||||
}
|
||||
@@ -112,12 +114,12 @@ function normalizeExtraWallets(secrets) {
|
||||
|
||||
function parseJwkSecretString(secret) {
|
||||
const raw = String(secret || '').trim();
|
||||
if (!raw) throw new Error('Введите секрет Arweave-кошелька.');
|
||||
if (!raw) throw new Error(t('remaining.arweave_wallet.enter_your_arweave_wallet_secret'));
|
||||
|
||||
const tryParse = (value) => {
|
||||
const parsed = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('Некорректный JWK Arweave.');
|
||||
throw new Error(t('remaining.arweave_wallet.invalid_arweave_jwk'));
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
@@ -131,12 +133,12 @@ function parseJwkSecretString(secret) {
|
||||
try {
|
||||
return tryParse(atob(normalized));
|
||||
} catch {
|
||||
throw new Error('Секрет должен быть JSON JWK или base64url(JSON JWK).');
|
||||
throw new Error(t('remaining.arweave_wallet.the_secret_must_be_json_jwk_or_base64url_json_jwk'));
|
||||
}
|
||||
}
|
||||
|
||||
function validateArweaveJwk(jwk) {
|
||||
if (!jwk || typeof jwk !== 'object') throw new Error('Некорректный JWK Arweave.');
|
||||
if (!jwk || typeof jwk !== 'object') throw new Error(t('remaining.arweave_wallet.invalid_arweave_jwk'));
|
||||
['kty', 'e', 'n', 'd', 'p', 'q', 'dp', 'dq', 'qi'].forEach((key) => {
|
||||
if (!String(jwk[key] || '').trim()) throw new Error(`В JWK Arweave нет поля ${key}.`);
|
||||
});
|
||||
@@ -158,7 +160,7 @@ export async function getArweaveWalletChoices({ login, storagePwd, onStatus } =
|
||||
return [
|
||||
{
|
||||
id: 'derived-blockchain-key',
|
||||
label: 'Стандартный из ключа блокчейна',
|
||||
label: t('remaining.arweave_wallet.derived_from_blockchain_key'),
|
||||
address: derived.address,
|
||||
owner: derived.owner,
|
||||
jwk: derived.jwk,
|
||||
@@ -175,7 +177,7 @@ export async function getArweaveWalletChoices({ login, storagePwd, onStatus } =
|
||||
export async function addArweaveWalletSecret({ login, storagePwd, secret, label = '' } = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanPwd = String(storagePwd || '').trim();
|
||||
if (!cleanLogin || !cleanPwd) throw new Error('Нет активной сессии.');
|
||||
if (!cleanLogin || !cleanPwd) throw new Error(t('remaining.arweave_wallet.no_active_session'));
|
||||
|
||||
const jwk = parseJwkSecretString(secret);
|
||||
validateArweaveJwk(jwk);
|
||||
@@ -212,21 +214,21 @@ export async function getArweaveWalletFromStoredBlockchainKey({ login, storagePw
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanPwd = String(storagePwd || '').trim();
|
||||
if (!cleanLogin || !cleanPwd) {
|
||||
throw new Error('Нет активной сессии для доступа к blockchain key');
|
||||
throw new Error(t('remaining.arweave_wallet_errors.no_active_session_to_access_blockchain_key'));
|
||||
}
|
||||
|
||||
const secrets = await loadEncryptedUserSecrets(cleanLogin, cleanPwd);
|
||||
const cached = pickCachedWallet(secrets);
|
||||
if (cached) {
|
||||
safeStatus(onStatus, 'Arweave-кошелёк загружен.');
|
||||
safeStatus(onStatus, t('remaining.arweave_wallet.arweave_wallet_loaded'));
|
||||
return cached;
|
||||
}
|
||||
|
||||
safeStatus(onStatus, 'Сейчас мы впервые получаем Arweave-кошелёк из вашего ключа блокчейна. Это может занять немного времени.');
|
||||
safeStatus(onStatus, t('remaining.arweave_wallet.your_arweave_wallet_is_being_derived_from_the_blockchain_k'));
|
||||
|
||||
const storedBlockchainKey = String(secrets?.blockchainKey || '').trim();
|
||||
if (!storedBlockchainKey) {
|
||||
throw new Error('На устройстве не найден blockchain key');
|
||||
throw new Error(t('remaining.arweave_wallet_errors.blockchain_key_not_found_on_this_device'));
|
||||
}
|
||||
|
||||
const blockchainKey32 = extractEd25519Seed32FromStoredValue(storedBlockchainKey);
|
||||
@@ -263,7 +265,7 @@ export async function getArweaveBalance({ gateway, address }) {
|
||||
const normalizedGateway = normalizeGateway(gateway);
|
||||
const cleanAddress = String(address || '').trim();
|
||||
if (!cleanAddress) {
|
||||
throw new Error('Не указан адрес Arweave');
|
||||
throw new Error(t('remaining.arweave_wallet.arweave_address_missing'));
|
||||
}
|
||||
|
||||
const url = `${normalizedGateway}/wallet/${encodeURIComponent(cleanAddress)}/balance`;
|
||||
@@ -274,7 +276,7 @@ export async function getArweaveBalance({ gateway, address }) {
|
||||
throw new Error(`Не удалось получить баланс Arweave (${response.status} ${response.statusText})`);
|
||||
}
|
||||
if (!/^\d+$/.test(rawText)) {
|
||||
throw new Error('Arweave gateway вернул некорректный баланс');
|
||||
throw new Error(t('remaining.arweave_wallet.arweave_gateway_returned_an_invalid_balance'));
|
||||
}
|
||||
|
||||
const winstonBig = BigInt(rawText);
|
||||
@@ -289,7 +291,7 @@ export async function getArweaveBalance({ gateway, address }) {
|
||||
export function formatAr(value, digits = 6) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
return n.toLocaleString('ru-RU', {
|
||||
return formatNumber(n, {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
@@ -301,8 +303,8 @@ export function getArweaveTopupSiteUrl() {
|
||||
|
||||
export async function transferAr({ gateway, jwk, toAddress, amountAr }) {
|
||||
const cleanTo = String(toAddress || '').trim();
|
||||
if (!cleanTo) throw new Error('Не указан адрес получателя Arweave');
|
||||
if (!jwk || typeof jwk !== 'object') throw new Error('Кошелёк Arweave не инициализирован');
|
||||
if (!cleanTo) throw new Error(t('remaining.arweave_wallet.arweave_recipient_address_missing'));
|
||||
if (!jwk || typeof jwk !== 'object') throw new Error(t('remaining.arweave_wallet.arweave_wallet_is_not_initialized'));
|
||||
|
||||
const normalizedGateway = normalizeGateway(gateway);
|
||||
const { host, port, protocol } = parseGatewayForArweaveInit(normalizedGateway);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { formatNumber } from '../i18n/format.js';
|
||||
import { openMediaViewer } from '../components/media-viewer.js';
|
||||
import { buildArweaveDataUrl, sha256HexFromArrayBuffer, validateArweaveTxId, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { resolvePublicFileUrl } from './public-file-service.js';
|
||||
@@ -20,13 +22,13 @@ export function escapeHtml(text) {
|
||||
// Размер файла по-русски: «83 Б», «93 КБ», «1,4 МБ»; после 10 – без дробной части.
|
||||
export function formatBytes(bytes) {
|
||||
const value = Number(bytes || 0);
|
||||
if (!Number.isFinite(value) || value <= 0) return '0 Б';
|
||||
for (const [unit, size] of [['ГБ', 1024 ** 3], ['МБ', 1024 ** 2], ['КБ', 1024]]) {
|
||||
if (!Number.isFinite(value) || value <= 0) return t('remaining.attachments.text_0_b');
|
||||
for (const [unit, size] of [[t('remaining.attachments.gb'), 1024 ** 3], [t('remaining.attachments.mb'), 1024 ** 2], [t('remaining.attachments.kb'), 1024]]) {
|
||||
if (value < size) continue;
|
||||
const amount = value / size;
|
||||
return `${amount.toLocaleString('ru-RU', { maximumFractionDigits: amount >= 10 ? 0 : 1 })} ${unit}`;
|
||||
return `${formatNumber(amount, { maximumFractionDigits: amount >= 10 ? 0 : 1 })} ${unit}`;
|
||||
}
|
||||
return `${Math.round(value)} Б`;
|
||||
return t('remaining.attachments.bytes', { count: Math.round(value) });
|
||||
}
|
||||
|
||||
function normalizeName(name) {
|
||||
@@ -42,9 +44,9 @@ export function normalizeAttachment(input = {}) {
|
||||
const sha256Hex = String(input.sha256 || input.sha256Hex || '').trim().toLowerCase();
|
||||
const size = Number(input.sz || input.size || input.sizeBytes || 0);
|
||||
const name = normalizeName(input.nm || input.name || input.fileName || 'file');
|
||||
if (txId && !validateArweaveTxId(txId)) throw new Error('Некорректный Transaction ID Arweave.');
|
||||
if (!validateSha256Hex(sha256Hex)) throw new Error('Некорректный SHA-256 файла.');
|
||||
if (!Number.isInteger(size) || size <= 0) throw new Error('Некорректный размер файла.');
|
||||
if (txId && !validateArweaveTxId(txId)) throw new Error(t('remaining.attachment_errors.invalid_arweave_transaction_id'));
|
||||
if (!validateSha256Hex(sha256Hex)) throw new Error(t('remaining.attachment_errors.invalid_file_sha_256'));
|
||||
if (!Number.isInteger(size) || size <= 0) throw new Error(t('remaining.attachment_errors.invalid_file_size'));
|
||||
const out = {
|
||||
v: 1,
|
||||
name,
|
||||
@@ -149,11 +151,11 @@ function createUnavailableBlock(messageTimestampMs, storage = 'arweave', detail
|
||||
const block = document.createElement('div');
|
||||
block.className = 'message-attachment-unavailable';
|
||||
if (storage === 'server') {
|
||||
block.textContent = 'Файл недоступен на сервере доступа автора.';
|
||||
block.textContent = t('remaining.attachments.the_file_is_unavailable_on_the_author_s_access_server');
|
||||
} else {
|
||||
block.textContent = isRecentMessage(messageTimestampMs)
|
||||
? 'Скорее всего файл недоступен, потому что сообщение было создано недавно и файл ещё не распространился в Arweave. Попробуйте повторить через несколько минут.'
|
||||
: 'Файл недоступен.';
|
||||
? t('remaining.attachments.the_file_may_not_have_propagated_to_arweave_yet_please_try')
|
||||
: t('remaining.attachments.file_unavailable');
|
||||
}
|
||||
if (detail) {
|
||||
const debug = document.createElement('pre');
|
||||
@@ -192,9 +194,9 @@ function createFileCard({ item, url, messageTimestampMs, slide }) {
|
||||
card.className = 'message-attachment-file-card';
|
||||
card.role = 'button';
|
||||
card.tabIndex = 0;
|
||||
card.title = 'Скачать файл';
|
||||
card.title = t('remaining.attachments.download_file');
|
||||
card.innerHTML = `
|
||||
<div class="message-attachment-file-ext">Файл</div>
|
||||
<div class="message-attachment-file-ext">${th('remaining.html_attachment_format.file_div')}
|
||||
<div class="message-attachment-file-main">
|
||||
<div class="message-attachment-name">${escapeHtml(item.name)}</div>
|
||||
<div class="message-attachment-meta">${escapeHtml(formatBytes(item.size))}</div>
|
||||
@@ -234,7 +236,7 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
|
||||
frame.className = `message-attachment-media-frame message-attachment-media-frame--${kind}`;
|
||||
frame.role = 'button';
|
||||
frame.tabIndex = 0;
|
||||
frame.title = kind === 'video' ? 'Открыть видео' : 'Открыть изображение';
|
||||
frame.title = kind === 'video' ? t('remaining.attachments.open_video') : t('remaining.attachments.open_image');
|
||||
frame.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
onOpen?.();
|
||||
@@ -377,7 +379,7 @@ async function resolveAttachmentDisplayUrl(item, options = {}) {
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status} ${serverUrl}`);
|
||||
const buffer = await response.arrayBuffer();
|
||||
const actualSha = await sha256HexFromArrayBuffer(buffer);
|
||||
if (actualSha !== item.sha256) throw new Error(`SHA-256 скачанного файла не совпал с блокчейном: ${actualSha} != ${item.sha256} (${serverUrl})`);
|
||||
if (actualSha !== item.sha256) throw new Error(t('remaining.attachment_error.hash_mismatch', { actual: actualSha, expected: item.sha256, url: serverUrl }));
|
||||
const blob = new Blob([buffer], { type: mimeTypeForAttachment(item, kind) });
|
||||
return { url: URL.createObjectURL(blob), sourceUrl: serverUrl, objectUrl: true };
|
||||
}
|
||||
@@ -423,12 +425,12 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
prev.type = 'button';
|
||||
prev.className = 'ui-button message-attachment-arrow message-attachment-arrow--prev';
|
||||
prev.textContent = '‹';
|
||||
prev.setAttribute('aria-label', 'Предыдущее вложение');
|
||||
prev.setAttribute('aria-label', t('remaining.attachments.previous_attachment'));
|
||||
const next = document.createElement('button');
|
||||
next.type = 'button';
|
||||
next.className = 'ui-button message-attachment-arrow message-attachment-arrow--next';
|
||||
next.textContent = '›';
|
||||
next.setAttribute('aria-label', 'Следующее вложение');
|
||||
next.setAttribute('aria-label', t('remaining.attachments.next_attachment'));
|
||||
const counter = document.createElement('div');
|
||||
counter.className = 'message-attachment-counter';
|
||||
wrap.classList.toggle('has-single-attachment', items.length <= 1);
|
||||
@@ -478,7 +480,7 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
|
||||
const loading = document.createElement('div');
|
||||
loading.className = 'message-attachment-unavailable';
|
||||
loading.textContent = 'Загружаем файл…';
|
||||
loading.textContent = t('remaining.attachments.loading_file');
|
||||
slide.append(loading);
|
||||
|
||||
void getResolved(currentIndex)
|
||||
@@ -501,7 +503,7 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
prev.hidden = items.length <= 1 || index <= 0;
|
||||
next.hidden = items.length <= 1 || index >= items.length - 1;
|
||||
counter.hidden = items.length <= 1;
|
||||
counter.textContent = items.length > 1 ? `${index + 1} из ${items.length}` : '';
|
||||
counter.textContent = items.length > 1 ? t('remaining.attachments.counter', { current: index + 1, total: items.length }) : '';
|
||||
};
|
||||
|
||||
const move = (delta) => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { navigate } from '../router.js';
|
||||
|
||||
function escapeHtml(text) {
|
||||
@@ -10,8 +11,8 @@ function escapeHtml(text) {
|
||||
}
|
||||
|
||||
export function openAuthRequiredModal({
|
||||
title = 'Нужен вход',
|
||||
text = 'Эта часть доступна после входа.',
|
||||
title = t('remaining.auth_required.sign_in_required'),
|
||||
text = t('remaining.auth_required.this_section_is_available_after_you_sign_in'),
|
||||
} = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!(root instanceof HTMLElement)) {
|
||||
@@ -24,8 +25,8 @@ export function openAuthRequiredModal({
|
||||
<h3 class="modal-title">${escapeHtml(title)}</h3>
|
||||
<p class="meta-muted" style="white-space: pre-wrap; line-height: 1.45;">${escapeHtml(text)}</p>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" type="button" id="auth-required-login">Войти</button>
|
||||
<button class="primary-btn" type="button" id="auth-required-register">Зарегистрироваться</button>
|
||||
<button class="secondary-btn" type="button" id="auth-required-login">${th('remaining.auth_required.sign_in')}</button>
|
||||
<button class="primary-btn" type="button" id="auth-required-register">${th('remaining.auth_required.register')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { addAppLogEntry, addSignedMessageToChat, authService, authorizeSession, state } from '../state.js';
|
||||
import { buildDmCallTechBlock } from './dm-tech-blocks.js';
|
||||
|
||||
@@ -150,23 +151,23 @@ function parseInviteData(data = '') {
|
||||
|
||||
function getCallTitleText(mode) {
|
||||
if (normalizeCallMode(mode) === CALL_MODE_INSTANT_VIDEO) {
|
||||
return 'Видеозвонок';
|
||||
return t('remaining.call.video_call');
|
||||
}
|
||||
if (normalizeCallMode(mode) === CALL_MODE_VIDEO) {
|
||||
return 'Видеозвонок';
|
||||
return t('remaining.call.video_call');
|
||||
}
|
||||
return 'Звонок';
|
||||
return t('remaining.call.call');
|
||||
}
|
||||
|
||||
function getIncomingCallStatusText(peerLogin, mode) {
|
||||
const name = String(peerLogin || '').trim();
|
||||
if (normalizeCallMode(mode) === CALL_MODE_INSTANT_VIDEO) {
|
||||
return `Входящий видеозвонок от ${name}`;
|
||||
return t('remaining.call.incoming_video', { name });
|
||||
}
|
||||
if (isVideoCallMode(mode)) {
|
||||
return `Входящий видеозвонок от ${name}`;
|
||||
return t('remaining.call.incoming_video', { name });
|
||||
}
|
||||
return `Вам звонит ${name}`;
|
||||
return t('remaining.call.incoming_voice', { name });
|
||||
}
|
||||
|
||||
function parseConnectStartWinnerSessionId(data = '') {
|
||||
@@ -331,9 +332,9 @@ function formatDuration(ms) {
|
||||
const totalMin = Math.floor(totalSec / 60);
|
||||
const min = totalMin % 60;
|
||||
const hours = Math.floor(totalMin / 60);
|
||||
if (hours > 0) return `${hours}ч ${min}м ${sec}с`;
|
||||
if (min > 0) return `${min}м ${sec}с`;
|
||||
return `${sec}с`;
|
||||
if (hours > 0) return `${hours}${t('remaining.call.unit_h')} ${min}${t('remaining.call.unit_m')} ${sec}${t('remaining.call.unit_s')}`;
|
||||
if (min > 0) return `${min}${t('remaining.call.unit_m')} ${sec}${t('remaining.call.unit_s')}`;
|
||||
return `${sec}${t('remaining.call.unit_s')}`;
|
||||
}
|
||||
|
||||
function isInviteUndelivered(call) {
|
||||
@@ -775,7 +776,7 @@ function setStatus(call, statusText, phase = '') {
|
||||
function buildActiveStatusText(call) {
|
||||
const route = String(call?.connectionRouteLabel || '').trim();
|
||||
const videoSlotMarker = call?.videoSlotReady ? ' +' : '';
|
||||
return route ? `Разговор идёт (${route}${videoSlotMarker})` : 'Разговор идёт';
|
||||
return route ? t('remaining.call.active_route', { route, videoSlotMarker }) : t('remaining.call.call_in_progress');
|
||||
}
|
||||
|
||||
function refreshVideoSlotReady(call) {
|
||||
@@ -1205,8 +1206,8 @@ async function detectConnectionRoute(call) {
|
||||
|
||||
if (localType === 'relay' || remoteType === 'relay') {
|
||||
const label = turnCandidateAddress
|
||||
? `через TURN (${turnCandidateAddress})`
|
||||
: (relayProto ? `через TURN (${relayProto})` : 'через TURN');
|
||||
? t('remaining.call.route_turn_candidate', { address: turnCandidateAddress })
|
||||
: (relayProto ? t('remaining.call.via_turn_proto', { protocol: relayProto }) : t('remaining.call.via_turn'));
|
||||
return { label, details, localIp, remoteIp, turnCandidateAddress };
|
||||
}
|
||||
if (localType || remoteType) {
|
||||
@@ -1216,7 +1217,7 @@ async function detectConnectionRoute(call) {
|
||||
|| (localIp.startsWith('172.16.') && remoteIp.startsWith('172.16.'))
|
||||
);
|
||||
return {
|
||||
label: sameLan ? 'напрямую в локальной сети' : 'напрямую через интернет',
|
||||
label: sameLan ? t('remaining.call.directly_on_local_network') : t('remaining.call.directly_over_the_internet'),
|
||||
details,
|
||||
localIp,
|
||||
remoteIp,
|
||||
@@ -1262,7 +1263,7 @@ function startReconnectFlow(call, reason = 'disconnected') {
|
||||
call.reconnectInProgress = true;
|
||||
call.reconnectAttempts = 0;
|
||||
recordCallTimeline(call, 'reconnect_start', `reason=${reason}`);
|
||||
setStatus(call, 'Связь прервалась. Переподключаем…', 'reconnecting');
|
||||
setStatus(call, t('remaining.call.connection_lost_reconnecting'), 'reconnecting');
|
||||
void emitDebug(call, 'warn', 'peer_connection_reconnect_start', `reason=${reason}`);
|
||||
|
||||
const maxAttempts = 6;
|
||||
@@ -1397,9 +1398,9 @@ async function finalizeCall(call, {
|
||||
}
|
||||
|
||||
call.phase = 'ended';
|
||||
call.statusText = 'Звонок завершён';
|
||||
call.statusText = t('remaining.call.call_ended');
|
||||
if (String(localReasonCode || '') === 'busy') {
|
||||
call.statusText = 'Пользователь занят';
|
||||
call.statusText = t('remaining.call.user_is_busy');
|
||||
}
|
||||
recordCallTimeline(call, 'finalize_end', `reason=${localReasonCode || ''}; status=${call.statusText || ''}`);
|
||||
notifyCallState();
|
||||
@@ -1770,7 +1771,7 @@ async function ensurePeerConnection(call) {
|
||||
ensureReservedVideoTransceiver(call);
|
||||
}
|
||||
} catch (e) {
|
||||
setStatus(call, `Нет доступа к микрофону: ${e?.message || 'unknown'}`, 'failed');
|
||||
setStatus(call, t('remaining.call.microphone_error_full', { error: e?.message || 'unknown' }), 'failed');
|
||||
recordCallTimeline(call, 'local_media_failed', toErrorText(e), 'warn');
|
||||
await emitDebug(call, 'warn', 'microphone_access_failed', toErrorText(e));
|
||||
throw e;
|
||||
@@ -1865,7 +1866,7 @@ async function onAccept(call) {
|
||||
recordCallTimeline(call, 'offer_start', `remoteSession=${call.remoteSessionId || ''}`);
|
||||
call.initialOfferInProgress = true;
|
||||
cleanupTimers(call);
|
||||
setStatus(call, 'Соединяем…', 'connecting');
|
||||
setStatus(call, t('remaining.call.connecting'), 'connecting');
|
||||
try {
|
||||
await notifyPeerSessionsAboutConnectStart(call);
|
||||
const pc = await ensurePeerConnection(call);
|
||||
@@ -1892,7 +1893,7 @@ function ensureIncomingNotification(peerLogin, mode = CALL_MODE_AUDIO) {
|
||||
const text = getIncomingCallStatusText(peerLogin, mode);
|
||||
try {
|
||||
if ('Notification' in window && Notification.permission === 'granted') {
|
||||
new Notification('SHiNE: входящий звонок', { body: text });
|
||||
new Notification(t('remaining.call.shine_incoming_call'), { body: text });
|
||||
}
|
||||
} catch {}
|
||||
try {
|
||||
@@ -2545,7 +2546,7 @@ export async function startOutgoingCall(peerLogin, options = {}) {
|
||||
|
||||
const active = getActiveCall();
|
||||
if (active) {
|
||||
throw new Error(`Уже есть активный звонок с ${active.peerLogin || 'другим пользователем'}`);
|
||||
throw new Error(t('remaining.call.active_call_already', { peer: active.peerLogin || t('remaining.call.another_user') }));
|
||||
}
|
||||
|
||||
const callId = makeCallId();
|
||||
@@ -2553,7 +2554,7 @@ export async function startOutgoingCall(peerLogin, options = {}) {
|
||||
const preflightTimeoutMs = resolveCallPreflightTimeoutMs();
|
||||
const preflightOk = await ensureSessionForCall({ timeoutMs: preflightTimeoutMs, force: false });
|
||||
if (!preflightOk) {
|
||||
throw new Error('Сервер временно недоступен');
|
||||
throw new Error(t('remaining.call.server_temporarily_unavailable'));
|
||||
}
|
||||
|
||||
const call = {
|
||||
@@ -2564,7 +2565,7 @@ export async function startOutgoingCall(peerLogin, options = {}) {
|
||||
autoEnableCameraOnConnect: isInstantVideoMode(callMode),
|
||||
direction: 'out',
|
||||
phase: 'searching',
|
||||
statusText: 'Ищем пользователя…',
|
||||
statusText: t('remaining.call.finding_user'),
|
||||
remoteSessionId: '',
|
||||
timers: {},
|
||||
startedAtMs: nowMs(),
|
||||
@@ -2596,7 +2597,7 @@ export async function startOutgoingCall(peerLogin, options = {}) {
|
||||
calls.set(callId, call);
|
||||
activeCallId = callId;
|
||||
recordCallTimeline(call, 'outgoing_created', `peer=${cleanPeer}`);
|
||||
setStatus(call, 'Ищем пользователя…', 'searching');
|
||||
setStatus(call, t('remaining.call.finding_user'), 'searching');
|
||||
|
||||
call.timers.total35s = setTimeout(() => {
|
||||
if (!calls.has(callId)) return;
|
||||
@@ -2614,7 +2615,7 @@ export async function startOutgoingCall(peerLogin, options = {}) {
|
||||
`ws=${Number(call.inviteDelivery?.deliveredWsSessions || 0)}; push=${Number(call.inviteDelivery?.deliveredWebPushSessions || call.inviteDelivery?.deliveredFcmSessions || 0)}`,
|
||||
);
|
||||
if (getInviteDeliveredCount(call) > 0 && call.phase === 'searching') {
|
||||
setStatus(call, 'Вызываем…', 'ringing');
|
||||
setStatus(call, t('remaining.call.calling'), 'ringing');
|
||||
}
|
||||
scheduleOutgoingAckTimeout(call);
|
||||
} catch (error) {
|
||||
@@ -2627,14 +2628,14 @@ export async function startOutgoingCall(peerLogin, options = {}) {
|
||||
try {
|
||||
call.inviteDelivery = await broadcastSignal(call, TYPES.INVITE, buildInviteData({ mode: callMode }));
|
||||
if (getInviteDeliveredCount(call) > 0 && call.phase === 'searching') {
|
||||
setStatus(call, 'Вызываем…', 'ringing');
|
||||
setStatus(call, t('remaining.call.calling'), 'ringing');
|
||||
}
|
||||
scheduleOutgoingAckTimeout(call);
|
||||
return;
|
||||
} catch {}
|
||||
}
|
||||
await finalizeCall(call, { localReasonCode: 'error', debugReason: 'invite_failed:not_authenticated_after_retry' });
|
||||
throw new Error('Сервер временно недоступен');
|
||||
throw new Error(t('remaining.call.server_temporarily_unavailable'));
|
||||
}
|
||||
await finalizeCall(call, { localReasonCode: 'error', debugReason: `invite_failed:${toErrorText(error)}` });
|
||||
throw error;
|
||||
@@ -2680,7 +2681,7 @@ export async function acceptIncomingCall() {
|
||||
call.cameraEnabled = true;
|
||||
}
|
||||
call.phase = 'connecting';
|
||||
setStatus(call, 'Соединяем…', 'connecting');
|
||||
setStatus(call, t('remaining.call.connecting'), 'connecting');
|
||||
cleanupTimers(call);
|
||||
scheduleIncomingConnectTimeout(call);
|
||||
await sendSignal(call, TYPES.ACCEPT, 'accept');
|
||||
@@ -2777,7 +2778,7 @@ export async function handleIncomingCallSignal(evt) {
|
||||
|
||||
if (type === TYPES.RINGING) {
|
||||
if (call.direction === 'out' && call.phase === 'searching') {
|
||||
setStatus(call, 'Вызываем…', 'ringing');
|
||||
setStatus(call, t('remaining.call.calling'), 'ringing');
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -2794,7 +2795,7 @@ export async function handleIncomingCallSignal(evt) {
|
||||
return;
|
||||
}
|
||||
call.phase = 'connecting';
|
||||
setStatus(call, 'Соединяем…', 'connecting');
|
||||
setStatus(call, t('remaining.call.connecting'), 'connecting');
|
||||
await onAccept(call);
|
||||
return;
|
||||
}
|
||||
@@ -2860,7 +2861,7 @@ export async function handleIncomingCallSignal(evt) {
|
||||
await pc.setLocalDescription(answer);
|
||||
await sendSignal(call, TYPES.ANSWER, JSON.stringify(answer));
|
||||
refreshVideoSlotReady(call);
|
||||
setStatus(call, 'Соединяем…', 'connecting');
|
||||
setStatus(call, t('remaining.call.connecting'), 'connecting');
|
||||
notifyCallState();
|
||||
await emitDebug(call, 'info', 'offer_processed', 'answer sent');
|
||||
} catch (error) {
|
||||
@@ -2901,7 +2902,7 @@ export async function handleIncomingCallSignal(evt) {
|
||||
await flushPendingIceCandidates(call);
|
||||
refreshVideoSlotReady(call);
|
||||
recordCallTimeline(call, 'answer_applied', `from=${fromSessionId || '-'}`);
|
||||
setStatus(call, 'Соединяем…', 'connecting');
|
||||
setStatus(call, t('remaining.call.connecting'), 'connecting');
|
||||
notifyCallState();
|
||||
await emitDebug(call, 'info', 'answer_processed', 'remote description set');
|
||||
} catch (error) {
|
||||
@@ -2994,7 +2995,7 @@ export async function handleCallPushAction(action, payload = {}) {
|
||||
const timeoutMs = resolveCallPreflightTimeoutMs();
|
||||
const ok = await ensureSessionForCall({ timeoutMs, force: false });
|
||||
if (!ok) {
|
||||
throw new Error('Не удалось подключиться, вызов завершён');
|
||||
throw new Error(t('remaining.call.could_not_connect_call_ended'));
|
||||
}
|
||||
await handleIncomingCallPush(payload);
|
||||
if (normalized === 'accept') {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
acceptIncomingCall,
|
||||
declineIncomingCall,
|
||||
@@ -82,10 +83,10 @@ function getSnapshotElapsedMs(snapshot) {
|
||||
}
|
||||
|
||||
function buildBarText(snapshot) {
|
||||
const peer = String(snapshot?.peerLogin || '').trim() || 'пользователь';
|
||||
const peer = String(snapshot?.peerLogin || '').trim() || t('remaining.call_ui.user');
|
||||
const elapsed = formatElapsedMs(getSnapshotElapsedMs(snapshot));
|
||||
const kind = String(snapshot?.titleText || 'Звонок').trim() || 'Звонок';
|
||||
return `${kind} с ${peer} · ${elapsed}`;
|
||||
const kind = String(snapshot?.titleText || t('remaining.call_ui.call')).trim() || t('remaining.call_ui.call');
|
||||
return t('remaining.call_ui.call_with', { kind, peer, elapsed });
|
||||
}
|
||||
|
||||
async function loadAvatarSnapshot(login) {
|
||||
@@ -116,7 +117,7 @@ function renderPeerAvatar(login, avatar = null) {
|
||||
avatar,
|
||||
size: 'xl',
|
||||
className: 'call-peer-avatar',
|
||||
title: login ? `Профиль ${login}` : 'Профиль собеседника',
|
||||
title: login ? t('remaining.call_ui.profile_of', { login }) : t('remaining.call_ui.other_user_s_profile'),
|
||||
});
|
||||
if (!hasAvatar) {
|
||||
avatarEl.classList.add('call-peer-avatar--empty');
|
||||
@@ -194,7 +195,7 @@ function setButtonIcon(button, iconName, label) {
|
||||
|
||||
function updateMuteButtons(muted) {
|
||||
const iconName = muted ? 'mic-off' : 'mic-on';
|
||||
const label = muted ? 'Включить микрофон' : 'Выключить микрофон';
|
||||
const label = muted ? t('remaining.call_ui.unmute_microphone') : t('remaining.call_ui.mute_microphone');
|
||||
setButtonIcon(muteBtn, iconName, label);
|
||||
setButtonIcon(barMuteBtn, iconName, label);
|
||||
if (muteBtn) muteBtn.dataset.muted = muted ? '1' : '0';
|
||||
@@ -203,14 +204,14 @@ function updateMuteButtons(muted) {
|
||||
|
||||
function updateSpeakerButtons(enabled) {
|
||||
const iconName = enabled ? 'speaker-on' : 'speaker-off';
|
||||
const label = enabled ? 'Выключить громкую связь' : 'Включить громкую связь';
|
||||
const label = enabled ? t('remaining.call_ui.turn_off_speaker') : t('remaining.call_ui.turn_on_speaker');
|
||||
setButtonIcon(speakerBtn, iconName, label);
|
||||
setButtonIcon(barSpeakerBtn, iconName, label);
|
||||
}
|
||||
|
||||
function updateCameraButtons(enabled) {
|
||||
const iconName = enabled ? 'camera-on' : 'camera-off';
|
||||
const label = enabled ? 'Выключить камеру' : 'Включить камеру';
|
||||
const label = enabled ? t('remaining.call_ui.turn_off_camera') : t('remaining.call_ui.turn_on_camera');
|
||||
setButtonIcon(cameraBtn, iconName, label);
|
||||
setButtonIcon(barCameraBtn, iconName, label);
|
||||
if (cameraBtn) cameraBtn.dataset.enabled = enabled ? '1' : '0';
|
||||
@@ -380,7 +381,7 @@ function ensureUi() {
|
||||
minimizeBtn = document.createElement('button');
|
||||
minimizeBtn.type = 'button';
|
||||
minimizeBtn.className = 'call-icon-btn call-icon-btn--secondary call-overlay-minimize-btn';
|
||||
setButtonIcon(minimizeBtn, 'minimize', 'Свернуть звонок');
|
||||
setButtonIcon(minimizeBtn, 'minimize', t('remaining.call_ui.minimize_call'));
|
||||
minimizeBtn.addEventListener('click', (event) => {
|
||||
stopEvent(event);
|
||||
if (!currentSnapshot) return;
|
||||
@@ -455,7 +456,7 @@ function ensureUi() {
|
||||
acceptBtn = document.createElement('button');
|
||||
acceptBtn.type = 'button';
|
||||
acceptBtn.className = 'call-accept-btn';
|
||||
acceptBtn.textContent = 'Ответить';
|
||||
acceptBtn.textContent = t('remaining.call_ui.answer');
|
||||
acceptBtn.addEventListener('click', async () => {
|
||||
await acceptIncomingCall();
|
||||
});
|
||||
@@ -463,7 +464,7 @@ function ensureUi() {
|
||||
declineBtn = document.createElement('button');
|
||||
declineBtn.type = 'button';
|
||||
declineBtn.className = 'destructive-btn call-decline-btn';
|
||||
declineBtn.textContent = 'Отклонить';
|
||||
declineBtn.textContent = t('remaining.call_ui.decline');
|
||||
declineBtn.addEventListener('click', async () => {
|
||||
await declineIncomingCall();
|
||||
});
|
||||
@@ -471,7 +472,7 @@ function ensureUi() {
|
||||
hangupBtn = document.createElement('button');
|
||||
hangupBtn.type = 'button';
|
||||
hangupBtn.className = 'call-icon-btn call-icon-btn--danger';
|
||||
setButtonIcon(hangupBtn, 'hangup', 'Положить трубку');
|
||||
setButtonIcon(hangupBtn, 'hangup', t('remaining.call_ui.hang_up'));
|
||||
hangupBtn.addEventListener('click', handleEndCallClick);
|
||||
|
||||
incomingActionsEl.append(acceptBtn, declineBtn);
|
||||
@@ -489,8 +490,8 @@ function applyExpandedState(snapshot) {
|
||||
|
||||
titleEl.textContent = '';
|
||||
statusEl.textContent = '';
|
||||
peerLoginEl.textContent = snapshot.peerLogin || 'пользователь';
|
||||
kindEl.textContent = snapshot.titleText || 'Звонок';
|
||||
peerLoginEl.textContent = snapshot.peerLogin || t('remaining.call_ui.user');
|
||||
kindEl.textContent = snapshot.titleText || t('remaining.call_ui.call');
|
||||
topStatusEl.textContent = snapshot.statusText || '';
|
||||
updatePeerAvatar(snapshot.peerLogin || '');
|
||||
|
||||
@@ -554,7 +555,7 @@ function applyMinimizedState(snapshot) {
|
||||
const canEnd = !incomingStage && snapshot.canHangup;
|
||||
barHangupBtn.hidden = !canEnd;
|
||||
barHangupBtn.disabled = !canEnd;
|
||||
setButtonIcon(barHangupBtn, 'hangup', 'Положить трубку');
|
||||
setButtonIcon(barHangupBtn, 'hangup', t('remaining.call_ui.hang_up'));
|
||||
barActionsEl.hidden = incomingStage || (!snapshot.canToggleSpeaker && !snapshot.canMute && !snapshot.canToggleCamera && !canEnd);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
const MIN_LEN = 4;
|
||||
const MAX_LEN = 32;
|
||||
const ALLOWED_CHARS_RE = /^[A-Za-z0-9_-]+$/;
|
||||
@@ -53,24 +54,24 @@ export function validateChannelDisplayName(value) {
|
||||
export function channelNameErrorText(code) {
|
||||
switch (String(code || '').trim()) {
|
||||
case 'blank':
|
||||
return 'Введите название канала.';
|
||||
return t('remaining.channel_validation.enter_a_channel_name');
|
||||
case 'too_short':
|
||||
return 'Название слишком короткое: минимум 4 символа.';
|
||||
return t('remaining.channel_validation.channel_name_is_too_short_minimum_4_characters');
|
||||
case 'too_long':
|
||||
return 'Название слишком длинное: максимум 32 символа.';
|
||||
return t('remaining.channel_validation.channel_name_is_too_long_maximum_32_characters');
|
||||
case 'bad_chars':
|
||||
return 'Разрешены только латиница, цифры, _ и -.';
|
||||
return t('remaining.channel_validation.only_latin_letters_digits_and_are_allowed');
|
||||
case 'digits_only':
|
||||
return 'Название канала не должно состоять только из цифр.';
|
||||
return t('remaining.channel_validation.a_channel_name_cannot_consist_of_digits_only');
|
||||
default:
|
||||
return 'Некорректное название канала.';
|
||||
return t('remaining.channel_validation.invalid_channel_name');
|
||||
}
|
||||
}
|
||||
|
||||
export function channelDescriptionErrorText(value) {
|
||||
const normalized = normalizeChannelDescription(value);
|
||||
if (new TextEncoder().encode(normalized).length > 200) {
|
||||
return 'Описание слишком длинное: максимум 200 байт UTF-8.';
|
||||
return t('remaining.channel_validation.description_is_too_long_maximum_200_utf_8_bytes');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { formatDate, formatTime, formatDateTime, formatRelative } from '../i18n/format.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
const TOAST_HOST_ID = 'shine-toast-host';
|
||||
|
||||
const rtf = (() => {
|
||||
try {
|
||||
return new Intl.RelativeTimeFormat('ru', { numeric: 'always' });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
function toNumber(value) {
|
||||
const n = Number(value);
|
||||
@@ -33,10 +28,10 @@ function pickUnit(seconds) {
|
||||
export function formatClockTime(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(ts));
|
||||
return formatTime(new Date(ts));
|
||||
}
|
||||
|
||||
const SHORT_MONTHS = ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'];
|
||||
const shortDay = (date) => formatDate(date, { day: 'numeric', month: 'short' });
|
||||
|
||||
// Дата записи в ряду действий: сегодня «10:24», раньше «25 сен, 10:24», в прошлом году «25 сен 2025».
|
||||
export function formatPostStamp(timestampMs) {
|
||||
@@ -46,7 +41,7 @@ export function formatPostStamp(timestampMs) {
|
||||
const now = new Date();
|
||||
const clock = formatClockTime(ts);
|
||||
if (dt.toDateString() === now.toDateString()) return clock;
|
||||
const day = `${dt.getDate()} ${SHORT_MONTHS[dt.getMonth()]}`;
|
||||
const day = shortDay(dt);
|
||||
if (dt.getFullYear() !== now.getFullYear()) return `${day} ${dt.getFullYear()}`;
|
||||
return `${day}, ${clock}`;
|
||||
}
|
||||
@@ -59,10 +54,10 @@ export function formatDayLabel(timestampMs) {
|
||||
const today = new Date();
|
||||
const startOf = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const diffDays = Math.round((startOf(today) - startOf(dt)) / 86400000);
|
||||
if (diffDays === 0) return 'Сегодня';
|
||||
if (diffDays === 1) return 'Вчера';
|
||||
if (diffDays === 0) return formatRelative(0, 'day');
|
||||
if (diffDays === 1) return formatRelative(-1, 'day');
|
||||
const sameYear = dt.getFullYear() === today.getFullYear();
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: 'numeric', month: 'long', ...(sameYear ? {} : { year: 'numeric' }) }).format(dt);
|
||||
return formatDate(dt, { day: 'numeric', month: 'long', ...(sameYear ? {} : { year: 'numeric' }) });
|
||||
}
|
||||
|
||||
export function dayKey(timestampMs) {
|
||||
@@ -81,17 +76,17 @@ export function formatListTime(timestampMs) {
|
||||
const now = new Date();
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
||||
if (ts >= startOfToday) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(dt);
|
||||
return formatTime(dt);
|
||||
}
|
||||
const dayMs = 86400000;
|
||||
if (ts >= startOfToday - dayMs) return 'вчера';
|
||||
if (ts >= startOfToday - dayMs) return formatRelative(-1, 'day');
|
||||
if (ts >= startOfToday - 6 * dayMs) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { weekday: 'short' }).format(dt);
|
||||
return formatDate(dt, { weekday: 'short' });
|
||||
}
|
||||
if (dt.getFullYear() === now.getFullYear()) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit' }).format(dt);
|
||||
return formatDate(dt, { day: '2-digit', month: '2-digit' });
|
||||
}
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit', year: '2-digit' }).format(dt);
|
||||
return formatDate(dt, { day: '2-digit', month: '2-digit', year: '2-digit' });
|
||||
}
|
||||
|
||||
// Возраст записи в шапке поста и ответа: «сейчас», «5 мин», «2 ч», «3 д», потом «12 окт», в прошлом году «12 окт 2025».
|
||||
@@ -99,14 +94,14 @@ export function formatShortAge(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
const ageMinutes = Math.max(0, Math.floor((Date.now() - ts) / 60000));
|
||||
if (ageMinutes < 1) return 'сейчас';
|
||||
if (ageMinutes < 60) return `${ageMinutes} мин`;
|
||||
if (ageMinutes < 1) return formatRelative(0, 'second');
|
||||
if (ageMinutes < 60) return formatRelative(-ageMinutes, 'minute', { numeric: 'always', style: 'narrow' });
|
||||
const ageHours = Math.floor(ageMinutes / 60);
|
||||
if (ageHours < 24) return `${ageHours} ч`;
|
||||
if (ageHours < 24) return formatRelative(-ageHours, 'hour', { numeric: 'always', style: 'narrow' });
|
||||
const ageDays = Math.floor(ageHours / 24);
|
||||
if (ageDays < 7) return `${ageDays} д`;
|
||||
if (ageDays < 7) return formatRelative(-ageDays, 'day', { numeric: 'always', style: 'narrow' });
|
||||
const dt = new Date(ts);
|
||||
const day = `${dt.getDate()} ${SHORT_MONTHS[dt.getMonth()]}`;
|
||||
const day = shortDay(dt);
|
||||
return dt.getFullYear() === new Date().getFullYear() ? day : `${day} ${dt.getFullYear()}`;
|
||||
}
|
||||
|
||||
@@ -121,26 +116,22 @@ export function formatRelativeTime(timestampMs) {
|
||||
const ageSeconds = Math.max(0, (now - ts) / 1000);
|
||||
const ageDays = ageSeconds / 86400;
|
||||
|
||||
if (ageSeconds < 60) return 'только что';
|
||||
if (ageSeconds < 60) return formatRelative(0, 'second');
|
||||
|
||||
if (ageDays < 7) {
|
||||
const [unit, value] = pickUnit(diffSeconds);
|
||||
if (rtf) return rtf.format(value, unit);
|
||||
const absValue = Math.abs(value);
|
||||
const suffix = value <= 0 ? 'назад' : 'через';
|
||||
const labels = { second: 'сек', minute: 'мин', hour: 'ч', day: 'д' };
|
||||
return `${absValue} ${labels[unit] || ''} ${suffix}`.trim();
|
||||
return formatRelative(value, unit, { numeric: 'always' });
|
||||
}
|
||||
|
||||
if (dt.getFullYear() === nowDt.getFullYear()) {
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
return formatDateTime(dt, {
|
||||
day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit',
|
||||
}).format(dt).replace(',', ',');
|
||||
});
|
||||
}
|
||||
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
return formatDate(dt, {
|
||||
day: '2-digit', month: '2-digit', year: 'numeric',
|
||||
}).format(dt);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureToastHost() {
|
||||
@@ -277,7 +268,7 @@ export function writeChannelNotificationsState(nextState) {
|
||||
}
|
||||
|
||||
export function makeAuthorLabel(login, localNumber) {
|
||||
const cleanLogin = String(login || 'автор');
|
||||
const cleanLogin = String(login || t('remaining.channels.author'));
|
||||
const n = Number(localNumber);
|
||||
if (!Number.isFinite(n) || n < 1) return cleanLogin;
|
||||
return `${cleanLogin} · #${n}`;
|
||||
@@ -300,7 +291,7 @@ export function createSkeletonRows(kind = 'list', count = 4) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = `skeleton-rows skeleton-rows--${kind}`;
|
||||
wrap.setAttribute('aria-busy', 'true');
|
||||
wrap.setAttribute('aria-label', 'Загрузка');
|
||||
wrap.setAttribute('aria-label', t('remaining.channels.loading'));
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'skeleton-row';
|
||||
@@ -379,7 +370,7 @@ export async function longPressFeel(el, delayMs = 130) {
|
||||
// Когда появится, здесь вызывать настоящий обработчик.
|
||||
export const REPOSTS_ENABLED = false;
|
||||
export function notifyRepostSoon() {
|
||||
showToast('Репосты скоро появятся', { kind: 'info' });
|
||||
showToast(t('remaining.channels.reposts_are_coming_soon'), { kind: 'info' });
|
||||
}
|
||||
|
||||
// Общая карточка «не удалось загрузить»: короткий заголовок, причина в пару строк и крупная кнопка снизу.
|
||||
@@ -395,7 +386,7 @@ export function createLoadErrorCard({ title, message, onRetry, secondary = null
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.textContent = t('remaining.channels.retry');
|
||||
retry.addEventListener('click', onRetry);
|
||||
card.append(heading, details, retry);
|
||||
if (secondary) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
base64ToBytes,
|
||||
bytesToBase64,
|
||||
@@ -42,11 +43,11 @@ function base64UrlToBytes(value) {
|
||||
function extractSeedFromPkcs8(pkcs8B64) {
|
||||
const raw = base64ToBytes(pkcs8B64);
|
||||
if (raw.length !== ED25519_PKCS8_PREFIX.length + 32) {
|
||||
throw new Error('Некорректный приватный Ed25519 ключ');
|
||||
throw new Error(t('remaining.device_pairing.invalid_ed25519_private_key'));
|
||||
}
|
||||
for (let i = 0; i < ED25519_PKCS8_PREFIX.length; i += 1) {
|
||||
if (raw[i] !== ED25519_PKCS8_PREFIX[i]) {
|
||||
throw new Error('Неподдерживаемый формат приватного Ed25519 ключа');
|
||||
throw new Error(t('remaining.device_pairing.unsupported_ed25519_private_key_format'));
|
||||
}
|
||||
}
|
||||
return raw.slice(ED25519_PKCS8_PREFIX.length);
|
||||
@@ -55,11 +56,11 @@ function extractSeedFromPkcs8(pkcs8B64) {
|
||||
function extractSessionPublicKeyB64(sessionKey) {
|
||||
const raw = String(sessionKey || '').trim();
|
||||
if (!raw.startsWith('ed25519/')) {
|
||||
throw new Error('Неподдерживаемый requesterSessionKey');
|
||||
throw new Error(t('remaining.device_pairing.unsupported_requester_session_key'));
|
||||
}
|
||||
const publicKeyB64 = raw.slice('ed25519/'.length).trim();
|
||||
if (!publicKeyB64) {
|
||||
throw new Error('Пустой requesterSessionKey');
|
||||
throw new Error(t('remaining.device_pairing.empty_requester_session_key'));
|
||||
}
|
||||
return publicKeyB64;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { formatDate, formatTime } from '../i18n/format.js';
|
||||
// Настройки личных чатов на этом устройстве: «без звука» (навсегда или до срока) и «закреплён».
|
||||
// Сервер про них не знает: хранятся в localStorage отдельно для каждого аккаунта.
|
||||
// Список «без звука» дублируется в Cache Storage, чтобы его видел service worker:
|
||||
@@ -168,10 +169,10 @@ export function formatDmMuteUntil(until, now = new Date()) {
|
||||
const value = Number(until || 0);
|
||||
if (!value) return '';
|
||||
const date = new Date(value);
|
||||
const time = date.toLocaleTimeString('ru-RU', { hour: 'numeric', minute: '2-digit' });
|
||||
const time = formatTime(date, { hour: 'numeric', minute: '2-digit' });
|
||||
const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const days = Math.round((startOfDay(date) - startOfDay(now)) / 86400000);
|
||||
if (days <= 0) return `до ${time}`;
|
||||
if (days === 1) return `до завтра, ${time}`;
|
||||
return `до ${date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })}, ${time}`;
|
||||
return `до ${formatDate(date, { day: 'numeric', month: 'long' })}, ${time}`;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
function defaultParsed(rawText = '') {
|
||||
const text = String(rawText || '');
|
||||
return {
|
||||
@@ -56,15 +57,15 @@ function formatCallDuration(totalSeconds) {
|
||||
function buildCallDisplayText(callSummary) {
|
||||
if (!callSummary) return '';
|
||||
if (callSummary.status === 'completed') {
|
||||
return `Звонок: ${formatCallDuration(callSummary.durationSec)}`;
|
||||
return t('remaining.call_history.call_length', { duration: formatCallDuration(callSummary.durationSec) });
|
||||
}
|
||||
const reason = String(callSummary.reason || '').trim().toLowerCase();
|
||||
if (reason === 'offline') return 'Абонент не в сети';
|
||||
if (reason === 'no_answer') return 'Нет ответа';
|
||||
if (reason === 'connect_failed') return 'Не удалось установить соединение';
|
||||
if (reason === 'busy') return 'Абонент занят';
|
||||
if (reason === 'declined') return 'Звонок отклонён';
|
||||
return 'Звонок не завершён';
|
||||
if (reason === 'offline') return t('remaining.call_history.user_is_offline');
|
||||
if (reason === 'no_answer') return t('remaining.call_history.no_answer');
|
||||
if (reason === 'connect_failed') return t('remaining.call_history.could_not_establish_a_connection');
|
||||
if (reason === 'busy') return t('remaining.call_history.user_is_busy');
|
||||
if (reason === 'declined') return t('remaining.call_history.call_declined');
|
||||
return t('remaining.call_history.call_was_not_completed');
|
||||
}
|
||||
|
||||
export function sanitizeUserDmTextForSend(rawText = '') {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
decryptJsonWithStoragePwd,
|
||||
encryptJsonWithStoragePwd,
|
||||
@@ -34,7 +35,7 @@ function openDb() {
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error || new Error('IndexedDB недоступен'));
|
||||
request.onerror = () => reject(request.error || new Error(t('remaining.key_storage.indexeddb_is_unavailable')));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -44,7 +45,7 @@ async function put(storeName, value) {
|
||||
const tx = db.transaction(storeName, 'readwrite');
|
||||
tx.objectStore(storeName).put(value);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error || new Error('Ошибка записи в IndexedDB'));
|
||||
tx.onerror = () => reject(tx.error || new Error(t('remaining.key_storage.could_not_write_to_indexeddb')));
|
||||
});
|
||||
db.close();
|
||||
}
|
||||
@@ -55,7 +56,7 @@ async function get(storeName, key) {
|
||||
const tx = db.transaction(storeName, 'readonly');
|
||||
const req = tx.objectStore(storeName).get(key);
|
||||
req.onsuccess = () => resolve(req.result || null);
|
||||
req.onerror = () => reject(req.error || new Error('Ошибка чтения из IndexedDB'));
|
||||
req.onerror = () => reject(req.error || new Error(t('remaining.key_storage.could_not_read_from_indexeddb')));
|
||||
});
|
||||
db.close();
|
||||
return result;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
|
||||
// Не обрезаем пароль: пробелы участвуют в формировании криптографических ключей.
|
||||
@@ -7,12 +8,12 @@ export function confirmPasswordBoundarySpaces(password) {
|
||||
const starts = /^\s/u.test(value);
|
||||
const ends = /\s$/u.test(value);
|
||||
if (!starts && !ends) return Promise.resolve(true);
|
||||
const where = starts && ends ? 'начинается и заканчивается пробелом'
|
||||
: starts ? 'начинается с пробела' : 'заканчивается пробелом';
|
||||
const where = starts && ends ? t('remaining.password.starts_and_ends_with_a_space')
|
||||
: starts ? t('remaining.password.starts_with_a_space') : t('remaining.password.ends_with_a_space');
|
||||
return confirmDialog({
|
||||
title: 'Пробел в пароле',
|
||||
text: `Ваш пароль ${where}. Такой пробел трудно заметить при следующем входе, но он является частью пароля и влияет на ключи доступа. Вы уверены, что хотите оставить его?`,
|
||||
confirmLabel: 'Да, оставить пароль',
|
||||
cancelLabel: 'Вернуться к паролю',
|
||||
title: t('remaining.password.space_in_password'),
|
||||
text: t('remaining.password.warning', { where }),
|
||||
confirmLabel: t('remaining.password.keep_password_as_entered'),
|
||||
cancelLabel: t('remaining.password.edit_password'),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
// Личные заметки о людях: текст и цветная метка, видны только владельцу аккаунта.
|
||||
// Пока хранятся на этом устройстве (localStorage, отдельно для каждого аккаунта) и на сервер
|
||||
// не уходят. Формат одной записи – { text, mark, updatedAt }: его же можно будет шифровать
|
||||
@@ -10,11 +11,11 @@ export const PEOPLE_NOTES_EVENT = 'shine-people-notes-updated';
|
||||
|
||||
// Цвет метки задаёт CSS (--note-mark-<id>), здесь только порядок и подписи для экранного диктора.
|
||||
export const NOTE_MARKS = [
|
||||
{ id: 'green', label: 'Зелёная метка' },
|
||||
{ id: 'yellow', label: 'Жёлтая метка' },
|
||||
{ id: 'red', label: 'Красная метка' },
|
||||
{ id: 'blue', label: 'Синяя метка' },
|
||||
{ id: 'violet', label: 'Фиолетовая метка' },
|
||||
{ id: 'green', get label() { return t('remaining.note_markers.green_marker'); } },
|
||||
{ id: 'yellow', get label() { return t('remaining.note_markers.yellow_marker'); } },
|
||||
{ id: 'red', get label() { return t('remaining.note_markers.red_marker'); } },
|
||||
{ id: 'blue', get label() { return t('remaining.note_markers.blue_marker'); } },
|
||||
{ id: 'violet', get label() { return t('remaining.note_markers.purple_marker'); } },
|
||||
];
|
||||
const MARK_IDS = new Set(NOTE_MARKS.map((mark) => mark.id));
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
// Minimal public preview sidebar, shown only to visitors without a session.
|
||||
export function mountPublicChannelSidebar(screen, { owner = '', channel = '', subscribers = null, avatar = null, navigate }) {
|
||||
@@ -11,17 +12,17 @@ export function mountPublicChannelSidebar(screen, { owner = '', channel = '', su
|
||||
face.replaceChildren(renderUserAvatar({ login: owner || 'unknown', size: 'sm' }));
|
||||
const details = document.createElement('div');
|
||||
const author = document.createElement('strong');
|
||||
author.textContent = owner || 'Автор';
|
||||
author.textContent = owner || t('remaining.public_channel.author');
|
||||
details.append(author);
|
||||
identity.append(face, details);
|
||||
const name = document.createElement('h2');
|
||||
name.textContent = channel || 'Канал';
|
||||
name.textContent = channel || t('remaining.public_channel.channel');
|
||||
const count = document.createElement('p');
|
||||
count.textContent = subscribers == null ? '' : `${Math.max(0, Number(subscribers) || 0)} подписчиков`;
|
||||
count.textContent = subscribers == null ? '' : t('remaining.public_channel.subscribers', { count: Math.max(0, Number(subscribers) || 0) });
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'primary-btn';
|
||||
button.textContent = 'Открыть в SHiNE';
|
||||
button.textContent = t('remaining.public_channel.open_in_shine');
|
||||
button.addEventListener('click', () => {
|
||||
window.sessionStorage.setItem('shine-public-return-path', window.location.pathname);
|
||||
navigate('login-view');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { importPkcs8Ed25519, signBase64 } from './crypto-utils.js';
|
||||
import { sha256HexFromArrayBuffer, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { loadSessionMaterial } from './key-vault.js';
|
||||
@@ -24,14 +25,14 @@ function wsUrlToHttpBase(wsUrl = '') {
|
||||
if (parsed.protocol === 'wss:') parsed.protocol = 'https:';
|
||||
else if (parsed.protocol === 'ws:') parsed.protocol = 'http:';
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error('Не удалось определить HTTP-адрес сервера доступа.');
|
||||
throw new Error(t('remaining.file_errors.could_not_determine_the_access_server_http_address'));
|
||||
}
|
||||
return parsed.origin;
|
||||
}
|
||||
|
||||
function publicFileUrl(serverBase, sha256) {
|
||||
const cleanSha = String(sha256 || '').trim().toLowerCase();
|
||||
if (!validateSha256Hex(cleanSha)) throw new Error('Некорректный SHA-256 файла.');
|
||||
if (!validateSha256Hex(cleanSha)) throw new Error(t('remaining.file_errors.invalid_file_sha_256'));
|
||||
return `${String(serverBase || '').replace(/\/$/, '')}/files/${cleanSha}`;
|
||||
}
|
||||
|
||||
@@ -57,13 +58,13 @@ async function readErrorMessage(response) {
|
||||
async function createUploadContext({ login, sessionId, wsUrl }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanSessionId = String(sessionId || '').trim();
|
||||
if (!cleanLogin || !cleanSessionId) throw new Error('Нет активной пользовательской сессии.');
|
||||
if (!cleanLogin || !cleanSessionId) throw new Error(t('remaining.file_errors.no_active_user_session'));
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin);
|
||||
if (!sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error('На устройстве нет session key для загрузки файла.');
|
||||
throw new Error(t('remaining.file_errors.session_key_for_uploading_files_is_missing_on_this_dev'));
|
||||
}
|
||||
if (sessionMaterial.sessionId && String(sessionMaterial.sessionId) !== cleanSessionId) {
|
||||
throw new Error('Сохранённый session key относится к другой сессии.');
|
||||
throw new Error(t('remaining.file_errors.saved_session_key_belongs_to_a_different_session'));
|
||||
}
|
||||
return {
|
||||
sessionId: cleanSessionId,
|
||||
@@ -73,16 +74,16 @@ async function createUploadContext({ login, sessionId, wsUrl }) {
|
||||
}
|
||||
|
||||
export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus = null } = {}) {
|
||||
if (!(file instanceof File)) throw new Error('Файл не выбран.');
|
||||
if (Number(file.size || 0) <= 0) throw new Error('Нельзя загрузить пустой файл.');
|
||||
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?.('Считаем SHA-256…');
|
||||
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?.('Проверяем, есть ли файл на сервере…');
|
||||
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) {
|
||||
@@ -111,7 +112,7 @@ export async function uploadPublicFile({ file, login, sessionId, wsUrl, onStatus
|
||||
timeMs,
|
||||
}));
|
||||
|
||||
onStatus?.('Загружаем на сервер доступа…');
|
||||
onStatus?.(t('remaining.file_upload.uploading_to_access_server'));
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
@@ -170,7 +171,7 @@ export async function resolvePublicFileUrl({
|
||||
}
|
||||
|
||||
const cleanLogin = String(authorLogin || '').trim().toLowerCase();
|
||||
if (!cleanLogin) throw new Error('Не указан автор server-вложения.');
|
||||
if (!cleanLogin) throw new Error(t('remaining.file_errors.server_attachment_author_is_missing'));
|
||||
const cacheKey = `${cleanLogin}|${String(solanaEndpoint || '').trim()}|${String(fallbackServerLogin || '').trim().toLowerCase()}`;
|
||||
const cached = accessServerCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.atMs < ACCESS_SERVER_CACHE_TTL_MS) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import qrcode from '../vendor-qrcode-generator.js';
|
||||
|
||||
const TRANSFER_PREFIX = 'shine-key-transfer-v1:';
|
||||
@@ -22,15 +23,15 @@ function base64UrlToBytes(value) {
|
||||
}
|
||||
|
||||
export function keyLabel(id) {
|
||||
if (id === 'blockchain') return 'ключ блокчейна';
|
||||
if (id === 'device' || id === 'client') return 'ключ доступа';
|
||||
if (id === 'blockchain') return t('remaining.qr_keys.blockchain_key');
|
||||
if (id === 'device' || id === 'client') return t('remaining.qr_keys.access_key');
|
||||
return id;
|
||||
}
|
||||
|
||||
export function describeTransferKeys(keys = {}) {
|
||||
const out = [];
|
||||
if (keys.clientKey) out.push('ключ доступа');
|
||||
if (keys.blockchainKey) out.push('ключ блокчейна');
|
||||
if (keys.clientKey) out.push(t('remaining.qr_keys.access_key'));
|
||||
if (keys.blockchainKey) out.push(t('remaining.qr_keys.blockchain_key'));
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -38,7 +39,7 @@ export function makeKeyTransferText({ login, keys }) {
|
||||
const clientKey = String(keys?.clientKey || '').trim();
|
||||
const blockchainKey = String(keys?.blockchainKey || '').trim();
|
||||
if (!clientKey || !blockchainKey) {
|
||||
throw new Error('Для подключения нужны ключ доступа и ключ блокчейна');
|
||||
throw new Error(t('remaining.qr_keys.both_an_access_key_and_blockchain_key_are_required_to_conn'));
|
||||
}
|
||||
const payload = {
|
||||
v: 1,
|
||||
@@ -54,20 +55,20 @@ export function makeKeyTransferText({ login, keys }) {
|
||||
export function parseKeyTransferText(text) {
|
||||
const raw = String(text || '').trim();
|
||||
if (!raw.startsWith(TRANSFER_PREFIX)) {
|
||||
throw new Error('Это не QR-код переноса ключей Сияния');
|
||||
throw new Error(t('remaining.qr_keys.this_is_not_a_shine_key_transfer_qr_code'));
|
||||
}
|
||||
const json = decoder.decode(base64UrlToBytes(raw.slice(TRANSFER_PREFIX.length)));
|
||||
const payload = JSON.parse(json);
|
||||
if (payload?.v !== 1 || payload?.type !== 'shine-key-transfer') {
|
||||
throw new Error('Неподдерживаемый формат QR-кода');
|
||||
throw new Error(t('remaining.qr_keys.unsupported_qr_code_format'));
|
||||
}
|
||||
const login = String(payload.login || '').trim();
|
||||
if (!login) throw new Error('В QR-коде нет логина');
|
||||
if (!login) throw new Error(t('remaining.qr_keys.no_login_found_in_qr_code'));
|
||||
const keys = payload.keys && typeof payload.keys === 'object' ? payload.keys : {};
|
||||
const clientKey = String(keys.clientKey || '').trim();
|
||||
const blockchainKey = String(keys.blockchainKey || '').trim();
|
||||
if (!clientKey || !blockchainKey) {
|
||||
throw new Error('В QR-коде нет полного набора рабочих ключей');
|
||||
throw new Error(t('remaining.qr_keys.qr_code_does_not_contain_all_required_keys'));
|
||||
}
|
||||
return {
|
||||
login,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
/** Единая стоимость регистрации: цена namespace уже включает депозит PDA. */
|
||||
export const USER_PDA_SPACE = 768; // shine-solana/shine/programs/shine_users/src/settings.rs
|
||||
// Запас для предварительной проверки баланса; сеть списывает фактическую комиссию.
|
||||
@@ -8,9 +9,9 @@ export const LAMPORTS_PER_SOL = 1_000_000_000;
|
||||
export function calculateRegistrationFunding({ namespaceFeeLamports, rentLamports }) {
|
||||
const namespaceFee = BigInt(namespaceFeeLamports);
|
||||
const rent = BigInt(rentLamports);
|
||||
if (namespaceFee < 0n || rent < 0n) throw new Error('Некорректная стоимость регистрации');
|
||||
if (namespaceFee < 0n || rent < 0n) throw new Error(t('remaining.registration_upgrade.invalid_registration_price'));
|
||||
if (namespaceFee < rent) {
|
||||
throw new Error(`Цена namespace (${solFromLamports(namespaceFee)} SOL) меньше депозита PDA (${solFromLamports(rent)} SOL). Регистрация временно недоступна: обратитесь к администратору namespace.`);
|
||||
throw new Error(t('remaining.registration_upgrade.price_below_rent', { price: solFromLamports(namespaceFee), rent: solFromLamports(rent) }));
|
||||
}
|
||||
const projectFee = namespaceFee - rent;
|
||||
const requiredLamports = namespaceFee + REGISTRATION_NETWORK_RESERVE_LAMPORTS;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
/** Разделённые шаги V2: независимая проверка логина, затем email. */
|
||||
import { authService } from '../state.js';
|
||||
import { normalizeFullLogin } from './shine-namespace-service.js';
|
||||
@@ -5,7 +6,7 @@ import { normalizeFullLogin } from './shine-namespace-service.js';
|
||||
async function call(op, payload = {}) {
|
||||
const response = await authService.ws.request(op, payload, op==='ConfirmFreeRegistration'?150000:18000);
|
||||
if (response.status !== 200 || response.ok === false) {
|
||||
const error=new Error(response.message || response.error || `${op}: ошибка сервера`);
|
||||
const error=new Error(response.message || response.error || t('remaining.registration_api.server_error', { op }));
|
||||
error.code=response.error || 'REGISTRATION_REQUEST_FAILED';
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
const SNAPSHOT_STORAGE_KEY = 'shine-ui-blockchain-snapshot-v1';
|
||||
|
||||
function normalizeLogin(login) {
|
||||
@@ -69,11 +70,11 @@ export async function buildBlockchainSnapshotFile({
|
||||
const cleanLogin = normalizeLogin(login);
|
||||
const cleanBlockchainName = String(blockchainName || '').trim();
|
||||
const maxBlockNumber = Number(lastBlockNumber);
|
||||
if (!authService?.ws?.request) throw new Error('Сервис сервера недоступен.');
|
||||
if (!cleanLogin) throw new Error('Не указан логин.');
|
||||
if (!cleanBlockchainName) throw new Error('Не указано имя блокчейна.');
|
||||
if (!authService?.ws?.request) throw new Error(t('remaining.blockchain_snapshot.server_service_unavailable'));
|
||||
if (!cleanLogin) throw new Error(t('remaining.blockchain_snapshot.login_missing'));
|
||||
if (!cleanBlockchainName) throw new Error(t('remaining.blockchain_snapshot.blockchain_name_missing'));
|
||||
if (!Number.isFinite(maxBlockNumber) || maxBlockNumber < 0) {
|
||||
throw new Error('На сервере нет блоков для слепка.');
|
||||
throw new Error(t('remaining.blockchain_snapshot.no_blocks_available_on_the_server_for_a_snapshot'));
|
||||
}
|
||||
|
||||
const parts = [];
|
||||
@@ -84,7 +85,7 @@ export async function buildBlockchainSnapshotFile({
|
||||
blockNumber,
|
||||
});
|
||||
if (response?.status !== 200) {
|
||||
const message = String(response?.payload?.message || response?.message || 'Не удалось получить блок.');
|
||||
const message = String(response?.payload?.message || response?.message || t('remaining.blockchain_snapshot.could_not_retrieve_block'));
|
||||
throw new Error(`Не удалось скачать блок ${blockNumber}: ${message}`);
|
||||
}
|
||||
const blockBytes = decodeBase64ToBytes(response?.payload?.blockBytesB64 || '');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { readShineUserPda } from './shine-user-pda-service.js';
|
||||
import {
|
||||
defaultServerAddress,
|
||||
@@ -63,7 +64,7 @@ export async function resolveShineServerByServerLogin({ serverLogin, solanaEndpo
|
||||
|
||||
export async function resolveShineServerForUserLogin({ login, solanaEndpoint, fallbackServerLogin = '' }) {
|
||||
const cleanLogin = normalizeShineServerLogin(login);
|
||||
if (!cleanLogin) throw new Error('Не указан логин пользователя для поиска сервера доступа.');
|
||||
if (!cleanLogin) throw new Error(t('remaining.server_resolver.user_login_is_required_to_find_an_access_server'));
|
||||
const parsedUser = await readShineUserPda({
|
||||
login: cleanLogin,
|
||||
solanaEndpoint,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { formatNumber } from '../i18n/format.js';
|
||||
import { confirmSolanaTransactionHttp, sendAndConfirmSolanaHttp } from './solana-rpc-gateway.js';
|
||||
import { extractEd25519Seed32FromStoredValue } from './client-key-utils.js';
|
||||
import { base64ToBytes } from './crypto-utils.js';
|
||||
@@ -53,7 +55,7 @@ export function solanaAddressFromPublicKeyBase64(publicKeyB64) {
|
||||
if (!clean) return '';
|
||||
const bytes = base64ToBytes(clean);
|
||||
if (bytes.length !== 32) {
|
||||
throw new Error('Публичный ключ Solana должен содержать 32 байта');
|
||||
throw new Error(t('remaining.solana_wallet_errors.solana_public_key_must_contain_32_bytes'));
|
||||
}
|
||||
return encodeBase58(bytes);
|
||||
}
|
||||
@@ -80,7 +82,7 @@ function decodeBase58(input) {
|
||||
const ch = text[i];
|
||||
const value = BASE58_MAP[ch];
|
||||
if (value == null) {
|
||||
throw new Error('Недопустимый символ Base58');
|
||||
throw new Error(t('remaining.solana_wallet_errors.invalid_base58_character'));
|
||||
}
|
||||
|
||||
let carry = value;
|
||||
@@ -126,7 +128,7 @@ async function keypairFromStoredSecret(storedSecret) {
|
||||
|
||||
export async function getSolanaWalletFromStoredSecret(storedSecret) {
|
||||
const clean = String(storedSecret || '').trim();
|
||||
if (!clean) throw new Error('Не передан приватный ключ');
|
||||
if (!clean) throw new Error(t('remaining.solana_wallet_errors.private_key_was_not_provided'));
|
||||
const keypair = await keypairFromStoredSecret(clean);
|
||||
return {
|
||||
address: keypair.publicKey.toBase58(),
|
||||
@@ -148,11 +150,11 @@ export async function createRandomSolanaWallet() {
|
||||
export async function createSolanaWalletFromPrivateBase58(privateKey32Base58) {
|
||||
const solana = await loadSolanaLib();
|
||||
const clean = String(privateKey32Base58 || '').trim();
|
||||
if (!clean) throw new Error('Введите приватный ключ');
|
||||
if (!BASE58_RE.test(clean)) throw new Error('Разрешены только символы Base58');
|
||||
if (!clean) throw new Error(t('remaining.solana_wallet.enter_a_private_key'));
|
||||
if (!BASE58_RE.test(clean)) throw new Error(t('remaining.solana_wallet.only_base58_characters_are_allowed'));
|
||||
const privateBytes = decodeBase58(clean);
|
||||
if (privateBytes.length !== 32) {
|
||||
throw new Error('Приватный ключ должен быть ровно 32 байта в Base58');
|
||||
throw new Error(t('remaining.solana_wallet_errors.private_key_must_be_exactly_32_bytes_in_base58'));
|
||||
}
|
||||
const keypair = solana.Keypair.fromSeed(privateBytes);
|
||||
return {
|
||||
@@ -166,12 +168,12 @@ export async function getWalletFromStoredClientKey({ login, storagePwd }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanPwd = String(storagePwd || '').trim();
|
||||
if (!cleanLogin || !cleanPwd) {
|
||||
throw new Error('Нет активной сессии для доступа к client.key');
|
||||
throw new Error(t('remaining.solana_wallet.no_active_session_to_access_client_key'));
|
||||
}
|
||||
const secrets = await loadEncryptedUserSecrets(cleanLogin, cleanPwd);
|
||||
const clientPrivate = String(secrets?.clientKey || '').trim();
|
||||
if (!clientPrivate) {
|
||||
throw new Error('На устройстве не найден client.key');
|
||||
throw new Error(t('remaining.solana_wallet.client_key_not_found_on_this_device'));
|
||||
}
|
||||
const keypair = await keypairFromStoredSecret(clientPrivate);
|
||||
return {
|
||||
@@ -186,12 +188,12 @@ export async function getWalletFromStoredBlockchainKey({ login, storagePwd }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanPwd = String(storagePwd || '').trim();
|
||||
if (!cleanLogin || !cleanPwd) {
|
||||
throw new Error('Нет активной сессии для доступа к blockchain.key');
|
||||
throw new Error(t('remaining.solana_wallet.no_active_session_to_access_blockchain_key'));
|
||||
}
|
||||
const secrets = await loadEncryptedUserSecrets(cleanLogin, cleanPwd);
|
||||
const blockchainPrivate = String(secrets?.blockchainKey || '').trim();
|
||||
if (!blockchainPrivate) {
|
||||
throw new Error('На устройстве не найден blockchain.key');
|
||||
throw new Error(t('remaining.solana_wallet.blockchain_key_not_found_on_this_device'));
|
||||
}
|
||||
const keypair = await keypairFromStoredSecret(blockchainPrivate);
|
||||
return {
|
||||
@@ -205,12 +207,12 @@ export async function getWalletFromStoredRootKey({ login, storagePwd }) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanPwd = String(storagePwd || '').trim();
|
||||
if (!cleanLogin || !cleanPwd) {
|
||||
throw new Error('Нет активной сессии для доступа к root key');
|
||||
throw new Error(t('remaining.solana_wallet.no_active_session_to_access_root_key'));
|
||||
}
|
||||
const secrets = await loadEncryptedUserSecrets(cleanLogin, cleanPwd);
|
||||
const rootPrivate = String(secrets?.rootKey || '').trim();
|
||||
if (!rootPrivate) {
|
||||
throw new Error('На устройстве не найден root key');
|
||||
throw new Error(t('remaining.solana_wallet.root_key_not_found_on_this_device'));
|
||||
}
|
||||
const keypair = await keypairFromStoredSecret(rootPrivate);
|
||||
return {
|
||||
@@ -223,12 +225,12 @@ export async function getWalletFromStoredRootKey({ login, storagePwd }) {
|
||||
export async function getStoredSolanaWalletChoices({ login, storagePwd } = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const cleanPwd = String(storagePwd || '').trim();
|
||||
if (!cleanLogin || !cleanPwd) throw new Error('Нет активной сессии для доступа к ключам');
|
||||
if (!cleanLogin || !cleanPwd) throw new Error(t('remaining.solana_wallet_errors.no_active_session_to_access_keys'));
|
||||
const wallet = await getWalletFromStoredBlockchainKey({ login: cleanLogin, storagePwd: cleanPwd });
|
||||
return [{
|
||||
id: 'blockchain-key',
|
||||
keySource: 'blockchain',
|
||||
label: 'Ключ блокчейна',
|
||||
label: t('remaining.solana_wallet.blockchain_key'),
|
||||
address: wallet.address,
|
||||
keypair: wallet.keypair,
|
||||
}];
|
||||
@@ -236,7 +238,7 @@ export async function getStoredSolanaWalletChoices({ login, storagePwd } = {}) {
|
||||
|
||||
export async function encodeSolanaSecretKeyBase58(secretKey) {
|
||||
const bytes = secretKey instanceof Uint8Array ? secretKey : Uint8Array.from(secretKey || []);
|
||||
if (!bytes.length) throw new Error('Пустой Solana secret key');
|
||||
if (!bytes.length) throw new Error(t('remaining.solana_wallet_errors.empty_solana_secret_key'));
|
||||
return encodeBase58(bytes);
|
||||
}
|
||||
|
||||
@@ -269,12 +271,12 @@ export async function transferSol({ endpoint, fromKeypair, toAddress, amountSol
|
||||
const rpc = normalizeEndpoint(endpoint);
|
||||
const cleanTo = String(toAddress || '').trim();
|
||||
const amount = Number(amountSol);
|
||||
if (!cleanTo) throw new Error('Не указан адрес получателя');
|
||||
if (!Number.isFinite(amount) || amount <= 0) throw new Error('Сумма перевода должна быть больше 0');
|
||||
if (!cleanTo) throw new Error(t('remaining.solana_wallet.recipient_address_missing'));
|
||||
if (!Number.isFinite(amount) || amount <= 0) throw new Error(t('remaining.solana_wallet.transfer_amount_must_be_greater_than_zero'));
|
||||
|
||||
const conn = new solana.Connection(rpc, 'confirmed');
|
||||
const lamports = Math.floor(amount * solana.LAMPORTS_PER_SOL);
|
||||
if (lamports <= 0) throw new Error('Сумма слишком мала');
|
||||
if (lamports <= 0) throw new Error(t('remaining.solana_wallet.amount_is_too_small'));
|
||||
|
||||
const tx = new solana.Transaction().add(
|
||||
solana.SystemProgram.transfer({
|
||||
@@ -292,10 +294,10 @@ export async function transferAllSol({ endpoint, fromKeypair, toAddress }) {
|
||||
const solana = await loadSolanaLib();
|
||||
const rpc = normalizeEndpoint(endpoint);
|
||||
const cleanTo = String(toAddress || '').trim();
|
||||
if (!fromKeypair?.publicKey) throw new Error('Не передан старый Solana-кошелёк');
|
||||
if (!cleanTo) throw new Error('Не указан новый адрес кошелька');
|
||||
if (!fromKeypair?.publicKey) throw new Error(t('remaining.solana_wallet.previous_solana_wallet_was_not_provided'));
|
||||
if (!cleanTo) throw new Error(t('remaining.solana_wallet.new_wallet_address_missing'));
|
||||
if (fromKeypair.publicKey.toBase58() === cleanTo) {
|
||||
throw new Error('Старый и новый кошельки совпадают');
|
||||
throw new Error(t('remaining.solana_wallet.old_and_new_wallet_addresses_are_the_same'));
|
||||
}
|
||||
|
||||
const conn = new solana.Connection(rpc, 'confirmed');
|
||||
@@ -351,7 +353,7 @@ export async function transferAllSol({ endpoint, fromKeypair, toAddress }) {
|
||||
export function formatSol(value, digits = 6) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
return n.toLocaleString('ru-RU', {
|
||||
return formatNumber(n, {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
const PIPER_LENGTH_SCALE_BY_QUALITY = {
|
||||
easy: '1.15',
|
||||
medium: '1.0',
|
||||
@@ -40,7 +41,7 @@ export async function speakTextBySettings(text, entrySettings) {
|
||||
|
||||
if (provider === 'piper-http') {
|
||||
const baseUrl = String(cfg.piperBaseUrl || '').trim().replace(/\/+$/, '');
|
||||
if (!baseUrl) throw new Error('Не указан адрес Piper HTTP.');
|
||||
if (!baseUrl) throw new Error(t('remaining.speech.piper_http_url_is_not_set'));
|
||||
const quality = String(cfg.quality || 'medium').toLowerCase();
|
||||
const voice = String(cfg.voice || '').trim();
|
||||
const lengthScale = PIPER_LENGTH_SCALE_BY_QUALITY[quality] || PIPER_LENGTH_SCALE_BY_QUALITY.medium;
|
||||
@@ -65,7 +66,7 @@ export async function speakTextBySettings(text, entrySettings) {
|
||||
|
||||
if (provider === 'openai') {
|
||||
const apiKey = String(cfg.apiKey || '').trim();
|
||||
if (!apiKey) throw new Error('Не заполнен API key для OpenAI TTS.');
|
||||
if (!apiKey) throw new Error(t('remaining.speech.openai_tts_api_key_is_missing'));
|
||||
const model = String(cfg.model || '').trim() || 'gpt-4o-mini-tts';
|
||||
const baseUrl = normalizeOpenAiBaseUrl(cfg.externalBaseUrl || cfg.baseUrl || 'https://api.openai.com/v1');
|
||||
const voice = String(cfg.voice || '').trim() || 'alloy';
|
||||
@@ -91,5 +92,5 @@ export async function speakTextBySettings(text, entrySettings) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error('Неизвестный провайдер озвучки.');
|
||||
throw new Error(t('remaining.speech.unknown_text_to_speech_provider'));
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
const STORAGE_KEY = 'shine-ui-theme-mode-v1';
|
||||
// Выбранная палитра и личные правки цветов (для дня и ночи отдельно).
|
||||
const PALETTE_KEY = 'shine-ui-palette-v1';
|
||||
@@ -9,30 +10,30 @@ let sessionMode = null;
|
||||
|
||||
// Роли цветов — тот же контракт, что в docs/UI-Design/DESIGN.md (раздел 4.1) и styles/main.css.
|
||||
export const PALETTE_ROLES = [
|
||||
{ id: 'background', label: 'Фон' },
|
||||
{ id: 'surface', label: 'Поверхности: поля, меню, карточки' },
|
||||
{ id: 'surface-selected', label: 'Выбранное и лёгкое выделение' },
|
||||
{ id: 'text-primary', label: 'Основной текст' },
|
||||
{ id: 'text-secondary', label: 'Вторичный текст: время, подсказки' },
|
||||
{ id: 'border-subtle', label: 'Разделители' },
|
||||
{ id: 'border-control', label: 'Рамки полей и кнопок' },
|
||||
{ id: 'surface-raised', label: 'Приподнятое: поля ввода, наведение' },
|
||||
{ id: 'accent', label: 'Акцент: главные кнопки, ссылки' },
|
||||
{ id: 'action', label: 'Вторичное действие: «Ответить», ссылки' },
|
||||
{ id: 'bubble-out', label: 'Исходящее сообщение' },
|
||||
{ id: 'on-accent', label: 'Текст на акцентной кнопке' },
|
||||
{ id: 'reaction-active', label: 'Поставленный лайк' },
|
||||
{ id: 'danger', label: 'Ошибки и удаление' },
|
||||
{ id: 'success', label: 'Успех' },
|
||||
{ id: 'warning', label: 'Предупреждение' },
|
||||
{ id: 'info', label: 'Информация, подсказки о процессе' },
|
||||
{ id: 'background', get label() { return t('remaining.theme.background'); } },
|
||||
{ id: 'surface', get label() { return t('remaining.theme.surfaces_inputs_menus_cards'); } },
|
||||
{ id: 'surface-selected', get label() { return t('remaining.theme.selection_and_subtle_highlighting'); } },
|
||||
{ id: 'text-primary', get label() { return t('remaining.theme.primary_text'); } },
|
||||
{ id: 'text-secondary', get label() { return t('remaining.theme.secondary_text_time_hints'); } },
|
||||
{ id: 'border-subtle', get label() { return t('remaining.theme.dividers'); } },
|
||||
{ id: 'border-control', get label() { return t('remaining.theme.input_and_button_borders'); } },
|
||||
{ id: 'surface-raised', get label() { return t('remaining.theme.raised_surfaces_inputs_and_hover'); } },
|
||||
{ id: 'accent', get label() { return t('remaining.theme.accent_primary_buttons_and_links'); } },
|
||||
{ id: 'action', get label() { return t('remaining.theme.secondary_actions_reply_and_links'); } },
|
||||
{ id: 'bubble-out', get label() { return t('remaining.theme.outgoing_message'); } },
|
||||
{ id: 'on-accent', get label() { return t('remaining.theme.text_on_accent_buttons'); } },
|
||||
{ id: 'reaction-active', get label() { return t('remaining.theme.liked_reaction'); } },
|
||||
{ id: 'danger', get label() { return t('remaining.theme.errors_and_destructive_actions'); } },
|
||||
{ id: 'success', get label() { return t('remaining.theme.success'); } },
|
||||
{ id: 'warning', get label() { return t('remaining.theme.warning'); } },
|
||||
{ id: 'info', get label() { return t('remaining.theme.information_and_progress_hints'); } },
|
||||
];
|
||||
|
||||
export const PALETTE_PRESETS = {
|
||||
// «Сияние» – цветовые роли макета V3/V4: тёмная тема из спецификации,
|
||||
// светлая подобрана отдельно, а не инверсией.
|
||||
aurora: {
|
||||
label: 'Сияние',
|
||||
get label() { return t('remaining.theme.shine'); },
|
||||
dark: {
|
||||
background: '#121419', surface: '#1c1f27', 'surface-selected': '#302b43', 'surface-raised': '#272a34',
|
||||
'text-primary': '#f1f1f5', 'text-secondary': '#a8abb8',
|
||||
@@ -69,7 +70,7 @@ export const PALETTE_PRESETS = {
|
||||
},
|
||||
},
|
||||
club: {
|
||||
label: 'Индиго',
|
||||
get label() { return t('remaining.theme.indigo'); },
|
||||
dark: {
|
||||
background: '#12141f', surface: '#1c2031', 'surface-selected': '#272c45',
|
||||
'text-primary': '#eceefa', 'text-secondary': '#a0a6c2',
|
||||
@@ -86,7 +87,7 @@ export const PALETTE_PRESETS = {
|
||||
},
|
||||
},
|
||||
shine: {
|
||||
label: 'Бирюза',
|
||||
get label() { return t('remaining.theme.turquoise'); },
|
||||
dark: {
|
||||
background: '#101b20', surface: '#17272d', 'surface-selected': '#213b3a',
|
||||
'text-primary': '#e8f2f1', 'text-secondary': '#98adaf',
|
||||
@@ -103,7 +104,7 @@ export const PALETTE_PRESETS = {
|
||||
},
|
||||
},
|
||||
mono: {
|
||||
label: 'Монохром',
|
||||
get label() { return t('remaining.theme.monochrome'); },
|
||||
dark: {
|
||||
background: '#111212', surface: '#1c1d1d', 'surface-selected': '#2c2d2d',
|
||||
'text-primary': '#f3f3f1', 'text-secondary': '#a3a3a0',
|
||||
@@ -128,28 +129,28 @@ function mixHex(first, second, amount) {
|
||||
}
|
||||
|
||||
const EXTRA_PRESETS = [
|
||||
['ocean', 'Океан', '#101c2b', '#182a3d', '#213c55', '#edf5ff', '#a6b9cf', '#75c8f0', '#102b40', '#f9fcff', '#e4f2fb', '#173247', '#536f83', '#087eae', '#ffffff'],
|
||||
['lavender', 'Лаванда', '#211b2b', '#30263d', '#473658', '#f5efff', '#bcb0cf', '#c5a0f5', '#f1ebf7', '#fffaff', '#e9def3', '#31283a', '#6d6076', '#7950a8', '#ffffff'],
|
||||
['graphite', 'Графит', '#17191c', '#222529', '#34383d', '#f2f4f5', '#adb4ba', '#c4cbd1', '#eef0f1', '#ffffff', '#e0e4e6', '#202427', '#5b646a', '#46535b', '#ffffff'],
|
||||
['sakura', 'Сакура', '#291b25', '#382430', '#503140', '#fff0f5', '#c9aab7', '#f39abb', '#fff0f4', '#fffafd', '#f7dce6', '#39232d', '#795967', '#b73565', '#ffffff'],
|
||||
['emerald', 'Изумруд', '#10231e', '#19332b', '#24483a', '#e8f8ef', '#a0c5ae', '#7fe0aa', '#eaf5ed', '#fbfffc', '#d8eddf', '#20372a', '#587363', '#187747', '#ffffff'],
|
||||
['sunrise', 'Рассвет', '#2b2017', '#3b2b1c', '#58402a', '#fff4df', '#d0b894', '#ffc36b', '#fff3df', '#fffaf0', '#f5e4c4', '#3a2b1b', '#78664c', '#a45c12', '#ffffff'],
|
||||
['cyberpunk', 'Киберпанк', '#171329', '#241b3b', '#382657', '#f5f0ff', '#b9a9d8', '#ff70dc', '#f6edfb', '#fffbff', '#eddcf5', '#30233b', '#705b7b', '#a12b91', '#ffffff'],
|
||||
['arctic', 'Арктика', '#14242a', '#1d333a', '#294750', '#edfaff', '#a7c4cc', '#82e2e5', '#e8f7f8', '#fbffff', '#d6eef0', '#20373a', '#587477', '#087f83', '#ffffff'],
|
||||
['coral', 'Коралл', '#2b1d1b', '#3a2925', '#563b34', '#fff1ec', '#d1b2a8', '#ff9d83', '#fff0e9', '#fffaf7', '#f9dfd4', '#3b2923', '#7b6258', '#bc4931', '#ffffff'],
|
||||
['grape', 'Виноград', '#211829', '#302238', '#493151', '#f8efff', '#c1a9cd', '#d39afa', '#f4eafa', '#fffaff', '#e9d8f2', '#35253d', '#725d7a', '#8145a9', '#ffffff'],
|
||||
['forest', 'Лес', '#19231b', '#263328', '#394b39', '#f0f7ed', '#b1c1a7', '#b0d17c', '#f0f4e8', '#fcfff7', '#e4ebd7', '#303828', '#69735d', '#52751f', '#ffffff'],
|
||||
['ruby', 'Рубин', '#28181e', '#382128', '#512e39', '#fff0f2', '#ceabb3', '#fa8095', '#fff0f1', '#fffafb', '#f4dce0', '#3c242b', '#795861', '#b52d4d', '#ffffff'],
|
||||
['lagoon', 'Лагуна', '#102323', '#193333', '#254949', '#e9f8f4', '#a1c4bc', '#67d8c2', '#e7f5ef', '#fbfffc', '#d3eee4', '#1e3932', '#56746b', '#087e70', '#ffffff'],
|
||||
['copper', 'Медь', '#281e19', '#392a22', '#533d30', '#fff2e8', '#ceb5a2', '#e9a879', '#f8eee5', '#fffaf5', '#eddfd1', '#392a21', '#786657', '#a65e2b', '#ffffff'],
|
||||
['neon', 'Неон', '#141f1b', '#1e3028', '#2b4939', '#edfff2', '#a6c6ae', '#a7f36b', '#eff7e9', '#fcfff8', '#dff0d0', '#253923', '#5b7352', '#4c861d', '#ffffff'],
|
||||
['paper', 'Бумага', '#20201e', '#2e2e2b', '#454540', '#f6f5ef', '#bcbcb2', '#d6c49b', '#f3f0e8', '#fffdf7', '#e8e2d3', '#302e28', '#716d61', '#76613b', '#ffffff'],
|
||||
['cosmos', 'Космос', '#171a30', '#222744', '#323b62', '#f0f2ff', '#aeb6d6', '#9eacff', '#edf0fc', '#fbfcff', '#dfe4fa', '#252b46', '#5c6687', '#4f61c5', '#ffffff'],
|
||||
['mint', 'Мята', '#14231f', '#1f332c', '#2e4940', '#ebfbf4', '#a9c6b9', '#8fe2c0', '#eaf5ee', '#fbfffc', '#d7eee1', '#21392f', '#597568', '#16805b', '#ffffff'],
|
||||
['sandstone', 'Песчаник', '#272019', '#382e23', '#514333', '#fff5e8', '#c9b69c', '#f0bd78', '#f6efe3', '#fffdf8', '#e9deca', '#3a3023', '#776b58', '#96601b', '#ffffff'],
|
||||
['dusk', 'Сумерки', '#211b2a', '#30263c', '#493658', '#f5efff', '#b8acc8', '#e0a6c8', '#f2edf4', '#fffaff', '#e8dfe9', '#352a39', '#706174', '#98577d', '#ffffff'],
|
||||
['lemon', 'Лимон', '#202216', '#30331e', '#454a2b', '#f8f9e9', '#bfc39c', '#e2e96d', '#f2f3e3', '#fdfff5', '#e6e9cc', '#353822', '#71755a', '#737c16', '#ffffff'],
|
||||
['obsidian', 'Обсидиан', '#151719', '#202326', '#30363b', '#f2f5f7', '#aab5bc', '#8db7c7', '#e9eef0', '#fbfeff', '#dce5e8', '#252c30', '#5c6a70', '#3b778c', '#ffffff'],
|
||||
['ocean', null, '#101c2b', '#182a3d', '#213c55', '#edf5ff', '#a6b9cf', '#75c8f0', '#102b40', '#f9fcff', '#e4f2fb', '#173247', '#536f83', '#087eae', '#ffffff'],
|
||||
['lavender', null, '#211b2b', '#30263d', '#473658', '#f5efff', '#bcb0cf', '#c5a0f5', '#f1ebf7', '#fffaff', '#e9def3', '#31283a', '#6d6076', '#7950a8', '#ffffff'],
|
||||
['graphite', null, '#17191c', '#222529', '#34383d', '#f2f4f5', '#adb4ba', '#c4cbd1', '#eef0f1', '#ffffff', '#e0e4e6', '#202427', '#5b646a', '#46535b', '#ffffff'],
|
||||
['sakura', null, '#291b25', '#382430', '#503140', '#fff0f5', '#c9aab7', '#f39abb', '#fff0f4', '#fffafd', '#f7dce6', '#39232d', '#795967', '#b73565', '#ffffff'],
|
||||
['emerald', null, '#10231e', '#19332b', '#24483a', '#e8f8ef', '#a0c5ae', '#7fe0aa', '#eaf5ed', '#fbfffc', '#d8eddf', '#20372a', '#587363', '#187747', '#ffffff'],
|
||||
['sunrise', null, '#2b2017', '#3b2b1c', '#58402a', '#fff4df', '#d0b894', '#ffc36b', '#fff3df', '#fffaf0', '#f5e4c4', '#3a2b1b', '#78664c', '#a45c12', '#ffffff'],
|
||||
['cyberpunk', null, '#171329', '#241b3b', '#382657', '#f5f0ff', '#b9a9d8', '#ff70dc', '#f6edfb', '#fffbff', '#eddcf5', '#30233b', '#705b7b', '#a12b91', '#ffffff'],
|
||||
['arctic', null, '#14242a', '#1d333a', '#294750', '#edfaff', '#a7c4cc', '#82e2e5', '#e8f7f8', '#fbffff', '#d6eef0', '#20373a', '#587477', '#087f83', '#ffffff'],
|
||||
['coral', null, '#2b1d1b', '#3a2925', '#563b34', '#fff1ec', '#d1b2a8', '#ff9d83', '#fff0e9', '#fffaf7', '#f9dfd4', '#3b2923', '#7b6258', '#bc4931', '#ffffff'],
|
||||
['grape', null, '#211829', '#302238', '#493151', '#f8efff', '#c1a9cd', '#d39afa', '#f4eafa', '#fffaff', '#e9d8f2', '#35253d', '#725d7a', '#8145a9', '#ffffff'],
|
||||
['forest', null, '#19231b', '#263328', '#394b39', '#f0f7ed', '#b1c1a7', '#b0d17c', '#f0f4e8', '#fcfff7', '#e4ebd7', '#303828', '#69735d', '#52751f', '#ffffff'],
|
||||
['ruby', null, '#28181e', '#382128', '#512e39', '#fff0f2', '#ceabb3', '#fa8095', '#fff0f1', '#fffafb', '#f4dce0', '#3c242b', '#795861', '#b52d4d', '#ffffff'],
|
||||
['lagoon', null, '#102323', '#193333', '#254949', '#e9f8f4', '#a1c4bc', '#67d8c2', '#e7f5ef', '#fbfffc', '#d3eee4', '#1e3932', '#56746b', '#087e70', '#ffffff'],
|
||||
['copper', null, '#281e19', '#392a22', '#533d30', '#fff2e8', '#ceb5a2', '#e9a879', '#f8eee5', '#fffaf5', '#eddfd1', '#392a21', '#786657', '#a65e2b', '#ffffff'],
|
||||
['neon', null, '#141f1b', '#1e3028', '#2b4939', '#edfff2', '#a6c6ae', '#a7f36b', '#eff7e9', '#fcfff8', '#dff0d0', '#253923', '#5b7352', '#4c861d', '#ffffff'],
|
||||
['paper', null, '#20201e', '#2e2e2b', '#454540', '#f6f5ef', '#bcbcb2', '#d6c49b', '#f3f0e8', '#fffdf7', '#e8e2d3', '#302e28', '#716d61', '#76613b', '#ffffff'],
|
||||
['cosmos', null, '#171a30', '#222744', '#323b62', '#f0f2ff', '#aeb6d6', '#9eacff', '#edf0fc', '#fbfcff', '#dfe4fa', '#252b46', '#5c6687', '#4f61c5', '#ffffff'],
|
||||
['mint', null, '#14231f', '#1f332c', '#2e4940', '#ebfbf4', '#a9c6b9', '#8fe2c0', '#eaf5ee', '#fbfffc', '#d7eee1', '#21392f', '#597568', '#16805b', '#ffffff'],
|
||||
['sandstone', null, '#272019', '#382e23', '#514333', '#fff5e8', '#c9b69c', '#f0bd78', '#f6efe3', '#fffdf8', '#e9deca', '#3a3023', '#776b58', '#96601b', '#ffffff'],
|
||||
['dusk', null, '#211b2a', '#30263c', '#493658', '#f5efff', '#b8acc8', '#e0a6c8', '#f2edf4', '#fffaff', '#e8dfe9', '#352a39', '#706174', '#98577d', '#ffffff'],
|
||||
['lemon', null, '#202216', '#30331e', '#454a2b', '#f8f9e9', '#bfc39c', '#e2e96d', '#f2f3e3', '#fdfff5', '#e6e9cc', '#353822', '#71755a', '#737c16', '#ffffff'],
|
||||
['obsidian', null, '#151719', '#202326', '#30363b', '#f2f5f7', '#aab5bc', '#8db7c7', '#e9eef0', '#fbfeff', '#dce5e8', '#252c30', '#5c6a70', '#3b778c', '#ffffff'],
|
||||
];
|
||||
|
||||
function makePreset(label, dark, light) {
|
||||
@@ -177,8 +178,33 @@ function makePreset(label, dark, light) {
|
||||
return { label, dark: toColors(dark, 'dark'), light: toColors(light, 'light') };
|
||||
}
|
||||
|
||||
const EXTRA_PRESET_LABEL_KEYS = {
|
||||
'ocean': 'remaining.theme.ocean',
|
||||
'lavender': 'remaining.theme.lavender',
|
||||
'graphite': 'remaining.theme.graphite',
|
||||
'sakura': 'remaining.theme.sakura',
|
||||
'emerald': 'remaining.theme.emerald',
|
||||
'sunrise': 'remaining.theme.sunrise',
|
||||
'cyberpunk': 'remaining.theme.cyberpunk',
|
||||
'arctic': 'remaining.theme.arctic',
|
||||
'coral': 'remaining.theme.coral',
|
||||
'grape': 'remaining.theme.grape',
|
||||
'forest': 'remaining.theme.forest',
|
||||
'ruby': 'remaining.theme.ruby',
|
||||
'lagoon': 'remaining.theme.lagoon',
|
||||
'copper': 'remaining.theme.copper',
|
||||
'neon': 'remaining.theme.neon',
|
||||
'paper': 'remaining.theme.paper',
|
||||
'cosmos': 'remaining.theme.cosmos',
|
||||
'mint': 'remaining.theme.mint',
|
||||
'sandstone': 'remaining.theme.sandstone',
|
||||
'dusk': 'remaining.theme.dusk',
|
||||
'lemon': 'remaining.theme.lemon',
|
||||
'obsidian': 'remaining.theme.obsidian',
|
||||
};
|
||||
for (const [id, label, ...colors] of EXTRA_PRESETS) {
|
||||
PALETTE_PRESETS[id] = makePreset(label, colors.slice(0, 7), colors.slice(7));
|
||||
Object.defineProperty(PALETTE_PRESETS[id], 'label', { enumerable: true, get: () => t(EXTRA_PRESET_LABEL_KEYS[id]) });
|
||||
}
|
||||
|
||||
const DEFAULT_PRESET = 'aurora';
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { formatNumber } from '../i18n/format.js';
|
||||
import { getBalanceSol, getStoredSolanaWalletChoices, encodeSolanaSecretKeyBase58, formatSol } from './solana-wallet-service.js';
|
||||
import { state } from '../state.js';
|
||||
|
||||
@@ -10,17 +12,17 @@ function parseSolToLamports(amountSol) {
|
||||
const raw = String(amountSol ?? '').trim().replace(',', '.');
|
||||
const match = raw.match(/^(\d+)(?:\.(\d+))?$/);
|
||||
if (!match) {
|
||||
throw new Error('Сумма пополнения должна быть числом');
|
||||
throw new Error(t('remaining.turbo.top_up_amount_must_be_a_number'));
|
||||
}
|
||||
const intPart = BigInt(match[1] || '0');
|
||||
const frac = String(match[2] || '');
|
||||
if (frac.length > 9) {
|
||||
throw new Error('Слишком много знаков после запятой для SOL');
|
||||
throw new Error(t('remaining.turbo.too_many_decimal_places_for_sol'));
|
||||
}
|
||||
const fracPadded = `${frac}${'0'.repeat(9 - frac.length)}`;
|
||||
const lamports = (intPart * 1_000_000_000n) + BigInt(fracPadded || '0');
|
||||
if (lamports <= 0n) {
|
||||
throw new Error('Сумма пополнения должна быть больше 0');
|
||||
throw new Error(t('remaining.turbo.top_up_amount_must_be_greater_than_zero'));
|
||||
}
|
||||
return lamports.toString();
|
||||
}
|
||||
@@ -41,7 +43,7 @@ async function getTurboWalletChoice({ login, storagePwd, keySource = 'blockchain
|
||||
const choices = await getStoredSolanaWalletChoices({ login, storagePwd });
|
||||
const selected = choices.find((item) => item.keySource === normalizedKeySource) || choices[0] || null;
|
||||
if (!selected?.keypair) {
|
||||
throw new Error('На устройстве не найден blockchain key для Turbo.');
|
||||
throw new Error(t('remaining.turbo.blockchain_key_for_turbo_not_found_on_this_device'));
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
@@ -50,7 +52,7 @@ async function createTurboClientFromWalletChoice(choice) {
|
||||
const moduleRef = await loadTurboLib();
|
||||
const TurboFactory = moduleRef?.TurboFactory;
|
||||
if (!TurboFactory?.authenticated) {
|
||||
throw new Error('Turbo SDK не удалось инициализировать.');
|
||||
throw new Error(t('remaining.turbo.could_not_initialize_turbo_sdk'));
|
||||
}
|
||||
const privateKey = await encodeSolanaSecretKeyBase58(choice.keypair.secretKey);
|
||||
return TurboFactory.authenticated({
|
||||
@@ -82,7 +84,7 @@ export function getFreeTurboUploadBytesLimit() {
|
||||
export function formatTurboCredits(value, digits = 6) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
return n.toLocaleString('ru-RU', {
|
||||
return formatNumber(n, {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
@@ -124,13 +126,13 @@ export async function getTurboBalanceForStoredSolanaKey({ login, storagePwd, key
|
||||
export async function estimateTurboUploadPrice({ login, storagePwd, keySource = 'blockchain', byteLength } = {}) {
|
||||
const bytes = Number(byteLength);
|
||||
if (!Number.isInteger(bytes) || bytes <= 0) {
|
||||
throw new Error('Некорректный размер файла для Turbo.');
|
||||
throw new Error(t('remaining.turbo.invalid_file_size_for_turbo'));
|
||||
}
|
||||
const ctx = await getTurboContextForStoredSolanaKey({ login, storagePwd, keySource });
|
||||
const rows = await ctx.turbo.getUploadCosts({ bytes: [bytes] });
|
||||
const price = Array.isArray(rows) ? rows[0] : null;
|
||||
if (!price) {
|
||||
throw new Error('Turbo не вернул цену загрузки.');
|
||||
throw new Error(t('remaining.turbo.turbo_did_not_return_an_upload_price'));
|
||||
}
|
||||
const winc = String(price.winc || '0');
|
||||
return {
|
||||
@@ -152,7 +154,7 @@ export async function uploadFileWithTurbo({
|
||||
onProgress,
|
||||
} = {}) {
|
||||
if (!(file instanceof File)) {
|
||||
throw new Error('Выберите файл для загрузки через Turbo.');
|
||||
throw new Error(t('remaining.turbo.select_a_file_to_upload_through_turbo'));
|
||||
}
|
||||
const ctx = await getTurboContextForStoredSolanaKey({ login, storagePwd, keySource });
|
||||
const result = await ctx.turbo.uploadFile({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { getLanguage, t } from '../i18n/index.js';
|
||||
import { isDeveloperToolsEnabled } from './feature-settings.js';
|
||||
|
||||
// Сетевые ошибки браузера (fetch, загрузка файла) – одним понятным текстом.
|
||||
@@ -163,6 +163,11 @@ export function toUserMessage(error, fallback = t('errors.text_002')) {
|
||||
}
|
||||
|
||||
if (!raw) return fallback;
|
||||
// Internal exceptions may contain Russian text even when the UI is in English.
|
||||
// Do not leak untranslated technical messages into the interface.
|
||||
if (getLanguage() !== 'ru' && HAS_CYRILLIC_RE.test(raw)) {
|
||||
return fallback || t('remaining.errors.generic');
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
@@ -178,7 +183,7 @@ export function actionErrorText(action, error) {
|
||||
return /^(не удалось|ошибка|нельзя|сначала)/i.test(raw) ? raw : `${action}: ${raw}`;
|
||||
}
|
||||
if (raw && isDeveloperToolsEnabled()) return `${action}: ${raw}`;
|
||||
return `${action}. Попробуйте ещё раз.`;
|
||||
return t('remaining.errors.try_again', { action });
|
||||
}
|
||||
|
||||
// Микрофон и камера (getUserMedia): у этих ошибок смысл несёт имя, а не текст. Имена общие
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadProfileSnapshot } from './user-profile-params.js';
|
||||
import { buildAvatarInitials as buildAvatarInitialsFromComponent } from '../components/avatar-image.js';
|
||||
@@ -240,7 +241,7 @@ export async function loadUserProfileCard(login) {
|
||||
loadProfileSnapshot(cleanLogin),
|
||||
]);
|
||||
|
||||
if (!user?.exists) throw new Error('Пользователь не найден');
|
||||
if (!user?.exists) throw new Error(t('remaining.connections.user_not_found'));
|
||||
|
||||
const canonicalLogin = normalizeLogin(user.login || cleanLogin);
|
||||
const fields = toFieldMap(snapshot);
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { validateArweaveTxId, validateSha256Hex } from './arweave-file-service.js';
|
||||
import { buildAvatarReference, parseAvatarReference } from './avatar-reference.js';
|
||||
import { CITY_MAX_LENGTH, CITY_PARAM, CITY_SUGGESTIONS } from './cities.js';
|
||||
|
||||
export const profileFieldDefs = [
|
||||
{ key: 'first_name', readKeys: ['first_name'], label: 'Имя', placeholder: 'Введите имя' },
|
||||
{ key: 'last_name', readKeys: ['last_name'], label: 'Фамилия', placeholder: 'Введите фамилию' },
|
||||
{ key: 'first_name', readKeys: ['first_name'], get label() { return t('remaining.profile_fields.first_name'); }, get placeholder() { return t('remaining.profile_fields.enter_your_first_name'); } },
|
||||
{ key: 'last_name', readKeys: ['last_name'], get label() { return t('remaining.profile_fields.last_name'); }, get placeholder() { return t('remaining.profile_fields.enter_your_last_name'); } },
|
||||
// Город виден в профиле и собирает знакомых в раскладке «Города» на карте связей.
|
||||
{ key: CITY_PARAM, readKeys: [CITY_PARAM], label: 'Город', placeholder: 'Например, Казань', maxLength: CITY_MAX_LENGTH, suggestions: CITY_SUGGESTIONS },
|
||||
{ key: 'address', readKeys: ['address'], label: 'Адрес', placeholder: 'Улица, дом' },
|
||||
{ key: 'web', readKeys: ['web'], label: 'Ссылки', placeholder: 'Сайт, профиль или другая ссылка' },
|
||||
{ key: 'phone', readKeys: ['phone'], label: 'Телефон', placeholder: '+7 ...' },
|
||||
{ key: 'about', readKeys: ['about'], label: 'О себе', placeholder: 'Коротко расскажите о себе', maxLength: 160, multiline: true },
|
||||
{ key: 'spiritual_path', readKeys: ['spiritual_path'], label: 'Духовный путь', placeholder: 'Расскажите о своём духовном пути, опыте, практиках и взглядах', maxLength: 5000, multiline: true },
|
||||
{ key: CITY_PARAM, readKeys: [CITY_PARAM], get label() { return t('remaining.profile_fields.city'); }, get placeholder() { return t('remaining.profile_fields.for_example_london'); }, maxLength: CITY_MAX_LENGTH, suggestions: CITY_SUGGESTIONS },
|
||||
{ key: 'address', readKeys: ['address'], get label() { return t('remaining.profile_fields.address'); }, get placeholder() { return t('remaining.profile_fields.street_and_house_number'); } },
|
||||
{ key: 'web', readKeys: ['web'], get label() { return t('remaining.profile_fields.links'); }, get placeholder() { return t('remaining.profile_fields.website_profile_or_other_link'); } },
|
||||
{ key: 'phone', readKeys: ['phone'], get label() { return t('remaining.profile_fields.phone'); }, placeholder: '+7 ...' },
|
||||
{ key: 'about', readKeys: ['about'], get label() { return t('remaining.profile_fields.about_me'); }, get placeholder() { return t('remaining.profile_fields.tell_us_a_little_about_yourself'); }, maxLength: 160, multiline: true },
|
||||
{ key: 'spiritual_path', readKeys: ['spiritual_path'], get label() { return t('remaining.profile_fields.spiritual_path'); }, get placeholder() { return t('remaining.profile_fields.share_your_spiritual_journey_experience_practices_and_view'); }, maxLength: 5000, multiline: true },
|
||||
];
|
||||
|
||||
export const profileToggleDefs = []; // legacy boolean toggles are no longer used by the new UI.
|
||||
@@ -60,7 +61,7 @@ function normalizeGenderValue(value) {
|
||||
async function getStoragePwd() {
|
||||
const storagePwd = state.session.storagePwdInMemory;
|
||||
if (!storagePwd) {
|
||||
throw new Error('Нет storagePwd в памяти сессии. Выполните вход заново.');
|
||||
throw new Error(t('remaining.profile_errors.session_password_is_unavailable_sign_in_again'));
|
||||
}
|
||||
return storagePwd;
|
||||
}
|
||||
@@ -131,8 +132,8 @@ export async function loadProfileSnapshot(login) {
|
||||
// Legacy shine=no is intentionally ignored. Legacy official=yes/no is not read at all.
|
||||
|
||||
const toggles = [
|
||||
{ key: 'account_role', label: 'Роль аккаунта', enabled: accountRole === PROFILE_ACCOUNT_ROLE_PRIMARY, rawValue: accountRole, timeMs: latestAccountRole?.timeMs || 0 },
|
||||
{ key: 'shine', label: 'Сияние', enabled: shineStatus === PROFILE_SHINE_SHINING, rawValue: shineStatus, timeMs: latestShine?.timeMs || 0 },
|
||||
{ key: 'account_role', get label() { return t('remaining.profile_fields.account_role'); }, enabled: accountRole === PROFILE_ACCOUNT_ROLE_PRIMARY, rawValue: accountRole, timeMs: latestAccountRole?.timeMs || 0 },
|
||||
{ key: 'shine', get label() { return t('remaining.profile_fields.shine'); }, enabled: shineStatus === PROFILE_SHINE_SHINING, rawValue: shineStatus, timeMs: latestShine?.timeMs || 0 },
|
||||
];
|
||||
|
||||
const latestGender = loadLatestByAliasesFromItems(items, ['gender']);
|
||||
@@ -186,10 +187,10 @@ export async function saveProfileStatus(login, key, value) {
|
||||
const cleanKey = String(key || '').trim();
|
||||
const cleanValue = String(value || '').trim().toLowerCase();
|
||||
if (cleanKey === 'account_role' && ![PROFILE_ACCOUNT_ROLE_PRIMARY, PROFILE_ACCOUNT_ROLE_NON_VOTING].includes(cleanValue)) {
|
||||
throw new Error('Некорректное значение account_role');
|
||||
throw new Error(t('remaining.profile_errors.invalid_account_role_value'));
|
||||
}
|
||||
if (cleanKey === 'shine' && ![PROFILE_SHINE_SHINING, PROFILE_SHINE_UNKNOWN, PROFILE_SHINE_NOT_INTERESTED].includes(cleanValue)) {
|
||||
throw new Error('Некорректное значение shine');
|
||||
throw new Error(t('remaining.profile_errors.invalid_shine_value'));
|
||||
}
|
||||
const storagePwd = await getStoragePwd();
|
||||
await authService.addBlockUserParam({ login, param: cleanKey, value: cleanValue, storagePwd });
|
||||
@@ -198,7 +199,7 @@ export async function saveProfileStatus(login, key, value) {
|
||||
// Kept only for old callers outside the current UI. New code must use saveProfileStatus().
|
||||
export async function saveProfileToggle(login, key, enabled) {
|
||||
if (key === 'shine') return saveProfileStatus(login, 'shine', enabled ? PROFILE_SHINE_SHINING : PROFILE_SHINE_UNKNOWN);
|
||||
if (key === 'official') throw new Error('Параметр official устарел. Используйте account_role.');
|
||||
if (key === 'official') throw new Error(t('remaining.profile_errors.the_official_parameter_is_deprecated_use_account_role'));
|
||||
throw new Error(`Неизвестный legacy toggle: ${key}`);
|
||||
}
|
||||
|
||||
@@ -217,8 +218,8 @@ export async function saveProfileAvatar(login, avatar) {
|
||||
const cleanAr = String(avatar?.ar || '').trim();
|
||||
const cleanSha = String(avatar?.sha256 || avatar?.sha256Hex || '').trim().toLowerCase();
|
||||
const size = Number(avatar?.size || 0);
|
||||
if (cleanAr && !validateArweaveTxId(cleanAr)) throw new Error('Некорректный Transaction ID Arweave');
|
||||
if (!validateSha256Hex(cleanSha)) throw new Error('Некорректный SHA256 хэш аватара');
|
||||
if (cleanAr && !validateArweaveTxId(cleanAr)) throw new Error(t('remaining.profile_errors.invalid_arweave_transaction_id'));
|
||||
if (!validateSha256Hex(cleanSha)) throw new Error(t('remaining.profile_errors.invalid_avatar_sha_256_hash'));
|
||||
await saveProfileParamBlock(login, 'ava', buildAvatarReference({ ar: cleanAr, sha256: cleanSha, size }));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { captureClientError } from './client-error-reporter.js';
|
||||
import { defaultServerWs } from '../deploy-config.js';
|
||||
|
||||
@@ -69,7 +70,7 @@ export class WsJsonClient {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
|
||||
if (this.openPromise) return this.openPromise;
|
||||
if (isMixedContentWs(this.url)) {
|
||||
const error = new Error('Страница открыта по HTTPS, а сервер указан как ws://. Используйте wss:// адрес для Shine сервера.');
|
||||
const error = new Error(t('remaining.websocket.this_page_uses_https_but_the_server_uses_ws_use_wss_for_th'));
|
||||
captureClientError({
|
||||
kind: 'ws_mixed_content_blocked',
|
||||
message: error.message,
|
||||
@@ -96,7 +97,7 @@ export class WsJsonClient {
|
||||
}, { once: true });
|
||||
|
||||
ws.addEventListener('close', () => {
|
||||
this.failPending('Соединение WebSocket закрыто');
|
||||
this.failPending(t('remaining.websocket.websocket_connection_closed'));
|
||||
});
|
||||
|
||||
ws.addEventListener('message', (event) => {
|
||||
|
||||
Reference in New Issue
Block a user