diff --git a/SHiNE-server/shine-server-db/src/main/java/shine/db/DatabaseInitializer.java b/SHiNE-server/shine-server-db/src/main/java/shine/db/DatabaseInitializer.java index 793c49a1..ea9f4932 100644 --- a/SHiNE-server/shine-server-db/src/main/java/shine/db/DatabaseInitializer.java +++ b/SHiNE-server/shine-server-db/src/main/java/shine/db/DatabaseInitializer.java @@ -21,10 +21,18 @@ public final class DatabaseInitializer { public static final int SCHEMA_VERSION_2 = 2; public static final int SCHEMA_VERSION_3 = 3; public static final int SCHEMA_VERSION_4 = 4; + public static final int SCHEMA_VERSION_5 = 5; + public static final int SCHEMA_VERSION_6 = 6; + public static final int SCHEMA_VERSION_7 = 7; + public static final int SCHEMA_VERSION_8 = 8; public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql"; public static final String POSTGRES_MIGRATION_V2_RESOURCE = "postgres/migration_v2.sql"; public static final String POSTGRES_MIGRATION_V3_RESOURCE = "postgres/migration_v3.sql"; public static final String POSTGRES_MIGRATION_V4_RESOURCE = "postgres/migration_v4.sql"; + public static final String POSTGRES_MIGRATION_V5_RESOURCE = "postgres/migration_v5.sql"; + public static final String POSTGRES_MIGRATION_V6_RESOURCE = "postgres/migration_v6.sql"; + public static final String POSTGRES_MIGRATION_V7_RESOURCE = "postgres/migration_v7.sql"; + public static final String POSTGRES_MIGRATION_V8_RESOURCE = "postgres/migration_v8.sql"; private DatabaseInitializer() {} @@ -100,6 +108,22 @@ public final class DatabaseInitializer { } if (currentVersion < SCHEMA_VERSION_4) { runSqlScript(conn, POSTGRES_MIGRATION_V4_RESOURCE); + currentVersion = SCHEMA_VERSION_4; + } + if (currentVersion < SCHEMA_VERSION_5) { + runSqlScript(conn, POSTGRES_MIGRATION_V5_RESOURCE); + currentVersion = SCHEMA_VERSION_5; + } + if (currentVersion < SCHEMA_VERSION_6) { + runSqlScript(conn, POSTGRES_MIGRATION_V6_RESOURCE); + currentVersion = SCHEMA_VERSION_6; + } + if (currentVersion < SCHEMA_VERSION_7) { + runSqlScript(conn, POSTGRES_MIGRATION_V7_RESOURCE); + currentVersion = SCHEMA_VERSION_7; + } + if (currentVersion < SCHEMA_VERSION_8) { + runSqlScript(conn, POSTGRES_MIGRATION_V8_RESOURCE); } } } diff --git a/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/CurrentUsersDAO.java b/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/CurrentUsersDAO.java index ec61b084..33d47ff7 100644 --- a/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/CurrentUsersDAO.java +++ b/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/CurrentUsersDAO.java @@ -49,7 +49,7 @@ public final class CurrentUsersDAO { String sql = """ SELECT 1 FROM %s - WHERE LOWER(login) = LOWER(?) + WHERE normalized_login = LOWER(BTRIM(?)) LIMIT 1 """.formatted(CurrentUsersSql.usersSubquery("su")); @@ -104,7 +104,7 @@ public final class CurrentUsersDAO { blockchain_key, client_key FROM %s - WHERE LOWER(login) = LOWER(?) + WHERE normalized_login = LOWER(BTRIM(?)) """.formatted(CurrentUsersSql.usersSubquery("su")); try (PreparedStatement ps = c.prepareStatement(sql)) { @@ -167,7 +167,7 @@ public final class CurrentUsersDAO { blockchain_key, client_key FROM %s - WHERE LOWER(login) LIKE ? + WHERE normalized_login LIKE LOWER(BTRIM(?)) AND (? IS NULL OR is_server = ?) ORDER BY login LIMIT 5 @@ -176,7 +176,7 @@ public final class CurrentUsersDAO { List result = new ArrayList<>(); try (PreparedStatement ps = c.prepareStatement(sql)) { - ps.setString(1, prefix.toLowerCase() + "%"); + ps.setString(1, prefix.trim() + "%"); if (isServer == null) { ps.setNull(2, Types.BOOLEAN); ps.setNull(3, Types.BOOLEAN); diff --git a/SHiNE-server/shine-server-db/src/main/java/shine/db/sql/CurrentUsersSql.java b/SHiNE-server/shine-server-db/src/main/java/shine/db/sql/CurrentUsersSql.java index 837e5aec..8fc33d91 100644 --- a/SHiNE-server/shine-server-db/src/main/java/shine/db/sql/CurrentUsersSql.java +++ b/SHiNE-server/shine-server-db/src/main/java/shine/db/sql/CurrentUsersSql.java @@ -12,6 +12,7 @@ public final class CurrentUsersSql { ( SELECT current_users.login AS login, + current_users.normalized_login AS normalized_login, current_users.blockchain_name AS blockchain_name, current_users.client_key AS solana_key, current_users.blockchain_key AS blockchain_key, diff --git a/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v5.sql b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v5.sql new file mode 100644 index 00000000..822a5483 --- /dev/null +++ b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v5.sql @@ -0,0 +1,83 @@ +BEGIN; + +ALTER TABLE solana_user_pda_current + ADD COLUMN IF NOT EXISTS normalized_login TEXT; + +UPDATE solana_user_pda_current +SET normalized_login = LOWER(BTRIM(login)) +WHERE normalized_login IS NULL + OR normalized_login <> LOWER(BTRIM(login)); + +ALTER TABLE solana_user_pda_current + ALTER COLUMN normalized_login SET NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS uq_solana_user_pda_current_normalized_login + ON solana_user_pda_current(normalized_login); + +CREATE INDEX IF NOT EXISTS idx_user_pda_current_normalized_login + ON solana_user_pda_current(normalized_login); + +WITH bad_signed_messages AS ( + SELECT DISTINCT sm.message_key + FROM signed_messages sm + LEFT JOIN solana_user_pda_current u_from + ON u_from.normalized_login = LOWER(BTRIM(sm.from_login)) + LEFT JOIN solana_user_pda_current u_to + ON u_to.normalized_login = LOWER(BTRIM(sm.to_login)) + WHERE (u_from.login IS NOT NULL AND sm.from_login <> u_from.login) + OR (u_to.login IS NOT NULL AND sm.to_login <> u_to.login) +) +DELETE FROM signed_message_session_delivery d +USING bad_signed_messages bad +WHERE d.message_key = bad.message_key; + +WITH bad_signed_messages AS ( + SELECT DISTINCT sm.message_key + FROM signed_messages sm + LEFT JOIN solana_user_pda_current u_from + ON u_from.normalized_login = LOWER(BTRIM(sm.from_login)) + LEFT JOIN solana_user_pda_current u_to + ON u_to.normalized_login = LOWER(BTRIM(sm.to_login)) + WHERE (u_from.login IS NOT NULL AND sm.from_login <> u_from.login) + OR (u_to.login IS NOT NULL AND sm.to_login <> u_to.login) +) +DELETE FROM signed_messages sm +USING bad_signed_messages bad +WHERE sm.message_key = bad.message_key; + +DELETE FROM signed_direct_messages_history h +USING solana_user_pda_current u_from, + solana_user_pda_current u_to +WHERE u_from.normalized_login = LOWER(BTRIM(h.from_login)) + AND u_to.normalized_login = LOWER(BTRIM(h.to_login)) + AND (h.from_login <> u_from.login OR h.to_login <> u_to.login); + +DELETE FROM signed_direct_message_replay r +USING solana_user_pda_current u_from +WHERE u_from.normalized_login = LOWER(BTRIM(r.from_login)) + AND r.from_login <> u_from.login; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.tables + WHERE table_schema = current_schema() + AND table_name = 'direct_messages' + ) THEN + DELETE FROM direct_messages d + USING solana_user_pda_current u_from, + solana_user_pda_current u_to + WHERE u_from.normalized_login = LOWER(BTRIM(d.from_login)) + AND u_to.normalized_login = LOWER(BTRIM(d.to_login)) + AND (d.from_login <> u_from.login OR d.to_login <> u_to.login); + END IF; +END $$; + +INSERT INTO db_schema_version (id, schema_version, updated_at_ms) +VALUES (1, 5, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) +ON CONFLICT (id) DO UPDATE SET + schema_version = EXCLUDED.schema_version, + updated_at_ms = EXCLUDED.updated_at_ms; + +COMMIT; diff --git a/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v6.sql b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v6.sql new file mode 100644 index 00000000..7407353a --- /dev/null +++ b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v6.sql @@ -0,0 +1,21 @@ +BEGIN; + +ALTER TABLE signed_messages + DROP CONSTRAINT IF EXISTS signed_messages_from_login_fkey; + +ALTER TABLE signed_messages + DROP CONSTRAINT IF EXISTS signed_messages_to_login_fkey; + +ALTER TABLE signed_direct_messages_history + DROP CONSTRAINT IF EXISTS signed_direct_messages_history_from_login_fkey; + +ALTER TABLE signed_direct_messages_history + DROP CONSTRAINT IF EXISTS signed_direct_messages_history_to_login_fkey; + +INSERT INTO db_schema_version (id, schema_version, updated_at_ms) +VALUES (1, 6, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) +ON CONFLICT (id) DO UPDATE SET + schema_version = EXCLUDED.schema_version, + updated_at_ms = EXCLUDED.updated_at_ms; + +COMMIT; diff --git a/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v7.sql b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v7.sql new file mode 100644 index 00000000..86017a32 --- /dev/null +++ b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v7.sql @@ -0,0 +1,16 @@ +BEGIN; + +ALTER TABLE blocks + DROP CONSTRAINT IF EXISTS blocks_login_fkey; + +ALTER TABLE blocks + ADD CONSTRAINT blocks_login_fkey + FOREIGN KEY (login) REFERENCES solana_user_pda_current(normalized_login); + +INSERT INTO db_schema_version (id, schema_version, updated_at_ms) +VALUES (1, 7, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) +ON CONFLICT (id) DO UPDATE SET + schema_version = EXCLUDED.schema_version, + updated_at_ms = EXCLUDED.updated_at_ms; + +COMMIT; diff --git a/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v8.sql b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v8.sql new file mode 100644 index 00000000..c28701f2 --- /dev/null +++ b/SHiNE-server/shine-server-db/src/main/resources/postgres/migration_v8.sql @@ -0,0 +1,16 @@ +BEGIN; + +ALTER TABLE connections_state + DROP CONSTRAINT IF EXISTS connections_state_login_fkey; + +ALTER TABLE connections_state + ADD CONSTRAINT connections_state_login_fkey + FOREIGN KEY (login) REFERENCES solana_user_pda_current(normalized_login); + +INSERT INTO db_schema_version (id, schema_version, updated_at_ms) +VALUES (1, 8, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) +ON CONFLICT (id) DO UPDATE SET + schema_version = EXCLUDED.schema_version, + updated_at_ms = EXCLUDED.updated_at_ms; + +COMMIT; diff --git a/SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql b/SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql index 5778d7fe..b86bd001 100644 --- a/SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql +++ b/SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql @@ -22,7 +22,7 @@ CREATE TABLE IF NOT EXISTS db_schema_version ( ); INSERT INTO db_schema_version (id, schema_version, updated_at_ms) -VALUES (1, 3, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) +VALUES (1, 8, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) ON CONFLICT (id) DO UPDATE SET schema_version = EXCLUDED.schema_version, updated_at_ms = EXCLUDED.updated_at_ms; @@ -74,6 +74,7 @@ CREATE INDEX IF NOT EXISTS idx_sync_tx_history_login CREATE TABLE IF NOT EXISTS solana_user_pda_current ( pda_address TEXT PRIMARY KEY, login TEXT NOT NULL UNIQUE, + normalized_login TEXT NOT NULL, record_number INTEGER NOT NULL, slot BIGINT NOT NULL, last_tx_signature TEXT NOT NULL, @@ -109,6 +110,12 @@ CREATE TABLE IF NOT EXISTS solana_user_pda_current ( CREATE INDEX IF NOT EXISTS idx_user_pda_current_slot ON solana_user_pda_current(slot); +CREATE UNIQUE INDEX IF NOT EXISTS uq_solana_user_pda_current_normalized_login + ON solana_user_pda_current(normalized_login); + +CREATE INDEX IF NOT EXISTS idx_user_pda_current_normalized_login + ON solana_user_pda_current(normalized_login); + CREATE TABLE IF NOT EXISTS user_access_servers_current ( user_login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE, server_login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE, @@ -440,7 +447,7 @@ CREATE INDEX IF NOT EXISTS idx_blockchain_state_updated_at ON blockchain_state(updated_at_ms); CREATE TABLE IF NOT EXISTS blocks ( - login TEXT NOT NULL REFERENCES solana_user_pda_current(login), + login TEXT NOT NULL REFERENCES solana_user_pda_current(normalized_login), bch_name TEXT NOT NULL REFERENCES blockchain_state(blockchain_name), block_number INTEGER NOT NULL CHECK (block_number >= 0), msg_type INTEGER NOT NULL, @@ -470,7 +477,7 @@ CREATE INDEX IF NOT EXISTS idx_blocks_by_line ON blocks (bch_name, line_code, this_line_number); CREATE TABLE IF NOT EXISTS connections_state ( - login TEXT NOT NULL REFERENCES solana_user_pda_current(login), + login TEXT NOT NULL REFERENCES solana_user_pda_current(normalized_login), rel_type INTEGER NOT NULL, to_login TEXT NOT NULL, to_bch_name TEXT NOT NULL, @@ -624,8 +631,8 @@ CREATE INDEX IF NOT EXISTS idx_signed_dm_replay_created CREATE TABLE IF NOT EXISTS signed_direct_messages_history ( message_id TEXT PRIMARY KEY, - from_login TEXT NOT NULL REFERENCES solana_user_pda_current(login), - to_login TEXT NOT NULL REFERENCES solana_user_pda_current(login), + from_login TEXT NOT NULL, + to_login TEXT NOT NULL, target_mode INTEGER NOT NULL, target_session_id TEXT, message_type INTEGER NOT NULL, @@ -642,8 +649,8 @@ CREATE TABLE IF NOT EXISTS signed_messages ( message_key TEXT PRIMARY KEY, base_key TEXT NOT NULL, target_login TEXT NOT NULL, - from_login TEXT NOT NULL REFERENCES solana_user_pda_current(login), - to_login TEXT NOT NULL REFERENCES solana_user_pda_current(login), + from_login TEXT NOT NULL, + to_login TEXT NOT NULL, time_ms BIGINT NOT NULL, nonce BIGINT NOT NULL, message_type INTEGER NOT NULL, diff --git a/SHiNE-server/shine-server-solana-users-sync/src/main/java/sync/storage/postgres/PostgresStorageRepository.java b/SHiNE-server/shine-server-solana-users-sync/src/main/java/sync/storage/postgres/PostgresStorageRepository.java index b1a2c145..2eddfe75 100644 --- a/SHiNE-server/shine-server-solana-users-sync/src/main/java/sync/storage/postgres/PostgresStorageRepository.java +++ b/SHiNE-server/shine-server-solana-users-sync/src/main/java/sync/storage/postgres/PostgresStorageRepository.java @@ -8,6 +8,7 @@ import sync.codec.ShineUsersCodec; import java.sql.*; import java.util.*; +import java.util.Locale; public final class PostgresStorageRepository implements AutoCloseable { @@ -465,7 +466,7 @@ public final class PostgresStorageRepository String sql = "INSERT INTO solana_user_pda_current (" + - "pda_address, login, record_number, slot, last_tx_signature, " + + "pda_address, login, normalized_login, record_number, slot, last_tx_signature, " + "recovery_key, root_key, client_key, blockchain_name, " + "blockchain_key, paid_limit_bytes, used_bytes, " + "last_block_number, last_block_hash, last_block_signature, " + @@ -475,9 +476,10 @@ public final class PostgresStorageRepository "trusted_count, created_at_ms, updated_at_ms, " + "prev_record_hash, record_signature, raw_data_base64, " + "first_seen_at_ms, last_synced_at_ms" + - ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT (pda_address) DO UPDATE SET " + "login = EXCLUDED.login, " + + "normalized_login = EXCLUDED.normalized_login, " + "record_number = EXCLUDED.record_number, " + "slot = EXCLUDED.slot, " + "last_tx_signature = EXCLUDED.last_tx_signature, " + @@ -679,36 +681,41 @@ public final class PostgresStorageRepository statement.setString(1, snapshot.pdaAddress()); statement.setString(2, snapshot.login()); - statement.setInt(3, snapshot.recordNumber()); - statement.setLong(4, snapshot.slot()); - statement.setString(5, snapshot.lastTxSignature()); - statement.setString(6, snapshot.recoveryKey()); - statement.setString(7, snapshot.rootKey()); - statement.setString(8, snapshot.clientKey()); - statement.setString(9, snapshot.blockchainName()); - statement.setString(10, snapshot.blockchainKey()); - statement.setLong(11, snapshot.paidLimitBytes()); - statement.setLong(12, snapshot.usedBytes()); - statement.setInt(13, snapshot.lastBlockNumber()); - statement.setString(14, snapshot.lastBlockHash()); - statement.setString(15, snapshot.lastBlockSignature()); - statement.setString(16, snapshot.arweaveTxId()); - statement.setBoolean(17, snapshot.isServer()); - statement.setInt(18, snapshot.addressFormatType()); - statement.setInt(19, snapshot.addressFormatVersion()); - statement.setString(20, snapshot.serverAddress()); - statement.setString(21, writeJson(snapshot.syncServers())); - statement.setString(22, writeJson(snapshot.accessServers())); - statement.setInt(23, snapshot.sessionsMode()); - statement.setString(24, writeJson(snapshot.sessions())); - statement.setInt(25, snapshot.trustedCount()); - statement.setLong(26, snapshot.createdAtMs()); - statement.setLong(27, snapshot.updatedAtMs()); - statement.setString(28, snapshot.prevRecordHash()); - statement.setString(29, snapshot.recordSignature()); - statement.setString(30, snapshot.rawDataBase64()); - statement.setLong(31, nowMs); + statement.setString(3, normalizeLogin(snapshot.login())); + statement.setInt(4, snapshot.recordNumber()); + statement.setLong(5, snapshot.slot()); + statement.setString(6, snapshot.lastTxSignature()); + statement.setString(7, snapshot.recoveryKey()); + statement.setString(8, snapshot.rootKey()); + statement.setString(9, snapshot.clientKey()); + statement.setString(10, snapshot.blockchainName()); + statement.setString(11, snapshot.blockchainKey()); + statement.setLong(12, snapshot.paidLimitBytes()); + statement.setLong(13, snapshot.usedBytes()); + statement.setInt(14, snapshot.lastBlockNumber()); + statement.setString(15, snapshot.lastBlockHash()); + statement.setString(16, snapshot.lastBlockSignature()); + statement.setString(17, snapshot.arweaveTxId()); + statement.setBoolean(18, snapshot.isServer()); + statement.setInt(19, snapshot.addressFormatType()); + statement.setInt(20, snapshot.addressFormatVersion()); + statement.setString(21, snapshot.serverAddress()); + statement.setString(22, writeJson(snapshot.syncServers())); + statement.setString(23, writeJson(snapshot.accessServers())); + statement.setInt(24, snapshot.sessionsMode()); + statement.setString(25, writeJson(snapshot.sessions())); + statement.setInt(26, snapshot.trustedCount()); + statement.setLong(27, snapshot.createdAtMs()); + statement.setLong(28, snapshot.updatedAtMs()); + statement.setString(29, snapshot.prevRecordHash()); + statement.setString(30, snapshot.recordSignature()); + statement.setString(31, snapshot.rawDataBase64()); statement.setLong(32, nowMs); + statement.setLong(33, nowMs); + } + + private String normalizeLogin(String login) { + return login == null ? "" : login.trim().toLowerCase(Locale.ROOT); } private ShineUsersCodec.UserPdaSnapshot mapSnapshot( @@ -911,6 +918,7 @@ public final class PostgresStorageRepository "CREATE TABLE IF NOT EXISTS solana_user_pda_current (" + "pda_address TEXT PRIMARY KEY, " + "login TEXT NOT NULL UNIQUE, " + + "normalized_login TEXT NOT NULL, " + "record_number INTEGER NOT NULL, " + "slot BIGINT NOT NULL, " + "last_tx_signature TEXT NOT NULL, " + @@ -943,11 +951,29 @@ public final class PostgresStorageRepository "last_synced_at_ms BIGINT NOT NULL" + ")" ); + statement.executeUpdate( + "ALTER TABLE solana_user_pda_current " + + "ADD COLUMN IF NOT EXISTS normalized_login TEXT" + ); + statement.executeUpdate( + "UPDATE solana_user_pda_current " + + "SET normalized_login = LOWER(BTRIM(login)) " + + "WHERE normalized_login IS NULL " + + " OR normalized_login <> LOWER(BTRIM(login))" + ); statement.executeUpdate( "CREATE INDEX IF NOT EXISTS idx_user_pda_current_slot " + "ON solana_user_pda_current(slot)" ); + statement.executeUpdate( + "CREATE UNIQUE INDEX IF NOT EXISTS uq_solana_user_pda_current_normalized_login " + + "ON solana_user_pda_current(normalized_login)" + ); + statement.executeUpdate( + "CREATE INDEX IF NOT EXISTS idx_user_pda_current_normalized_login " + + "ON solana_user_pda_current(normalized_login)" + ); statement.executeUpdate( "CREATE TABLE IF NOT EXISTS solana_user_pda_history (" + diff --git a/VERSION.properties b/VERSION.properties index d31849b1..35dcd70b 100644 --- a/VERSION.properties +++ b/VERSION.properties @@ -1,2 +1,2 @@ -client.version=1.5.39 -server.version=1.4.12 +client.version=1.5.40 +server.version=1.4.13 diff --git a/deploy/SOLANA_USERS_SYNC_SERVER_SETUP.md b/deploy/SOLANA_USERS_SYNC_SERVER_SETUP.md index b1f121ac..66e80e0d 100644 --- a/deploy/SOLANA_USERS_SYNC_SERVER_SETUP.md +++ b/deploy/SOLANA_USERS_SYNC_SERVER_SETUP.md @@ -13,6 +13,9 @@ - `user_access_servers_current` - `solana_user_pda_history` - источник истины по пользовательским PDA: `solana_user_pda_current`. +- в `solana_user_pda_current` хранятся оба варианта логина: + - `login` — display-логин из PDA; + - `normalized_login` — канонический lower-case для runtime lookup и части FK; - `user_access_servers_current` — это вторичная локальная проекция для быстрого роутинга DM по access servers; она автоматически пересобирается из `solana_user_pda_current`, включая backfill для уже существующих пользователей. @@ -56,7 +59,7 @@ psql \ Скрипт: - создаёт таблицу версии схемы `db_schema_version`; -- ставит `schema_version = 2`; +- ставит актуальный `schema_version`; - создаёт таблицы sync-модуля Solana users; - создаёт server runtime tables; - создаёт триггеры и функции автоматической актуализации `user_access_servers_current`; diff --git a/docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md b/docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md index 132922e6..6d432b78 100644 --- a/docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md +++ b/docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md @@ -323,6 +323,7 @@ Append-only журнал всех просмотренных транзакци - `pda_address TEXT PRIMARY KEY` - `login TEXT NOT NULL` +- `normalized_login TEXT NOT NULL` - `record_number INTEGER NOT NULL` - `slot INTEGER NOT NULL` - `last_tx_signature TEXT NOT NULL` @@ -349,9 +350,16 @@ Append-only журнал всех просмотренных транзакци Индексы: - уникальный индекс на `login` +- уникальный индекс на `normalized_login` - индекс на `slot` - индекс на `last_tx_signature` +Правило использования: + +- `login` хранит display-логин ровно в том регистре, как он записан в PDA; +- `normalized_login` хранит канонический lower-case логин; +- server runtime может использовать `normalized_login` для lookup и FK там, где внутренние записи живут в canonical lower-case. + ### 4. `solana_user_pda_history` Append-only история всех версий пользовательских PDA. diff --git a/shine-UI/js/app.js b/shine-UI/js/app.js index bb1b2b17..4a4b03a0 100644 --- a/shine-UI/js/app.js +++ b/shine-UI/js/app.js @@ -1,13 +1,8 @@ import { navigate, getRoute, - parseRouteFromPath, PRE_AUTH_PAGES, - getSwipeNavigationTarget, syncTrackedRouteHistory, - rememberToolbarRoute, - resetRememberedToolbarRoutes, - resolveToolbarActive, } from './router.js'; import { renderToolbar } from './components/toolbar.js'; import { captureClientError, setClientErrorSentNotifier, setClientErrorTransport } from './services/client-error-reporter.js'; @@ -173,14 +168,6 @@ const SIGNED_DM_DECRYPT_CONTEXT_POLL_MS = 50; const UI_VERSION_PERIODIC_CHECK_MS = 5 * 60 * 1000; const CURRENT_BUILD_HASH = String(window.__SHINE_BUILD_HASH__ || '').trim(); const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/; -const KEEP_ALIVE_ROOTS = new Set(['messages-list', 'channels-list']); -const HORIZONTAL_SWIPE_MIN_DISTANCE_PX = 72; -const HORIZONTAL_SWIPE_MAX_VERTICAL_DRIFT_PX = 56; -const HORIZONTAL_SWIPE_DOMINANCE_RATIO = 1.35; -const HORIZONTAL_SWIPE_LOCK_DISTANCE_PX = 14; -const HORIZONTAL_SWIPE_COMMIT_RATIO = 0.32; -const HORIZONTAL_SWIPE_PREVIEW_EDGE_PX = 18; -const HORIZONTAL_SWIPE_MAX_DURATION_MS = 260; let currentCleanup = null; let pingIntervalId = null; @@ -202,9 +189,6 @@ let hiddenDmAudioUnlocked = false; let initialConnectionCompleted = false; let orientationLockInFlight = false; let currentChromeCleanup = null; -let currentMountState = null; -let activeSwipePreview = null; -const keepAliveEntries = new Map(); const CALL_PUSH_PENDING_ACTION_KEY = 'shine-ui-call-push-pending-action-v1'; const GUEST_ALLOWED_PAGES = new Set([ 'start-view', @@ -319,403 +303,11 @@ function createChromeController(showAppChrome) { }; } -function destroyMountState(entry) { - if (!entry) return; - if (entry.destroyed) return; - entry.destroyed = true; - try { - if (typeof entry.cleanup === 'function') { - entry.cleanup(); - } - } finally { - entry.chrome?.dispose?.(); - } -} - function clearKeepAliveEntries() { - teardownSwipePreview({ cancelOnly: true }); - keepAliveEntries.forEach((entry) => destroyMountState(entry)); - keepAliveEntries.clear(); - resetRememberedToolbarRoutes(); - currentMountState = null; currentCleanup = null; currentChromeCleanup = null; } -function detachMountedScreen(entry) { - if (!entry) return; - entry.chrome?.suspend?.(); - if (entry.screen?.parentNode === screenEl) { - screenEl.removeChild(entry.screen); - } else { - screenEl.innerHTML = ''; - } -} - -function mountExistingEntry(entry, { showAppChrome, pageId }) { - teardownSwipePreview({ cancelOnly: true }); - screenEl.innerHTML = ''; - screenEl.append(entry.screen); - entry.chrome?.resume?.(); - currentMountState = entry; - currentCleanup = typeof entry.cleanup === 'function' ? entry.cleanup : null; - currentChromeCleanup = () => entry.chrome?.dispose?.(); - screenEl.classList.toggle('no-app-chrome', !showAppChrome); - screenEl.classList.toggle('preauth-flow', PRE_AUTH_PAGES.includes(pageId)); -} - -function cloneScreenForSwipe(screen) { - const clone = screen?.cloneNode?.(true); - if (!(clone instanceof Node)) return null; - return clone; -} - -function sanitizeSwipeClone(node) { - if (!(node instanceof Element)) return; - node.removeAttribute('id'); - node.querySelectorAll('[id]').forEach((el) => el.removeAttribute('id')); -} - -function cloneSlotChildForSwipe(slotEl) { - const child = slotEl?.firstElementChild; - if (!(child instanceof Node)) return null; - const clone = child.cloneNode(true); - if (clone instanceof Element) sanitizeSwipeClone(clone); - return clone; -} - -function createSwipeFrameSlot(className, contentNode = null) { - const slot = document.createElement('div'); - slot.className = className; - if (contentNode instanceof Node) { - slot.append(contentNode); - slot.hidden = false; - } else { - slot.hidden = true; - } - return slot; -} - -function buildSwipePane({ - topbarNode = null, - screenNode = null, - composerNode = null, - screenClassName = '', - screenScrollTop = 0, -}) { - const pane = document.createElement('div'); - pane.className = 'screen-swipe-pane'; - - const topbarSlot = createSwipeFrameSlot('topbar-slot screen-swipe-slot screen-swipe-slot--topbar', topbarNode); - const screenSlot = document.createElement('main'); - screenSlot.className = `${screenClassName || 'screen-content'} screen-swipe-slot screen-swipe-slot--content`; - if (screenNode instanceof Node) { - screenSlot.append(screenNode); - } - const composerSlot = createSwipeFrameSlot('composer-slot screen-swipe-slot screen-swipe-slot--composer', composerNode); - - pane.append(topbarSlot, screenSlot, composerSlot); - requestAnimationFrame(() => { - screenSlot.scrollTop = Math.max(0, Number(screenScrollTop || 0)); - }); - return pane; -} - -function createSwipePreviewTarget(targetPath) { - const route = parseRouteFromPath(`/${String(targetPath || '').replace(/^\/+/, '')}`); - const pageId = route.pageId || (state.session.isAuthorized ? 'messages-list' : 'start-view'); - const page = routes[pageId] || routes['start-view']; - const rootPageId = resolveToolbarActive(pageId); - const cachedEntry = keepAliveEntries.get(rootPageId); - if (cachedEntry && cachedEntry.routePath === `/${String(targetPath || '').replace(/^\/+/, '')}`) { - return { - screen: cloneScreenForSwipe(cachedEntry.screen), - cleanup: null, - }; - } - - let previewTopbarNode = null; - let previewComposerNode = null; - const chrome = { - setTopbar(node = null) { - previewTopbarNode = node instanceof Node ? node : null; - }, - setComposer(node = null) { - previewComposerNode = node instanceof Node ? node : null; - }, - clear() { - previewTopbarNode = null; - previewComposerNode = null; - }, - suspend() {}, - resume() {}, - dispose() {}, - }; - const screen = page.render({ route, navigate, chrome }); - if (!(screen instanceof Node)) { - chrome.dispose(); - throw new Error('Swipe preview render returned invalid node'); - } - const cleanup = typeof screen.cleanup === 'function' ? screen.cleanup : null; - return { - screen, - topbarNode: previewTopbarNode, - composerNode: previewComposerNode, - cleanup: () => { - try { - if (typeof cleanup === 'function') cleanup(); - } finally { - chrome.dispose(); - } - }, - }; -} - -function applySwipePreviewOffset(session, revealPx) { - if (!session) return; - const width = Math.max(1, session.width); - const clamped = Math.max(0, Math.min(width, revealPx)); - session.revealPx = clamped; - - const currentX = session.direction === 'left' ? -clamped : clamped; - const targetX = session.direction === 'left' - ? width - clamped + HORIZONTAL_SWIPE_PREVIEW_EDGE_PX - : -width + clamped - HORIZONTAL_SWIPE_PREVIEW_EDGE_PX; - const dividerX = session.direction === 'left' - ? width - clamped - : clamped; - - session.currentPane.style.transform = `translate3d(${currentX}px, 0, 0)`; - session.targetPane.style.transform = `translate3d(${targetX}px, 0, 0)`; - session.divider.style.transform = `translate3d(${dividerX}px, 0, 0)`; - - const overlayOpacity = Math.max(0.08, Math.min(0.24, (clamped / width) * 0.24)); - session.overlay.style.setProperty('--swipe-overlay-opacity', overlayOpacity.toFixed(3)); -} - -function teardownSwipePreview({ cancelOnly = false } = {}) { - const session = activeSwipePreview; - if (!session) return; - activeSwipePreview = null; - - appShellEl?.classList.remove('app-shell--swiping'); - topbarEl?.classList.remove('topbar-slot--swipe-hidden'); - screenEl.classList.remove('screen-content--swipe-hidden'); - composerEl?.classList.remove('composer-slot--swipe-hidden'); - session.overlay.remove(); - if (typeof session.targetCleanup === 'function') { - session.targetCleanup(); - } - if (!cancelOnly) { - session.onComplete?.(); - } -} - -function animateSwipePreviewTo(session, revealPx, { complete = false } = {}) { - const width = Math.max(1, session.width); - const currentReveal = Number(session.revealPx || 0); - const remaining = Math.abs(revealPx - currentReveal); - const duration = Math.max(140, Math.min(HORIZONTAL_SWIPE_MAX_DURATION_MS, Math.round((remaining / width) * HORIZONTAL_SWIPE_MAX_DURATION_MS))); - - [session.currentPane, session.targetPane, session.divider].forEach((node) => { - node.style.transition = `transform ${duration}ms cubic-bezier(0.22, 1, 0.36, 1)`; - }); - session.overlay.style.transition = `opacity ${duration}ms ease`; - - requestAnimationFrame(() => { - applySwipePreviewOffset(session, revealPx); - if (!complete) { - session.overlay.style.opacity = '0'; - } - }); - - window.setTimeout(() => { - teardownSwipePreview({ cancelOnly: !complete }); - }, duration + 24); -} - -function beginSwipePreview(direction, targetPath) { - if (!currentMountState?.screen || activeSwipePreview) return null; - const currentTopbarClone = cloneSlotChildForSwipe(topbarEl); - const currentScreenClone = cloneScreenForSwipe(currentMountState.screen); - const currentComposerClone = cloneSlotChildForSwipe(composerEl); - if (!(currentScreenClone instanceof Node)) return null; - if (currentTopbarClone instanceof Element) sanitizeSwipeClone(currentTopbarClone); - if (currentScreenClone instanceof Element) sanitizeSwipeClone(currentScreenClone); - if (currentComposerClone instanceof Element) sanitizeSwipeClone(currentComposerClone); - - const targetPreview = createSwipePreviewTarget(targetPath); - if (!(targetPreview?.screen instanceof Node)) { - targetPreview?.cleanup?.(); - return null; - } - if (targetPreview.topbarNode instanceof Element) sanitizeSwipeClone(targetPreview.topbarNode); - if (targetPreview.screen instanceof Element) sanitizeSwipeClone(targetPreview.screen); - if (targetPreview.composerNode instanceof Element) sanitizeSwipeClone(targetPreview.composerNode); - - const overlay = document.createElement('div'); - overlay.className = 'screen-swipe-overlay'; - - const currentPane = buildSwipePane({ - topbarNode: currentTopbarClone, - screenNode: currentScreenClone, - composerNode: currentComposerClone, - screenClassName: screenEl.className, - screenScrollTop: screenEl.scrollTop, - }); - currentPane.classList.add('screen-swipe-pane--current'); - - const targetPane = buildSwipePane({ - topbarNode: targetPreview.topbarNode || null, - screenNode: targetPreview.screen, - composerNode: targetPreview.composerNode || null, - screenClassName: screenEl.className, - screenScrollTop: 0, - }); - targetPane.classList.add('screen-swipe-pane--target', `screen-swipe-pane--${direction}`); - - const divider = document.createElement('div'); - divider.className = 'screen-swipe-divider'; - - overlay.append(currentPane, targetPane, divider); - appShellEl.append(overlay); - appShellEl?.classList.add('app-shell--swiping'); - topbarEl?.classList.add('topbar-slot--swipe-hidden'); - screenEl.classList.add('screen-content--swipe-hidden'); - composerEl?.classList.add('composer-slot--swipe-hidden'); - - const session = { - direction, - targetPath, - width: screenEl.clientWidth || 1, - overlay, - currentPane, - targetPane, - divider, - targetCleanup: targetPreview.cleanup || null, - revealPx: 0, - onComplete: () => navigate(targetPath), - }; - activeSwipePreview = session; - applySwipePreviewOffset(session, 0); - return session; -} - -function installHorizontalTabSwipe() { - if (!screenEl) return; - - let touchStartX = 0; - let touchStartY = 0; - let touchActive = false; - let touchBlocked = false; - let swipeLocked = false; - let swipeDirection = ''; - let swipeTargetPath = ''; - let swipeSession = null; - - const reset = () => { - touchActive = false; - touchBlocked = false; - swipeLocked = false; - swipeDirection = ''; - swipeTargetPath = ''; - swipeSession = null; - touchStartX = 0; - touchStartY = 0; - }; - - screenEl.addEventListener('touchstart', (event) => { - if (event.touches.length !== 1) { - reset(); - return; - } - const target = event.target instanceof Element ? event.target : null; - touchBlocked = Boolean(target?.closest('input, textarea, select, button, a, [contenteditable="true"]')); - touchActive = !touchBlocked; - touchStartX = Number(event.touches[0]?.clientX || 0); - touchStartY = Number(event.touches[0]?.clientY || 0); - }, { passive: true }); - - screenEl.addEventListener('touchmove', (event) => { - if (!touchActive || touchBlocked) return; - const touch = event.touches?.[0]; - const deltaX = Number(touch?.clientX || 0) - touchStartX; - const deltaY = Number(touch?.clientY || 0) - touchStartY; - const absX = Math.abs(deltaX); - const absY = Math.abs(deltaY); - - if (!swipeLocked) { - if (absX < HORIZONTAL_SWIPE_LOCK_DISTANCE_PX && absY < HORIZONTAL_SWIPE_LOCK_DISTANCE_PX) return; - if (absX <= absY * 1.05) { - touchBlocked = true; - return; - } - const currentPageId = getRoute().pageId || ''; - swipeDirection = deltaX < 0 ? 'left' : 'right'; - swipeTargetPath = getSwipeNavigationTarget(currentPageId, swipeDirection); - if (!swipeTargetPath) { - touchBlocked = true; - return; - } - swipeSession = beginSwipePreview(swipeDirection, swipeTargetPath); - if (!swipeSession) { - touchBlocked = true; - return; - } - swipeLocked = true; - } - - if (!swipeLocked || !swipeSession) return; - event.preventDefault(); - - const revealPx = swipeDirection === 'left' - ? Math.max(0, -deltaX) - : Math.max(0, deltaX); - applySwipePreviewOffset(swipeSession, revealPx); - }, { passive: false }); - - screenEl.addEventListener('touchcancel', reset, { passive: true }); - - screenEl.addEventListener('touchend', (event) => { - if (!touchActive || touchBlocked) { - if (swipeSession) { - animateSwipePreviewTo(swipeSession, 0, { complete: false }); - } - reset(); - return; - } - - const touch = event.changedTouches?.[0]; - const endX = Number(touch?.clientX || 0); - const endY = Number(touch?.clientY || 0); - const deltaX = endX - touchStartX; - const deltaY = endY - touchStartY; - const absX = Math.abs(deltaX); - const absY = Math.abs(deltaY); - const session = swipeSession; - const wasLocked = swipeLocked; - reset(); - - if (wasLocked && session) { - event.preventDefault(); - const revealRatio = Number(session.revealPx || 0) / Math.max(1, session.width); - const shouldCommit = revealRatio >= HORIZONTAL_SWIPE_COMMIT_RATIO; - animateSwipePreviewTo(session, shouldCommit ? session.width : 0, { complete: shouldCommit }); - return; - } - - if (absX < HORIZONTAL_SWIPE_MIN_DISTANCE_PX) return; - if (absY > HORIZONTAL_SWIPE_MAX_VERTICAL_DRIFT_PX) return; - if (absX <= absY * HORIZONTAL_SWIPE_DOMINANCE_RATIO) return; - - const currentPageId = getRoute().pageId || ''; - const direction = deltaX < 0 ? 'left' : 'right'; - const target = getSwipeNavigationTarget(currentPageId, direction); - if (!target) return; - navigate(target); - }, { passive: true }); -} - async function unlockHiddenDmAudio() { try { const Ctx = window.AudioContext || window.webkitAudioContext; @@ -1396,7 +988,6 @@ function renderPageFailureFallback(pageId, error) { }); screenEl.innerHTML = ''; - teardownSwipePreview({ cancelOnly: true }); const wrap = document.createElement('section'); wrap.className = 'stack'; @@ -1433,7 +1024,6 @@ function renderPageFailureFallback(pageId, error) { } function renderApp() { - teardownSwipePreview({ cancelOnly: true }); syncTrackedRouteHistory(window.location.pathname || '/'); const route = getRoute(); const pageId = route.pageId || (state.session.isAuthorized ? 'messages-list' : 'start-view'); @@ -1450,56 +1040,13 @@ function renderApp() { const page = routes[pageId] || routes['start-view']; const showAppChrome = page.pageMeta?.showAppChrome !== false; - const rootPageId = resolveToolbarActive(pageId); - const keepAliveEligible = showAppChrome && KEEP_ALIVE_ROOTS.has(rootPageId); - const currentRoutePath = String(window.location.pathname || '/'); - - rememberToolbarRoute(pageId); - - if (currentMountState) { - const shouldPreserveCurrent = currentMountState.keepAlive && currentMountState.rootPageId !== rootPageId; - if (shouldPreserveCurrent) { - currentMountState.routePath = currentMountState.routePath || currentRoutePath; - keepAliveEntries.set(currentMountState.rootPageId, currentMountState); - detachMountedScreen(currentMountState); - currentMountState = null; - currentCleanup = null; - currentChromeCleanup = null; - } else { - destroyMountState(currentMountState); - if (currentMountState.keepAlive) { - keepAliveEntries.delete(currentMountState.rootPageId); - } - currentMountState = null; - currentCleanup = null; - currentChromeCleanup = null; - } - } else { - if (typeof currentCleanup === 'function') { - currentCleanup(); - currentCleanup = null; - } - if (typeof currentChromeCleanup === 'function') { - currentChromeCleanup(); - currentChromeCleanup = null; - } + if (typeof currentCleanup === 'function') { + currentCleanup(); + currentCleanup = null; } - - const cachedEntry = keepAliveEligible ? keepAliveEntries.get(rootPageId) : null; - if (cachedEntry && cachedEntry.routePath === currentRoutePath) { - mountExistingEntry(cachedEntry, { showAppChrome, pageId }); - toolbarEl.innerHTML = ''; - if (showAppChrome) { - toolbarEl.append(renderToolbar(page.pageMeta.id, navigate)); - } - toolbarHeightObserver?.sync?.(); - refreshConnectionUi(); - return; - } - - if (cachedEntry) { - destroyMountState(cachedEntry); - keepAliveEntries.delete(rootPageId); + if (typeof currentChromeCleanup === 'function') { + currentChromeCleanup(); + currentChromeCleanup = null; } try { @@ -1513,19 +1060,6 @@ function renderApp() { screenEl.append(screen); currentCleanup = typeof screen.cleanup === 'function' ? screen.cleanup : null; - currentMountState = { - pageId, - rootPageId, - keepAlive: keepAliveEligible, - routePath: currentRoutePath, - screen, - cleanup: currentCleanup, - chrome, - destroyed: false, - }; - if (keepAliveEligible) { - keepAliveEntries.set(rootPageId, currentMountState); - } screenEl.classList.toggle('no-app-chrome', !showAppChrome); screenEl.classList.toggle('preauth-flow', PRE_AUTH_PAGES.includes(pageId)); @@ -2008,7 +1542,6 @@ async function init() { })(); window.addEventListener('popstate', renderApp); - installHorizontalTabSwipe(); document.addEventListener('pointerdown', () => { void unlockHiddenDmAudio(); }, { passive: true }); diff --git a/shine-UI/js/components/arweave-attachment-manager.js b/shine-UI/js/components/arweave-attachment-manager.js index 72f5529d..1885c9ea 100644 --- a/shine-UI/js/components/arweave-attachment-manager.js +++ b/shine-UI/js/components/arweave-attachment-manager.js @@ -284,10 +284,22 @@ export function openArweaveAttachmentManager({ onSelect, selectedTxIds = [], historyOnly = false, + persistToHistory = true, + allowHistorySelection = true, + allowExistingTxInput = true, mode = 'attachment', historyPurpose = '', uploadTransport = 'turbo', turboKeySource = 'client', + dialogTitle = '', + uploadButtonLabel = '', + initialFile = null, + initialSha256 = '', + initialName = '', + fixedFile = false, + autoOpenFileDialog = true, + shineType = '', + extraUploadTags = [], } = {}) { const cleanLogin = String(login || '').trim(); const cleanStoragePwd = String(storagePwd || '').trim(); @@ -312,7 +324,7 @@ export function openArweaveAttachmentManager({ let selectedPreviewPriceInfo = null; let priceInfo = null; let balanceInfo = null; - let autoOpenedFileDialog = false; + let autoOpenedFileDialogOnce = false; const isAvatarMode = String(mode || '') === 'avatar'; if (isAvatarMode && !String(uploadTransport || '').trim()) { selectedUploadTransport = 'turbo'; @@ -320,6 +332,16 @@ export function openArweaveAttachmentManager({ const historyPurposeMode = String(historyPurpose || '').trim(); const purposeFilter = isAvatarMode || historyPurposeMode === 'avatar' ? 'avatar' : 'attachment'; const selectedTxIdSet = new Set((Array.isArray(selectedTxIds) ? selectedTxIds : []).map((item) => String(item || '').trim()).filter(Boolean)); + const effectiveDialogTitle = String(dialogTitle || '').trim(); + const effectiveUploadButtonLabel = String(uploadButtonLabel || '').trim(); + const forcedShineType = String(shineType || '').trim(); + const normalizedExtraUploadTags = Array.isArray(extraUploadTags) + ? extraUploadTags.filter((item) => item?.name && item?.value) + : []; + if (initialFile instanceof File) { + selectedFile = initialFile; + if (initialSha256) selectedSha256 = String(initialSha256 || '').trim().toLowerCase(); + } function isTurboUpload() { return selectedUploadTransport === 'turbo'; @@ -337,10 +359,15 @@ export function openArweaveAttachmentManager({ } function finish(resolve, attachment, { pendingPlacement = undefined } = {}) { - const item = addArweaveAttachmentToHistory(cleanLogin, attachment, { - pendingPlacement, - markPlaced: false, - }); + const item = persistToHistory + ? addArweaveAttachmentToHistory(cleanLogin, attachment, { + pendingPlacement, + markPlaced: false, + }) + : { + ...attachment, + ...normalizeAttachment(attachment), + }; if (!pendingPlacement && typeof onSelect === 'function') onSelect(item); close(resolve, item); } @@ -588,16 +615,21 @@ export function openArweaveAttachmentManager({ const showUpload = async () => { const turboMode = isTurboUpload(); + const titleText = effectiveDialogTitle + || (turboMode ? 'Загрузить через Turbo' : (isAvatarMode ? 'Загрузить аватар' : (historyOnly ? 'Загрузить файл в блокчейн' : 'Добавить вложение'))); + const uploadText = effectiveUploadButtonLabel || (historyOnly ? 'Загрузить в журнал' : 'Загрузить'); + const canShowHistory = allowHistorySelection; + const canShowExisting = allowExistingTxInput; root.innerHTML = `