StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Implement Stalker sync and VOD improvements
David Nashashdb6197e3bd7a
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 1c509b7d..595cad7f 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -87,6 +87,7 @@ object DatabaseModule {@Provides fun provideXtreamIndexJobDao(db: StreamVaultDatabase): XtreamIndexJobDao = db.xtreamIndexJobDao()@Provides fun provideXtreamLiveOnboardingDao(db: StreamVaultDatabase): XtreamLiveOnboardingDao = db.xtreamLiveOnboardingDao()@Provides fun provideStalkerIndexJobDao(db: StreamVaultDatabase): StalkerIndexJobDao = db.stalkerIndexJobDao()+ @Provides fun provideStalkerLiveCategoryRetryDao(db: StreamVaultDatabase): StalkerLiveCategoryRetryDao = db.stalkerLiveCategoryRetryDao()@Provides fun provideStalkerPortalStateDao(db: StreamVaultDatabase): StalkerPortalStateDao = db.stalkerPortalStateDao()@Provides fun provideStalkerRemoteIdentityDao(db: StreamVaultDatabase): StalkerRemoteIdentityDao = db.stalkerRemoteIdentityDao()@Provides fun provideStalkerDiscoveryStageDao(db: StreamVaultDatabase): StalkerDiscoveryStageDao = db.stalkerDiscoveryStageDao()diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/80.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/80.jsonnew file mode 100644index 00000000..ac8db510--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/80.json@@ -0,0 +1,7199 @@+{+ "formatVersion": 1,+ "database": {+ "version": 80,+ "identityHash": "0294cba9c7af785c179086e385e2eba8",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_type",+ "unique": false,+ "columnNames": [+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_type` ON `${TABLE_NAME}` (`type`)"+ },+ {+ "name": "index_providers_is_active",+ "unique": false,+ "columnNames": [+ "is_active"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_is_active` ON `${TABLE_NAME}` (`is_active`)"+ }+ ]+ },+ {+ "tableName": "provider_configs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `type` TEXT NOT NULL, `schema_version` INTEGER NOT NULL, `configuration_generation` INTEGER NOT NULL, `identity_key` TEXT NOT NULL, `encrypted_config_json` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "schemaVersion",+ "columnName": "schema_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "identityKey",+ "columnName": "identity_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "encryptedConfigJson",+ "columnName": "encrypted_config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_configs_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_configs_identity_key",+ "unique": true,+ "columnNames": [+ "identity_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_identity_key` ON `${TABLE_NAME}` (`identity_key`)"+ },+ {+ "name": "index_provider_configs_type",+ "unique": false,+ "columnNames": [+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_configs_type` ON `${TABLE_NAME}` (`type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_account_runtime",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `catalog_layout` TEXT NOT NULL, `catalog_layout_detection_version` INTEGER NOT NULL, `observed_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayout",+ "columnName": "catalog_layout",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayoutDetectionVersion",+ "columnName": "catalog_layout_detection_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_account_runtime_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_account_runtime_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `playback_metadata_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "playbackMetadataJson",+ "columnName": "playback_metadata_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, `playback_metadata_json` TEXT, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "playbackMetadataJson",+ "columnName": "playback_metadata_json",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, `catalog_origin` TEXT NOT NULL, `episode_playback_template_url` TEXT, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catalogOrigin",+ "columnName": "catalog_origin",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodePlaybackTemplateUrl",+ "columnName": "episode_playback_template_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ },+ {+ "name": "index_series_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_last_modified_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "last_modified",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `provider_order` INTEGER NOT NULL DEFAULT 0, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerOrder",+ "columnName": "provider_order",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `playback_metadata_json` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "playbackMetadataJson",+ "columnName": "playback_metadata_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `playback_metadata_json` TEXT, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "playbackMetadataJson",+ "columnName": "playback_metadata_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerSeriesKey",+ "columnName": "provider_series_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "provider_series_key"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_order` INTEGER NOT NULL DEFAULT 0, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerOrder",+ "columnName": "provider_order",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "advertisedTotalItems",+ "columnName": "advertised_total_items",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "advertisedTotalPages",+ "columnName": "advertised_total_pages",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "advertisedTotalItems",+ "columnName": "advertised_total_items",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "advertisedTotalPages",+ "columnName": "advertised_total_pages",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "vod_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `page_size` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `has_movies` INTEGER NOT NULL, `has_series` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "advertisedTotalItems",+ "columnName": "advertised_total_items",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "advertisedTotalPages",+ "columnName": "advertised_total_pages",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "hasMovies",+ "columnName": "has_movies",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "hasSeries",+ "columnName": "has_series",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_vod_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "vod_catalog_entries",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `raw_item_id` TEXT NOT NULL, `item_type` TEXT NOT NULL, `target_id` INTEGER NOT NULL, `raw_page` INTEGER NOT NULL, `raw_index` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`, `raw_item_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawItemId",+ "columnName": "raw_item_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "itemType",+ "columnName": "item_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawPage",+ "columnName": "raw_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawIndex",+ "columnName": "raw_index",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "raw_item_id"+ ]+ },+ "indices": [+ {+ "name": "index_vod_catalog_entries_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "raw_page",+ "raw_index"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `raw_page`, `raw_index`)"+ },+ {+ "name": "index_vod_catalog_entries_provider_id_item_type_target_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "item_type",+ "target_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_item_type_target_id` ON `${TABLE_NAME}` (`provider_id`, `item_type`, `target_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT, `timezone_policy` TEXT NOT NULL, `timezone_id` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "timezonePolicy",+ "columnName": "timezone_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "timezoneId",+ "columnName": "timezone_id",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `exact_alarm_armed` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `exact_alarm_armed` INTEGER NOT NULL, `delivery_state` TEXT NOT NULL, `delivery_attempt_token` TEXT, `delivery_attempted_at` INTEGER, `delivery_attempt_count` INTEGER NOT NULL, `delivery_failure_reason` TEXT, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "exactAlarmArmed",+ "columnName": "exact_alarm_armed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryState",+ "columnName": "delivery_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deliveryAttemptToken",+ "columnName": "delivery_attempt_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "deliveryAttemptedAt",+ "columnName": "delivery_attempted_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "deliveryAttemptCount",+ "columnName": "delivery_attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deliveryFailureReason",+ "columnName": "delivery_failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "playback_compatibility_records",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deviceFingerprint",+ "columnName": "device_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deviceModel",+ "columnName": "device_model",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "androidSdk",+ "columnName": "android_sdk",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamType",+ "columnName": "stream_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "videoMimeType",+ "columnName": "video_mime_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolutionBucket",+ "columnName": "resolution_bucket",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "decoderName",+ "columnName": "decoder_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surfaceType",+ "columnName": "surface_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureType",+ "columnName": "failure_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastFailedAt",+ "columnName": "last_failed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSucceededAt",+ "columnName": "last_succeeded_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "successCount",+ "columnName": "success_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",+ "unique": true,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket",+ "decoder_name",+ "surface_type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"+ },+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",+ "unique": false,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"+ },+ {+ "name": "index_playback_compatibility_records_last_failed_at",+ "unique": false,+ "columnNames": [+ "last_failed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"+ },+ {+ "name": "index_playback_compatibility_records_last_succeeded_at",+ "unique": false,+ "columnNames": [+ "last_succeeded_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"+ }+ ]+ },+ {+ "tableName": "xtream_content_index",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `remote_id` TEXT NOT NULL, `local_content_id` INTEGER, `name` TEXT NOT NULL, `category_id` INTEGER, `category_name` TEXT, `image_url` TEXT, `container_extension` TEXT, `rating` REAL NOT NULL, `added_at` INTEGER NOT NULL, `remote_updated_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `indexed_at` INTEGER NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `stale_state` TEXT NOT NULL, `error_state` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `remote_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "remoteId",+ "columnName": "remote_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "localContentId",+ "columnName": "local_content_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteUpdatedAt",+ "columnName": "remote_updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedAt",+ "columnName": "indexed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "staleState",+ "columnName": "stale_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorState",+ "columnName": "error_state",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "remote_id"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_content_index_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_category_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `category_id`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_name",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_name` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `name`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_local_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "local_content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_local_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `local_content_id`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_indexed_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "indexed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_indexed_at` ON `${TABLE_NAME}` (`provider_id`, `indexed_at`)"+ },+ {+ "name": "index_xtream_content_index_stale_state",+ "unique": false,+ "columnNames": [+ "stale_state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_stale_state` ON `${TABLE_NAME}` (`stale_state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "xtream_index_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `priority_category_id` INTEGER, `priority_requested_at` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCategories",+ "columnName": "total_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedCategories",+ "columnName": "completed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCategories",+ "columnName": "failed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedRows",+ "columnName": "indexed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "skippedMalformedRows",+ "columnName": "skipped_malformed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deletedPrunedRows",+ "columnName": "deleted_pruned_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priorityCategoryId",+ "columnName": "priority_category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "priorityRequestedAt",+ "columnName": "priority_requested_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "last_attempt_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "section"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_index_jobs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_xtream_index_jobs_section",+ "unique": false,+ "columnNames": [+ "section"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_section` ON `${TABLE_NAME}` (`section`)"+ },+ {+ "name": "index_xtream_index_jobs_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_xtream_index_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "xtream_live_onboarding_state",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `provider_type` TEXT NOT NULL, `content_type` TEXT NOT NULL, `phase` TEXT NOT NULL, `staged_session_id` INTEGER, `import_strategy` TEXT, `next_category_index` INTEGER NOT NULL, `accepted_row_count` INTEGER NOT NULL, `staged_flush_count` INTEGER NOT NULL, `sealed_session_id` INTEGER, `sealed_row_count` INTEGER NOT NULL DEFAULT 0, `sealed_configuration_generation` INTEGER, `sealed_mapping_profile` TEXT, `sync_profile_tier` TEXT, `sync_profile_batch_size` INTEGER NOT NULL, `sync_profile_strategy` TEXT, `sync_profile_low_memory` INTEGER NOT NULL, `sync_profile_memory_class_mb` INTEGER NOT NULL, `sync_profile_available_mem_mb` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerType",+ "columnName": "provider_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stagedSessionId",+ "columnName": "staged_session_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "importStrategy",+ "columnName": "import_strategy",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "acceptedRowCount",+ "columnName": "accepted_row_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stagedFlushCount",+ "columnName": "staged_flush_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sealedSessionId",+ "columnName": "sealed_session_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "sealedRowCount",+ "columnName": "sealed_row_count",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ },+ {+ "fieldPath": "sealedConfigurationGeneration",+ "columnName": "sealed_configuration_generation",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "sealedMappingProfile",+ "columnName": "sealed_mapping_profile",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncProfileTier",+ "columnName": "sync_profile_tier",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncProfileBatchSize",+ "columnName": "sync_profile_batch_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileStrategy",+ "columnName": "sync_profile_strategy",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncProfileLowMemory",+ "columnName": "sync_profile_low_memory",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileMemoryClassMb",+ "columnName": "sync_profile_memory_class_mb",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileAvailableMemMb",+ "columnName": "sync_profile_available_mem_mb",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_live_onboarding_state_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_phase",+ "unique": false,+ "columnNames": [+ "phase"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_phase` ON `${TABLE_NAME}` (`phase`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_staged_session_id",+ "unique": false,+ "columnNames": [+ "staged_session_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_staged_session_id` ON `${TABLE_NAME}` (`staged_session_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_index_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCategories",+ "columnName": "total_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedCategories",+ "columnName": "completed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCategories",+ "columnName": "failed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedRows",+ "columnName": "indexed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "skippedMalformedRows",+ "columnName": "skipped_malformed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deletedPrunedRows",+ "columnName": "deleted_pruned_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "last_attempt_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "section"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_index_jobs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_index_jobs_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_stalker_index_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_live_category_retries",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `category_name` TEXT NOT NULL, `configuration_generation` INTEGER NOT NULL, `attempt_count` INTEGER NOT NULL, `last_attempt_at` INTEGER NOT NULL, `last_error` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "last_attempt_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_live_category_retries_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_live_category_retries_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_portal_state",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `working_endpoint` TEXT, `bootstrap_recipe` TEXT, `bulk_live_supported` INTEGER, `bulk_live_category_fidelity` INTEGER, `movie_wildcard_supported` INTEGER, `series_wildcard_supported` INTEGER, `epg_supported` INTEGER, `safe_metadata_concurrency` INTEGER NOT NULL, `stress_cooldown_until` INTEGER NOT NULL, `endpoint_health_json` TEXT NOT NULL, `endpoint_failed_until` INTEGER NOT NULL, `validated_at` INTEGER NOT NULL, `schema_version` INTEGER NOT NULL, `configuration_generation` INTEGER NOT NULL, `learning_json` TEXT NOT NULL, `observation_source` TEXT NOT NULL, `observed_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "workingEndpoint",+ "columnName": "working_endpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bootstrapRecipe",+ "columnName": "bootstrap_recipe",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bulkLiveSupported",+ "columnName": "bulk_live_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "bulkLiveCategoryFidelity",+ "columnName": "bulk_live_category_fidelity",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "movieWildcardSupported",+ "columnName": "movie_wildcard_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seriesWildcardSupported",+ "columnName": "series_wildcard_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "epgSupported",+ "columnName": "epg_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "safeMetadataConcurrency",+ "columnName": "safe_metadata_concurrency",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stressCooldownUntil",+ "columnName": "stress_cooldown_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endpointHealthJson",+ "columnName": "endpoint_health_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "endpointFailedUntil",+ "columnName": "endpoint_failed_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "validatedAt",+ "columnName": "validated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schemaVersion",+ "columnName": "schema_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "learningJson",+ "columnName": "learning_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observationSource",+ "columnName": "observation_source",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "observedAt",+ "columnName": "observed_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_portal_state_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_portal_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_remote_identities",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `raw_id` TEXT NOT NULL, `surrogate_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `raw_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rawId",+ "columnName": "raw_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surrogateId",+ "columnName": "surrogate_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "raw_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_remote_identities_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_remote_identities_provider_id_content_type_surrogate_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_type",+ "surrogate_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id_content_type_surrogate_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `surrogate_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_discovery_staging",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`discovery_id` TEXT NOT NULL, `provider_id` INTEGER, `configuration_generation` INTEGER NOT NULL, `sanitized_summary` TEXT NOT NULL, `categories_json` TEXT NOT NULL, `channels_json` TEXT NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`discovery_id`))",+ "fields": [+ {+ "fieldPath": "discoveryId",+ "columnName": "discovery_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sanitizedSummary",+ "columnName": "sanitized_summary",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "categoriesJson",+ "columnName": "categories_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelsJson",+ "columnName": "channels_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "discovery_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_discovery_staging_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_discovery_staging_created_at",+ "unique": false,+ "columnNames": [+ "created_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_created_at` ON `${TABLE_NAME}` (`created_at`)"+ }+ ]+ },+ {+ "tableName": "downloads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `owner_id` TEXT, `owner_epoch` INTEGER NOT NULL, `heartbeat_at` INTEGER, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentName",+ "columnName": "content_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceStreamUrl",+ "columnName": "source_stream_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "sourceStreamId",+ "columnName": "source_stream_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalBytes",+ "columnName": "total_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "supportsResume",+ "columnName": "supports_resume",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerId",+ "columnName": "owner_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "ownerEpoch",+ "columnName": "owner_epoch",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_downloads_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_downloads_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_downloads_content_type_content_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"+ }+ ]+ },+ {+ "tableName": "provider_deletion_cleanup",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `action` TEXT NOT NULL, `target_id` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "action",+ "columnName": "action",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_deletion_cleanup_provider_id_action_target_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "action",+ "target_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_deletion_cleanup_provider_id_action_target_id` ON `${TABLE_NAME}` (`provider_id`, `action`, `target_id`)"+ }+ ]+ },+ {+ "tableName": "plugin_provider_ownership",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`package_name` TEXT NOT NULL, `service_class_name` TEXT NOT NULL, `manifest_id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`package_name`, `service_class_name`, `manifest_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "packageName",+ "columnName": "package_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serviceClassName",+ "columnName": "service_class_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "manifestId",+ "columnName": "manifest_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "package_name",+ "service_class_name",+ "manifest_id"+ ]+ },+ "indices": [+ {+ "name": "index_plugin_provider_ownership_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_plugin_provider_ownership_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_config_revisions",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `config_json` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `revision`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "revision",+ "columnName": "revision",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "configJson",+ "columnName": "config_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "revision"+ ]+ },+ "indices": [+ {+ "name": "index_provider_config_revisions_provider_id_state",+ "unique": false,+ "columnNames": [+ "provider_id",+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_config_revisions_provider_id_state` ON `${TABLE_NAME}` (`provider_id`, `state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "backup_restore_checkpoints",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`restore_key` TEXT NOT NULL, `room_complete` INTEGER NOT NULL, `preferences_complete` INTEGER NOT NULL, `presets_complete` INTEGER NOT NULL, `schedules_complete` INTEGER NOT NULL, `state` TEXT NOT NULL, `preference_snapshot_json` TEXT, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`restore_key`))",+ "fields": [+ {+ "fieldPath": "restoreKey",+ "columnName": "restore_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "roomComplete",+ "columnName": "room_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "preferencesComplete",+ "columnName": "preferences_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "presetsComplete",+ "columnName": "presets_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schedulesComplete",+ "columnName": "schedules_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "preferenceSnapshotJson",+ "columnName": "preference_snapshot_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "restore_key"+ ]+ }+ },+ {+ "tableName": "backup_restore_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `restore_key` TEXT NOT NULL, `backup_version` INTEGER NOT NULL, `conflict_strategy` TEXT NOT NULL, `status` TEXT NOT NULL, `total_count` INTEGER NOT NULL, `pending_count` INTEGER NOT NULL, `applied_count` INTEGER NOT NULL, `unresolved_count` INTEGER NOT NULL, `failed_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "restoreKey",+ "columnName": "restore_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "backupVersion",+ "columnName": "backup_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "conflictStrategy",+ "columnName": "conflict_strategy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCount",+ "columnName": "total_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pendingCount",+ "columnName": "pending_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "appliedCount",+ "columnName": "applied_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "unresolvedCount",+ "columnName": "unresolved_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCount",+ "columnName": "failed_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_backup_restore_jobs_restore_key",+ "unique": true,+ "columnNames": [+ "restore_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_backup_restore_jobs_restore_key` ON `${TABLE_NAME}` (`restore_key`)"+ },+ {+ "name": "index_backup_restore_jobs_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_jobs_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_backup_restore_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ]+ },+ {+ "tableName": "backup_restore_items",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `job_id` TEXT NOT NULL, `provider_identity_key` TEXT NOT NULL, `local_provider_id` INTEGER, `section` TEXT NOT NULL, `content_type` TEXT, `stable_reference_key` TEXT NOT NULL, `reference_json` TEXT NOT NULL, `payload_json` TEXT NOT NULL, `status` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`job_id`) REFERENCES `backup_restore_jobs`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "jobId",+ "columnName": "job_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerIdentityKey",+ "columnName": "provider_identity_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "localProviderId",+ "columnName": "local_provider_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stableReferenceKey",+ "columnName": "stable_reference_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "referenceJson",+ "columnName": "reference_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "payloadJson",+ "columnName": "payload_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_backup_restore_items_job_id",+ "unique": false,+ "columnNames": [+ "job_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_job_id` ON `${TABLE_NAME}` (`job_id`)"+ },+ {+ "name": "index_backup_restore_items_provider_identity_key_status",+ "unique": false,+ "columnNames": [+ "provider_identity_key",+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_provider_identity_key_status` ON `${TABLE_NAME}` (`provider_identity_key`, `status`)"+ },+ {+ "name": "index_backup_restore_items_job_id_status",+ "unique": false,+ "columnNames": [+ "job_id",+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_job_id_status` ON `${TABLE_NAME}` (`job_id`, `status`)"+ },+ {+ "name": "index_backup_restore_items_job_id_section_stable_reference_key",+ "unique": true,+ "columnNames": [+ "job_id",+ "section",+ "stable_reference_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_backup_restore_items_job_id_section_stable_reference_key` ON `${TABLE_NAME}` (`job_id`, `section`, `stable_reference_key`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "backup_restore_jobs",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "job_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_workflows",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `state` TEXT NOT NULL, `reason` TEXT NOT NULL, `priority` INTEGER NOT NULL, `force` INTEGER NOT NULL, `current_phase` TEXT, `lease_token` TEXT, `lease_expires_at` INTEGER, `heartbeat_at` INTEGER, `progress_message` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "reason",+ "columnName": "reason",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "force",+ "columnName": "force",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "currentPhase",+ "columnName": "current_phase",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseToken",+ "columnName": "lease_token",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "leaseExpiresAt",+ "columnName": "lease_expires_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "heartbeatAt",+ "columnName": "heartbeat_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "progressMessage",+ "columnName": "progress_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflows_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflows_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_provider_workflows_lease_expires_at",+ "unique": false,+ "columnNames": [+ "lease_expires_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_lease_expires_at` ON `${TABLE_NAME}` (`lease_expires_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "provider_workflow_phases",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `phase` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `checkpoint` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`, `generation`, `phase`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "generation",+ "columnName": "generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attempt_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "checkpoint",+ "columnName": "checkpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorCode",+ "columnName": "last_error_code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastErrorMessage",+ "columnName": "last_error_message",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "generation",+ "phase"+ ]+ },+ "indices": [+ {+ "name": "index_provider_workflow_phases_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_provider_workflow_phases_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_provider_workflow_phases_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "m3u_classification_overrides",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `source_key` TEXT NOT NULL, `stream_id` INTEGER NOT NULL, `target_type` TEXT NOT NULL, `group_key` TEXT NOT NULL, `series_key` TEXT, `series_name` TEXT, `season_number` INTEGER, `episode_number` INTEGER, `episode_title` TEXT, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `source_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceKey",+ "columnName": "source_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "targetType",+ "columnName": "target_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesKey",+ "columnName": "series_key",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesName",+ "columnName": "series_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeTitle",+ "columnName": "episode_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "source_key"+ ]+ },+ "indices": [+ {+ "name": "index_m3u_classification_overrides_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_m3u_classification_overrides_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "m3u_category_classification_rules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `group_key` TEXT NOT NULL, `target_type` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `group_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetType",+ "columnName": "target_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "group_key"+ ]+ },+ "indices": [+ {+ "name": "index_m3u_category_classification_rules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_m3u_category_classification_rules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '0294cba9c7af785c179086e385e2eba8')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/StalkerIdentityIntegrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StalkerIdentityIntegrationTest.ktnew file mode 100644index 00000000..49a63bd3--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/StalkerIdentityIntegrationTest.kt@@ -0,0 +1,55 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.StalkerRemoteIdentityEntity+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class StalkerIdentityIntegrationTest {+ @Test fun batchedIdentitiesRespectRoomConstraintsAndRollback() = runTest {+ val context = ApplicationProvider.getApplicationContext<Context>()+ val db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()+ try {+ val providerId = db.providerDao().insert(ProviderEntity(name = "Stalker", type = ProviderType.STALKER_PORTAL))+ val otherId = db.providerDao().insert(ProviderEntity(name = "Other", type = ProviderType.STALKER_PORTAL))+ val dao = db.stalkerRemoteIdentityDao()+ val runner = RoomDatabaseTransactionRunner(db)+ val resolver = StalkerRemoteIdentityResolver(dao, runner, db.categoryDao())+ db.categoryDao().insertAll(listOf(CategoryEntity(providerId = providerId, categoryId = 42L, name = "Existing", type = ContentType.LIVE)))+ assertThat(resolver.resolveCategories(providerId, ContentType.LIVE, listOf("remote-category" to "EXISTING")))+ .containsEntry("remote-category", 42L)+ val ids = (1..1200).map(Int::toString) + listOf("001", "string-id")+ val initial = resolver.resolveAll(providerId, ContentType.LIVE, ids)+ assertThat(initial.values.toSet()).hasSize(ids.size)+ assertThat(resolver.resolveAll(providerId, ContentType.LIVE, ids)).isEqualTo(initial)+ initial.forEach { (rawId, id) -> assertThat(resolver.reverse(providerId, ContentType.LIVE, id)).isEqualTo(rawId) }+ assertThat(resolver.resolveAll(otherId, ContentType.LIVE, listOf("1"))).containsEntry("1", 1L)+ val known = dao.getByRawId(providerId, ContentType.LIVE.name, "1")!!+ val conflict = known.copy(rawId = "conflict")+ assertThat(dao.insertAll(listOf(known, conflict))).containsExactly(-1L, -1L)+ assertThat(dao.getByRawId(providerId, ContentType.LIVE.name, "conflict")).isNull()+ assertThat(dao.getBySurrogateId(providerId, ContentType.LIVE.name, known.surrogateId)).isEqualTo(known)+ val rolledBack = StalkerRemoteIdentityEntity(providerId, ContentType.LIVE, "rollback", 9000L, 0L, 0L)+ try {+ runner.inTransaction {+ dao.insertAll(listOf(rolledBack))+ error("rollback")+ }+ } catch (expected: IllegalStateException) {+ assertThat(expected.message).isEqualTo("rollback")+ }+ assertThat(dao.getByRawId(providerId, ContentType.LIVE.name, "rollback")).isNull()+ } finally { db.close() }+ }+}diff --git a/data/src/androidTest/java/com/streamvault/data/local/StalkerLiveIngestionIntegrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StalkerLiveIngestionIntegrationTest.ktnew file mode 100644index 00000000..d9ab23e7--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/StalkerLiveIngestionIntegrationTest.kt@@ -0,0 +1,205 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.remote.stalker.*+import com.streamvault.data.sync.FallbackCategoryCollector+import com.streamvault.data.sync.SyncCatalogStore+import com.streamvault.data.sync.SyncManagerCatalogStager+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Response+import okhttp3.ResponseBody.Companion.toResponseBody+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class StalkerLiveIngestionIntegrationTest {+ @Test fun decodedPipelineRowsPromoteWithStableIdsAndSearch() = runTest {+ withFixture { db, provider, import, setPayload ->+ setPayload(payload(1..250))+ assertThat(import()).isInstanceOf(Result.Success::class.java)+ val original = db.channelDao().getByProviderSync(provider.providerId).first { it.streamId == 2L }+ db.favoriteDao().insert(FavoriteEntity(providerId = provider.providerId, contentId = original.id, contentType = ContentType.LIVE))+ assertThat(original.catchUpSupported).isTrue()+ assertThat(original.epgChannelId).isEqualTo("guide.2")+ setPayload(payload(2..251, renamed = true))+ assertThat(import()).isInstanceOf(Result.Success::class.java)+ val rows = db.channelDao().getByProviderSync(provider.providerId)+ assertThat(rows).hasSize(250)+ assertThat(rows.any { it.streamId == 1L }).isFalse()+ val refreshed = rows.first { it.streamId == 2L }+ assertThat(refreshed.id).isEqualTo(original.id)+ assertThat(refreshed.name).isEqualTo("Renamedtoken")+ assertThat(refreshed.streamUrl).isEqualTo(original.streamUrl)+ db.openHelper.writableDatabase.query("SELECT COUNT(*) FROM channels_fts WHERE channels_fts MATCH 'renamedtoken'").use {+ it.moveToFirst(); assertThat(it.getInt(0)).isEqualTo(1)+ }+ db.openHelper.writableDatabase.query("SELECT COUNT(*) FROM favorites WHERE content_id = ?", arrayOf(original.id)).use {+ it.moveToFirst(); assertThat(it.getInt(0)).isEqualTo(1)+ }+ }+ }++ @Test fun trailingOrTruncatedDocumentCannotReplaceVerifiedCatalog() = runTest {+ withFixture { db, provider, import, setPayload ->+ setPayload(payload(1..250))+ assertThat(import()).isInstanceOf(Result.Success::class.java)+ val original = db.channelDao().getByProviderSync(provider.providerId)+ for (broken in listOf(payload(300..550) + " {}", payload(300..550).dropLast(3))) {+ setPayload(broken)+ assertThat(import()).isInstanceOf(Result.Error::class.java)+ assertThat(db.channelDao().getByProviderSync(provider.providerId)).isEqualTo(original)+ db.openHelper.writableDatabase.query("SELECT COUNT(*) FROM channel_import_stage").use {+ it.moveToFirst(); assertThat(it.getInt(0)).isEqualTo(0)+ }+ }+ }+ }++ @Test fun partialCategoryCoveragePrunesOnlyCompletedCategoryRows() = runTest {+ withFixture { db, provider, _, _ ->+ val runner = RoomDatabaseTransactionRunner(db)+ val store = SyncCatalogStore(+ db.channelDao(), db.movieDao(), db.seriesDao(), db.categoryDao(),+ db.catalogSyncDao(), db.tmdbIdentityDao(), runner+ )+ val categories = listOf(+ CategoryEntity(categoryId = 10L, name = "News", parentId = 0, type = ContentType.LIVE, providerId = provider.providerId),+ CategoryEntity(categoryId = 20L, name = "Sports", parentId = 0, type = ContentType.LIVE, providerId = provider.providerId)+ )+ val existing = listOf(+ Channel(id = 1L, streamId = 1L, providerId = provider.providerId, name = "News 1", categoryId = 10L),+ Channel(id = 4L, streamId = 4L, providerId = provider.providerId, name = "News stale", categoryId = 10L),+ Channel(id = 2L, streamId = 2L, providerId = provider.providerId, name = "Sports verified", categoryId = 20L)+ ).map(Channel::toEntity)+ store.replaceLiveCatalog(provider.providerId, categories, existing)++ val sessionId = store.newSessionId()+ store.stageChannelBatch(+ provider.providerId,+ sessionId,+ listOf(Channel(+ id = 1L,+ streamId = 1L,+ providerId = provider.providerId,+ name = "News refreshed",+ categoryId = 10L+ ).toEntity())+ )+ store.applyStagedLiveCatalogWithCoverage(+ providerId = provider.providerId,+ sessionId = sessionId,+ categories = categories,+ completeCategoryIds = setOf(10L),+ pruneCategories = false+ )++ val rows = db.channelDao().getByProviderSync(provider.providerId).associateBy { it.streamId }+ assertThat(rows.keys).containsExactly(1L, 2L)+ assertThat(rows.getValue(1L).name).isEqualTo("News refreshed")+ assertThat(rows.getValue(2L).name).isEqualTo("Sports verified")+ }+ }++ @Test fun categoryFallbackStreamsValidatedPagesInBoundedBatches() = runTest {+ withFixture { _, provider, _, setPayload ->+ setPayload(payload(1..250))+ assertThat(provider.getLiveCategories()).isInstanceOf(Result.Success::class.java)+ val batches = mutableListOf<List<Channel>>()+ val result = provider.streamLiveCategory(+ categoryId = 10L,+ batchRows = 50,+ batchBytes = 256L * 1024L+ ) { channels -> batches += channels }++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data).isEqualTo(250)+ assertThat(batches.sumOf { it.size }).isEqualTo(250)+ assertThat(batches).isNotEmpty()+ assertThat(batches.maxOf { it.size }).isAtMost(50)+ }+ }++ private fun payload(ids: IntRange, renamed: Boolean = false): String =+ """{"js":{"data":[""" + ids.joinToString(",") { id ->+ """{"id":"$id","name":"${if (renamed && id == 2) "Renamedtoken" else "Channel $id"}","tv_genre_id":"10","xmltv_id":"guide.$id","archive":true,"cmd":"ffmpeg http://localhost/ch/${id}_","cmd_1":"https://cdn.example/$id.m3u8","use_http_tmp_link":1,"unknown":{"ignored":[1,2,3]}}"""+ } + "]}}"++ private suspend fun withFixture(+ block: suspend (StreamVaultDatabase, StalkerProvider, suspend () -> Result<Int>, (String) -> Unit) -> Unit+ ) {+ StalkerProvider.clearSharedAuthCacheForTests()+ val context = ApplicationProvider.getApplicationContext<Context>()+ val db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()+ try {+ val id = db.providerDao().insert(ProviderEntity(name = "Fixture", type = ProviderType.STALKER_PORTAL))+ var body = ""+ val client = OkHttpClient.Builder().addInterceptor { chain ->+ val requestUrl = chain.request().url+ val responseBody = when {+ requestUrl.queryParameter("action") == "get_genres" ->+ """{"js":[{"id":"10","title":"News"}]}"""+ requestUrl.queryParameter("action") == "get_ordered_list" &&+ requestUrl.queryParameter("p") != "1" -> """{"js":{"data":[]}}"""+ else -> body+ }+ Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(200).message("OK")+ .body(responseBody.toResponseBody("application/json".toMediaType())).build()+ }.build()+ val service = OkHttpStalkerApiService(client, Json { ignoreUnknownKeys = true })+ val api = object : StalkerApiService by service {+ override suspend fun authenticate(profile: StalkerDeviceProfile) = Result.success(+ StalkerSession("https://portal.example/server/load.php", "https://portal.example/c/", "token") to+ StalkerProviderProfile(accountName = "Fixture")+ )+ }+ val runner = RoomDatabaseTransactionRunner(db)+ val provider = StalkerProvider(id, api, "https://portal.example/c/", "00:1A:79:12:34:56",+ deviceProfile = "MAG250", timezone = "UTC", locale = "en",+ identityResolver = StalkerRemoteIdentityResolver(db.stalkerRemoteIdentityDao(), runner, db.categoryDao()))+ val categories = (provider.getLiveCategories() as Result.Success).data.map { it.toEntity(id) }+ val store = SyncCatalogStore(db.channelDao(), db.movieDao(), db.seriesDao(), db.categoryDao(), db.catalogSyncDao(), db.tmdbIdentityDao(), runner)+ val stager = SyncManagerCatalogStager(store, 25)+ suspend fun import(): Result<Int> {+ var session: Long? = null+ var collector = FallbackCategoryCollector(id, ContentType.LIVE)+ val seen = HashSet<Long>()+ val batch = ArrayList<Channel>()+ suspend fun flush() {+ if (batch.isEmpty()) return+ val staged = stager.stageChannelItems(id, batch, seen, collector, session, useLiveAdmissionCount = true)+ session = staged.sessionId+ batch.clear()+ }+ try {+ val result = provider.streamLiveStreams(batchRows = 100, batchBytes = 256L * 1024L,+ onAttemptStart = {+ session?.let { store.discardStagedImport(id, it) }+ session = null; seen.clear(); batch.clear(); collector = FallbackCategoryCollector(id, ContentType.LIVE)+ }) { channel -> batch += channel; if (batch.size == 25) flush() }+ if (result is Result.Success) { flush(); store.applyStagedLiveCatalog(id, requireNotNull(session), categories) }+ return result+ } finally { session?.let { store.discardStagedImport(id, it) } }+ }+ block(db, provider, ::import, { body = it })+ } finally {+ db.close()+ StalkerProvider.clearSharedAuthCacheForTests()+ }+ }+}diff --git a/data/src/androidTest/java/com/streamvault/data/local/StalkerVodHydrationIntegrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StalkerVodHydrationIntegrationTest.ktnew file mode 100644index 00000000..3c7b0fbd--- /dev/null+++ b/data/src/androidTest/java/com/streamvault/data/local/StalkerVodHydrationIntegrationTest.kt@@ -0,0 +1,183 @@+package com.streamvault.data.local++import android.content.Context+import androidx.room.Room+import androidx.room.withTransaction+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.PlaybackHistoryEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.data.local.entity.VodCategoryHydrationEntity+import com.streamvault.data.local.entity.VodCatalogEntryEntity+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class StalkerVodHydrationIntegrationTest {+ @Test+ fun roomPageCommitKeepsProtectionIdentityFavoritesProgressAndCatalogOrder() = runTest {+ val context = ApplicationProvider.getApplicationContext<Context>()+ val db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()+ try {+ val providerId = db.providerDao().insert(+ ProviderEntity(name = "VOD fixture", type = ProviderType.STALKER_PORTAL)+ )+ val categoryId = 42L+ db.categoryDao().insertAll(+ listOf(+ CategoryEntity(+ providerId = providerId,+ categoryId = categoryId,+ name = "Protected catalog",+ type = ContentType.VOD,+ isUserProtected = true+ )+ )+ )+ val stableMovieId = db.movieDao().insert(+ MovieEntity(+ id = 500L,+ streamId = 101L,+ name = "Before refresh",+ categoryId = categoryId,+ providerId = providerId+ )+ )+ db.favoriteDao().insert(+ FavoriteEntity(+ providerId = providerId,+ contentId = stableMovieId,+ contentType = ContentType.MOVIE+ )+ )+ db.playbackHistoryDao().insertOrUpdate(+ PlaybackHistoryEntity(+ contentId = stableMovieId,+ contentType = ContentType.MOVIE,+ providerId = providerId,+ resumePositionMs = 31_500L,+ lastWatchedAt = 100L+ )+ )++ val pageItems = listOf(+ VodCatalogEntryEntity(providerId, categoryId, "101", ContentType.MOVIE, 101L, 1, 0),+ VodCatalogEntryEntity(providerId, categoryId, "201", ContentType.SERIES, 201L, 1, 1),+ VodCatalogEntryEntity(providerId, categoryId, "102", ContentType.MOVIE, 102L, 1, 2)+ )+ db.withTransaction {+ val protected = db.categoryDao().getByProviderTypeAndCategoryId(+ providerId,+ ContentType.VOD.name,+ categoryId+ )?.isUserProtected == true+ db.movieDao().upsertCategoryPage(+ providerId,+ listOf(+ MovieEntity(+ streamId = 101L,+ name = "Updated movie",+ categoryId = categoryId,+ categoryName = "Protected catalog",+ providerId = providerId,+ isUserProtected = protected+ ),+ MovieEntity(+ streamId = 102L,+ name = "Second movie",+ categoryId = categoryId,+ categoryName = "Protected catalog",+ providerId = providerId,+ isUserProtected = protected+ )+ )+ )+ db.seriesDao().upsertCategoryPage(+ providerId,+ listOf(+ SeriesEntity(+ seriesId = 201L,+ providerSeriesId = "201",+ name = "Derived series",+ categoryId = categoryId,+ categoryName = "Protected catalog",+ providerId = providerId,+ isUserProtected = protected,+ catalogOrigin = com.streamvault.domain.model.SeriesCatalogOrigin.VOD_DERIVED+ )+ )+ )+ db.vodCatalogEntryDao().replacePage(providerId, categoryId, 1, pageItems)+ db.vodCategoryHydrationDao().upsert(+ VodCategoryHydrationEntity(+ providerId = providerId,+ categoryId = categoryId,+ lastLoadedPage = 1,+ lastAttemptedPage = 1,+ lastSuccessfulPage = 1,+ totalPages = 2,+ advertisedTotalPages = 2,+ pageSize = 3,+ itemCount = 3,+ hasMovies = true,+ hasSeries = true,+ lastStatus = "SUCCESS"+ )+ )+ }++ // The second empty terminal page advances the durable coverage receipt without+ // deleting the previously committed page or replacing the category's order.+ db.withTransaction {+ db.categoryDao().getByProviderTypeAndCategoryId(+ providerId,+ ContentType.VOD.name,+ categoryId+ )+ db.vodCatalogEntryDao().replacePage(providerId, categoryId, 2, emptyList())+ db.vodCategoryHydrationDao().upsert(+ requireNotNull(db.vodCategoryHydrationDao().get(providerId, categoryId)).copy(+ lastLoadedPage = 2,+ lastAttemptedPage = 2,+ lastSuccessfulPage = 2,+ isComplete = true+ )+ )+ }++ val movies = db.movieDao().getByProviderSync(providerId).associateBy { it.streamId }+ assertThat(movies.keys).containsExactly(101L, 102L)+ val refreshedMovie = movies.getValue(101L)+ assertThat(refreshedMovie.id).isEqualTo(stableMovieId)+ assertThat(refreshedMovie.name).isEqualTo("Updated movie")+ assertThat(refreshedMovie.isUserProtected).isTrue()+ assertThat(refreshedMovie.watchProgress).isEqualTo(31_500L)+ assertThat(+ db.favoriteDao().getGlobalByType(providerId, ContentType.MOVIE.name).first()+ .map(FavoriteEntity::contentId)+ ).containsExactly(stableMovieId)++ val series = db.seriesDao().getByProviderSync(providerId).single()+ assertThat(series.name).isEqualTo("Derived series")+ assertThat(series.isUserProtected).isTrue()+ val entries = db.vodCatalogEntryDao().observeByCategory(providerId, categoryId).first()+ assertThat(entries.map { it.rawItemId }).containsExactly("101", "201", "102").inOrder()+ assertThat(entries.map { it.rawIndex }).containsExactly(0, 1, 2).inOrder()+ val hydration = db.vodCategoryHydrationDao().get(providerId, categoryId)+ assertThat(hydration?.lastSuccessfulPage).isEqualTo(2)+ assertThat(hydration?.totalPages).isEqualTo(2)+ assertThat(hydration?.isComplete).isTrue()+ } finally {+ db.close()+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV79To80.kt b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV79To80.ktnew file mode 100644index 00000000..f03777ed--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV79To80.kt@@ -0,0 +1,31 @@+package com.streamvault.data.local++import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabase++/** Durable Stalker live-category retry scopes survive process death and provider refreshes. */+internal object FeatureMigrationsV79To80 {+ val MIGRATION_79_80 = object : Migration(79, 80) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL(+ """+ CREATE TABLE IF NOT EXISTS `stalker_live_category_retries` (+ `provider_id` INTEGER NOT NULL,+ `category_id` INTEGER NOT NULL,+ `category_name` TEXT NOT NULL,+ `configuration_generation` INTEGER NOT NULL,+ `attempt_count` INTEGER NOT NULL,+ `last_attempt_at` INTEGER NOT NULL,+ `last_error` TEXT,+ PRIMARY KEY(`provider_id`, `category_id`),+ FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ db.execSQL(+ "CREATE INDEX IF NOT EXISTS `index_stalker_live_category_retries_provider_id` " ++ "ON `stalker_live_category_retries` (`provider_id`)"+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex 81027cf3..e2cb2f5a 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -12,7 +12,7 @@ import org.json.JSONObjectimport java.net.URIimport java.security.MessageDigest-internal const val STREAM_VAULT_DATABASE_VERSION = 79+internal const val STREAM_VAULT_DATABASE_VERSION = 80@Database(entities = [@@ -59,6 +59,7 @@ internal const val STREAM_VAULT_DATABASE_VERSION = 79XtreamIndexJobEntity::class,XtreamLiveOnboardingStateEntity::class,StalkerIndexJobEntity::class,+ StalkerLiveCategoryRetryEntity::class,StalkerPortalStateEntity::class,StalkerRemoteIdentityEntity::class,StalkerDiscoveryStageEntity::class,@@ -116,6 +117,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun xtreamIndexJobDao(): XtreamIndexJobDaoabstract fun xtreamLiveOnboardingDao(): XtreamLiveOnboardingDaoabstract fun stalkerIndexJobDao(): StalkerIndexJobDao+ abstract fun stalkerLiveCategoryRetryDao(): StalkerLiveCategoryRetryDaoabstract fun stalkerPortalStateDao(): StalkerPortalStateDaoabstract fun stalkerRemoteIdentityDao(): StalkerRemoteIdentityDaoabstract fun stalkerDiscoveryStageDao(): StalkerDiscoveryStageDao@@ -207,5 +209,6 @@ abstract class StreamVaultDatabase : RoomDatabase() {val MIGRATION_76_77 = FeatureMigrationsV76To77.MIGRATION_76_77val MIGRATION_77_78 = FeatureMigrationsV77To78.MIGRATION_77_78val MIGRATION_78_79 = FeatureMigrationsV78To79.MIGRATION_78_79+ val MIGRATION_79_80 = FeatureMigrationsV79To80.MIGRATION_79_80}}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.ktindex 75148d2f..dff6bc5b 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt@@ -16,7 +16,8 @@ object StreamVaultDatabaseMigrationRegistry {val v76To77: List<Migration> = listOf(FeatureMigrationsV76To77.MIGRATION_76_77)val v77To78: List<Migration> = listOf(FeatureMigrationsV77To78.MIGRATION_77_78)val v78To79: List<Migration> = listOf(FeatureMigrationsV78To79.MIGRATION_78_79)- val all: List<Migration> = (v1To24 + v24To49 + v49To75 + v75To76 + v76To77 + v77To78 + v78To79).also(::validate)+ val v79To80: List<Migration> = listOf(FeatureMigrationsV79To80.MIGRATION_79_80)+ val all: List<Migration> = (v1To24 + v24To49 + v49To75 + v75To76 + v76To77 + v77To78 + v78To79 + v79To80).also(::validate)private fun validate(migrations: List<Migration>) {require(migrations.map { it.startVersion }.distinct().size == migrations.size) {diff --git a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.ktindex e71df4af..63ca3153 100644--- a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt@@ -421,6 +421,26 @@ interface CatalogSyncDao {)suspend fun deleteStaleChannelsForStage(providerId: Long, sessionId: Long)+ @Query(+ """+ DELETE FROM channels+ WHERE provider_id = :providerId+ AND category_id IN (:categoryIds)+ AND NOT EXISTS (+ SELECT 1+ FROM channel_import_stage AS stage+ WHERE stage.session_id = :sessionId+ AND stage.provider_id = :providerId+ AND stage.stream_id = channels.stream_id+ )+ """+ )+ suspend fun deleteStaleChannelsForStageInCategories(+ providerId: Long,+ sessionId: Long,+ categoryIds: List<Long>+ )+@Query("""UPDATE moviesdiff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex f443dc0a..163e7122 100644--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt@@ -3029,6 +3029,9 @@ interface CategoryDao {@Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY provider_order ASC, id ASC")suspend fun getByProviderAndTypeSync(providerId: Long, type: String): List<CategoryEntity>+ @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type AND category_id = :categoryId LIMIT 1")+ suspend fun getByProviderTypeAndCategoryId(providerId: Long, type: String, categoryId: Long): CategoryEntity?+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insertAll(categories: List<CategoryEntity>)diff --git a/data/src/main/java/com/streamvault/data/local/dao/StalkerSyncDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/StalkerSyncDaos.ktindex c428df77..c3b1a93b 100644--- a/data/src/main/java/com/streamvault/data/local/dao/StalkerSyncDaos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/StalkerSyncDaos.kt@@ -5,6 +5,7 @@ import androidx.room.Insertimport androidx.room.OnConflictStrategyimport androidx.room.Queryimport com.streamvault.data.local.entity.StalkerIndexJobEntity+import com.streamvault.data.local.entity.StalkerLiveCategoryRetryEntityimport com.streamvault.data.local.entity.StalkerPortalStateEntityimport com.streamvault.data.local.entity.StalkerRemoteIdentityEntityimport com.streamvault.data.local.entity.StalkerDiscoveryStageEntity@@ -34,6 +35,45 @@ interface StalkerIndexJobDao {suspend fun deleteByProvider(providerId: Long): Int}+@Dao+interface StalkerLiveCategoryRetryDao {+ @Query("SELECT * FROM stalker_live_category_retries WHERE provider_id = :providerId AND configuration_generation = :configurationGeneration ORDER BY category_id")+ suspend fun getForProvider(providerId: Long, configurationGeneration: Long): List<StalkerLiveCategoryRetryEntity>++ @Query("DELETE FROM stalker_live_category_retries WHERE provider_id = :providerId AND configuration_generation != :configurationGeneration")+ suspend fun deleteForOtherConfigurations(providerId: Long, configurationGeneration: Long): Int++ @Query("DELETE FROM stalker_live_category_retries WHERE provider_id = :providerId AND category_id IN (:categoryIds)")+ suspend fun deleteCategories(providerId: Long, categoryIds: List<Long>): Int++ @Query("DELETE FROM stalker_live_category_retries WHERE provider_id = :providerId")+ suspend fun deleteForProvider(providerId: Long): Int++ @Query("""+ INSERT INTO stalker_live_category_retries (+ provider_id, category_id, category_name, configuration_generation,+ attempt_count, last_attempt_at, last_error+ ) VALUES (+ :providerId, :categoryId, :categoryName, :configurationGeneration,+ 1, :attemptedAt, :errorMessage+ )+ ON CONFLICT(provider_id, category_id) DO UPDATE SET+ category_name = excluded.category_name,+ configuration_generation = excluded.configuration_generation,+ attempt_count = stalker_live_category_retries.attempt_count + 1,+ last_attempt_at = excluded.last_attempt_at,+ last_error = excluded.last_error+ """)+ suspend fun recordFailure(+ providerId: Long,+ categoryId: Long,+ categoryName: String,+ configurationGeneration: Long,+ attemptedAt: Long,+ errorMessage: String?+ )+}+@Daointerface StalkerPortalStateDao {@Query("SELECT * FROM stalker_portal_state WHERE provider_id = :providerId LIMIT 1")@@ -48,6 +88,16 @@ interface StalkerPortalStateDao {@Daointerface StalkerRemoteIdentityDao {+ @Query("SELECT * FROM stalker_remote_identities WHERE provider_id = :providerId AND content_type = :contentType AND raw_id IN (:rawIds)")+ suspend fun getByRawIds(providerId: Long, contentType: String, rawIds: List<String>): List<StalkerRemoteIdentityEntity>++ @Query("SELECT * FROM stalker_remote_identities WHERE provider_id = :providerId AND content_type = :contentType AND surrogate_id IN (:surrogateIds)")+ suspend fun getBySurrogateIds(providerId: Long, contentType: String, surrogateIds: List<Long>): List<StalkerRemoteIdentityEntity>++ // Never replace established identities. Ignored conflicts use the resolver's recovery path.+ @Insert(onConflict = OnConflictStrategy.IGNORE)+ suspend fun insertAll(entities: List<StalkerRemoteIdentityEntity>): List<Long>+@Query("SELECT * FROM stalker_remote_identities WHERE provider_id = :providerId AND content_type = :contentType AND raw_id = :rawId LIMIT 1")suspend fun getByRawId(providerId: Long, contentType: String, rawId: String): StalkerRemoteIdentityEntity?diff --git a/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.ktindex 410d8b73..36a3f987 100644--- a/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt+++ b/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt@@ -39,6 +39,28 @@ data class StalkerIndexJobEntity(@ColumnInfo(name = "updated_at") val updatedAt: Long = 0L)+/** A failed live category scope that must be retried before the catalog is considered fresh. */+@Entity(+ tableName = "stalker_live_category_retries",+ primaryKeys = ["provider_id", "category_id"],+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [Index(value = ["provider_id"])]+)+data class StalkerLiveCategoryRetryEntity(+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "category_id") val categoryId: Long,+ @ColumnInfo(name = "category_name") val categoryName: String,+ @ColumnInfo(name = "configuration_generation") val configurationGeneration: Long,+ @ColumnInfo(name = "attempt_count") val attemptCount: Int = 1,+ @ColumnInfo(name = "last_attempt_at") val lastAttemptAt: Long,+ @ColumnInfo(name = "last_error") val lastError: String? = null+)+@Entity(tableName = "stalker_portal_state",foreignKeys = [ForeignKey(diff --git a/data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.kt b/data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.ktindex 5b076d43..0b5d6bc6 100644--- a/data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.kt+++ b/data/src/main/java/com/streamvault/data/provider/TypedProviderClientFactory.kt@@ -8,6 +8,7 @@ import com.streamvault.data.remote.stalker.StalkerPlaybackModeimport com.streamvault.data.remote.stalker.StalkerPortalStateStoreimport com.streamvault.data.remote.stalker.StalkerProviderimport com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver+import com.streamvault.data.remote.stalker.StalkerResolvedCategoryHandoffimport com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.domain.model.JellyfinConfig@@ -126,7 +127,10 @@ class TypedProviderClientFactory @Inject constructor(catalogLayoutDetectionVersionHint = snapshot.accountRuntime.catalogLayoutDetectionVersion,identityResolver = stalkerRemoteIdentityResolver,portalStateStore = stalkerPortalStateStore,- onProgress = options.onProgress+ onProgress = options.onProgress,+ resolvedCategoryHandoffKey = StalkerResolvedCategoryHandoff.key(+ snapshot.provider.id, snapshot.configurationGeneration, config+ )))}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.ktindex 77adc58b..0c59d770 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt@@ -712,6 +712,27 @@ class OkHttpStalkerApiService @Inject constructor()}+ override suspend fun streamLiveStreamsByCategory(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ categoryId: String,+ onItem: suspend (StalkerItemRecord) -> Unit+ ): Result<Int> = runApiCall("Failed to load live channels", maxAttempts = 1) {+ streamPagedItems(+ session = session,+ profile = profile,+ baseQuery = mapOf(+ "type" to "itv",+ "action" to "get_ordered_list",+ "JsHttpRequest" to "1-xml",+ "force_ch_link_check" to "0",+ "fav" to "0",+ "genre" to categoryId+ ),+ onItem = onItem+ )+ }+override suspend fun getVodCategories(session: StalkerSession,profile: StalkerDeviceProfile@@ -1415,6 +1436,74 @@ class OkHttpStalkerApiService @Inject constructor(return items}+ /** Streams one category with the same page validation used by complete catalog reads. */+ private suspend fun streamPagedItems(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ baseQuery: Map<String, String>,+ onItem: suspend (StalkerItemRecord) -> Unit+ ): Int {+ val zoneId = profile.timezone.toPortalZoneId()+ val fingerprints = mutableSetOf<String>()+ var page = 1+ var advertisedTotalPages: Int? = null+ var reachedEnd = false+ var itemCount = 0++ while (page <= MAX_PAGE_COUNT) {+ val payload = requestJson(+ url = session.loadUrl,+ profile = profile,+ referer = session.portalReferer,+ token = session.token,+ query = baseQuery + ("p" to page.toString())+ )+ val entries = payload.extractItemEntries()+ val fingerprint = entries.joinToString("|") { entry ->+ listOf(+ entry.findString("id").orEmpty(),+ entry.findString("ch_id").orEmpty(),+ entry.findString("video_id").orEmpty(),+ entry.findString("name").orEmpty()+ ).joinToString(":")+ }+ if (page > 1 && fingerprint.isNotEmpty() && !fingerprints.add(fingerprint)) {+ throw StalkerApiError.Malformed("Portal repeated a catalog page while loading page $page.")+ }+ if (fingerprint.isNotEmpty()) fingerprints += fingerprint++ val reportedTotalPages = payload.advertisedTotalPages()+ if (advertisedTotalPages != null && reportedTotalPages != null &&+ advertisedTotalPages != reportedTotalPages+ ) {+ throw StalkerApiError.Malformed("Portal changed its advertised catalog page count while loading page $page.")+ }+ advertisedTotalPages = advertisedTotalPages ?: reportedTotalPages+ if (entries.isEmpty() && reportedTotalPages != null && page < reportedTotalPages) {+ throw StalkerApiError.Malformed("Portal returned an empty catalog page before its advertised end.")+ }++ entries.mapNotNull { it.toItemRecord(zoneId) }.forEach { item ->+ onItem(item)+ itemCount+++ }+ reachedEnd = when {+ entries.isEmpty() -> true+ reportedTotalPages != null -> page >= reportedTotalPages+ else -> false+ }+ if (reachedEnd) break+ page+++ }+ if (!reachedEnd) {+ throw StalkerApiError.CatalogTruncated(+ advertisedTotalPages = (advertisedTotalPages ?: page).coerceAtLeast(page),+ pageLimit = MAX_PAGE_COUNT+ )+ }+ return itemCount+ }+private suspend fun fetchPagedItemPage(session: StalkerSession,profile: StalkerDeviceProfile,@@ -1811,6 +1900,9 @@ class OkHttpStalkerApiService @Inject constructor(reader.isLenient = truetry {streamStalkerItems(reader, profile.timezone.toPortalZoneId(), onItem).also { itemCount ->+ if (reader.peek() != JsonToken.END_DOCUMENT) {+ throw StalkerApiError.Malformed("Portal returned trailing live catalog data.")+ }recordResolvedLoadUrl(request, response, profile)captureResponseCookies(response, profile)StalkerTelemetry.httpResponse(@@ -1874,8 +1966,7 @@ class OkHttpStalkerApiService @Inject constructor(// an item record before falling back to skip, so these catalogs are not// silently dropped on the streaming path.if (reader.peek() == JsonToken.BEGIN_OBJECT) {- val element = JsonParser.parseReader(reader)- val item = element.asJsonObjectOrNull()?.toItemRecord(zoneId)+ val item = readLiveItem(reader, zoneId)if (item != null) {onItem(item)count++@@ -1899,8 +1990,7 @@ class OkHttpStalkerApiService @Inject constructor(reader.beginArray()while (reader.hasNext()) {if (reader.peek() == JsonToken.BEGIN_OBJECT) {- val element = JsonParser.parseReader(reader)- val item = element.asJsonObjectOrNull()?.toItemRecord(zoneId)+ val item = readLiveItem(reader, zoneId)if (item != null) {onItem(item)count++@@ -2496,6 +2586,7 @@ class OkHttpStalkerApiService @Inject constructor(private suspend inline fun <T> runApiCall(message: String,+ maxAttempts: Int = MAX_OPERATION_ATTEMPTS,crossinline block: suspend () -> T): Result<T> {var attempt = 0@@ -2515,7 +2606,7 @@ class OkHttpStalkerApiService @Inject constructor(// individual API operation would defeat that cooldown.val retryable = typed is StalkerApiError.Transport ||(typed is StalkerApiError.Server && (typed.httpStatus ?: 500) >= 500)- if (!retryable || attempt >= MAX_OPERATION_ATTEMPTS) {+ if (!retryable || attempt >= maxAttempts) {return Result.error(typed.message ?: message, typed)}val exponential = 250L shl (attempt - 1)@@ -3324,7 +3415,21 @@ class OkHttpStalkerApiService @Inject constructor()}- private fun GsonJsonObject.toItemRecord(zoneId: ZoneId): StalkerItemRecord? {+ internal fun readLiveItem(reader: JsonReader, zoneId: ZoneId, direct: Boolean = true): StalkerItemRecord? {+ if (!direct) return JsonParser.parseReader(reader).asJsonObjectOrNull()?.toItemRecord(zoneId)+ val fields = StalkerLiveRowReader.read(reader)+ return toLiveItemRecord(zoneId, fields::string, fields::boolean, fields::alternateCommands)+ }++ private fun GsonJsonObject.toItemRecord(zoneId: ZoneId): StalkerItemRecord? =+ toLiveItemRecord(zoneId, { findString(it) }, { findBoolean(it) }, { extractAlternateCommands() })++ private fun toLiveItemRecord(+ zoneId: ZoneId,+ findString: (String) -> String?,+ findBoolean: (String) -> Boolean?,+ alternateCommands: () -> List<Pair<String, String>>+ ): StalkerItemRecord? {val id = findString("id")?: findString("ch_id")?: findString("video_id")@@ -3344,10 +3449,9 @@ class OkHttpStalkerApiService @Inject constructor(allowRemotePvr = findBoolean("allow_remote_pvr") == true || findString("allow_remote_pvr") == "1",archiveAvailable = findBoolean("archive") == true || findString("archive") == "1")- val alternateCommands = extractAlternateCommands()val descriptor = buildStalkerPlaybackDescriptor(primaryCmd = findString("cmd"),- alternateCommands = alternateCommands,+ alternateCommands = alternateCommands(),capabilities = capabilities)return StalkerItemRecord(diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.ktindex a3c5431d..e1da689f 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt@@ -320,6 +320,21 @@ interface StalkerApiService {onItem: suspend (StalkerItemRecord) -> Unit): Result<Int>+ /** Streams one live category a page at a time; the default keeps older test transports compatible. */+ suspend fun streamLiveStreamsByCategory(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ categoryId: String,+ onItem: suspend (StalkerItemRecord) -> Unit+ ): Result<Int> = when (val result = getLiveStreams(session, profile, categoryId)) {+ is Result.Success -> {+ result.data.forEach { onItem(it) }+ Result.success(result.data.size)+ }+ is Result.Error -> Result.error(result.message, result.exception)+ is Result.Loading -> Result.error("Unexpected loading state")+ }+suspend fun getVodCategories(session: StalkerSession,profile: StalkerDeviceProfilediff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerLivePipeline.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerLivePipeline.ktnew file mode 100644index 00000000..88187a97--- /dev/null+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerLivePipeline.kt@@ -0,0 +1,73 @@+package com.streamvault.data.remote.stalker++import com.streamvault.domain.model.Result+import java.util.concurrent.atomic.AtomicBoolean+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.async+import kotlinx.coroutines.cancel+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.channels.Channel+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.withContext++/** One bounded reader and one owner of identity mapping and staging callbacks per attempt. */+internal suspend fun runStalkerLivePipeline(+ batchRows: Int,+ batchBytes: Long,+ localWork: (Boolean) -> Unit,+ read: suspend (suspend (StalkerItemRecord) -> Unit) -> Result<Int>,+ consume: suspend (List<StalkerItemRecord>) -> Unit+): Result<Int> = coroutineScope {+ require(batchRows > 0 && batchBytes > 0)+ val queue = Channel<List<StalkerItemRecord>>(1)+ val cleaningUp = AtomicBoolean()+ val writer = async(Dispatchers.Default) {+ try {+ for (batch in queue) {+ localWork(true)+ try { consume(batch) } finally { localWork(false) }+ }+ } catch (cancelled: CancellationException) {+ if (!cleaningUp.get()) [email protected](cancelled)+ throw cancelled+ }+ }+ try {+ var batch = ArrayList<StalkerItemRecord>(batchRows)+ var bytes = 0L+ suspend fun flush() {+ if (batch.isEmpty()) return+ localWork(true)+ try { queue.send(batch) } finally { localWork(false) }+ batch = ArrayList(batchRows)+ bytes = 0L+ }+ val result = read { row ->+ val size = row.estimatedLiveBufferBytes()+ if (size > batchBytes) throw StalkerApiError.ResponseTooLarge("Live row exceeds the buffered batch budget.")+ if (batch.isNotEmpty() && bytes + size > batchBytes) flush()+ batch += row+ bytes += size+ if (batch.size >= batchRows || bytes >= batchBytes) flush()+ }+ if (result is Result.Success) {+ flush()+ queue.close()+ writer.await()+ }+ result+ } finally {+ cleaningUp.set(true)+ queue.cancel()+ // Retry and staging cleanup must wait for callbacks to stop, including parent cancel.+ withContext(NonCancellable) { writer.cancelAndJoin() }+ }+}++private fun StalkerItemRecord.estimatedLiveBufferBytes(): Long =+ 768L + listOf(id, name, categoryId, categoryName, logoUrl, epgChannelId, cmd, streamUrl,+ plot, cast, director, genre, releaseDate, youtubeTrailer, backdropUrl, containerExtension, mcCmd)+ .sumOf { 40L + 2L * (it?.length ?: 0) } ++ commandVariants.sumOf { 128L + 2L * (it.cmd.length + it.sourceKey.length) }diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerLiveRowReader.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerLiveRowReader.ktnew file mode 100644index 00000000..35ce3887--- /dev/null+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerLiveRowReader.kt@@ -0,0 +1,89 @@+package com.streamvault.data.remote.stalker++import com.google.gson.stream.JsonReader+import com.google.gson.stream.JsonToken+import java.util.Locale++/** Retains mapped scalar fields and command variants, skipping unknown nested metadata. */+internal class StalkerLiveRowFields(+ private val scalars: Map<String, String?>,+ private val arrayCommands: List<Pair<String, String>>,+ private val invalidCommandsShape: Boolean+) {+ fun string(key: String): String? = scalars[key]+ fun boolean(key: String): Boolean? = when (string(key)?.lowercase(Locale.ROOT)) {+ "1", "true", "yes" -> true+ "0", "false", "no" -> false+ else -> null+ }++ fun alternateCommands(): List<Pair<String, String>> {+ check(!invalidCommandsShape) { "Portal command variants must be an array" }+ return (listOf("cmd_1", "cmd_2", "cmd_3", "mc_cmd").mapNotNull { key ->+ string(key)?.let { key to it }+ } + arrayCommands).distinctBy { it.second.trim() }+ }+}++internal object StalkerLiveRowReader {+ private val scalarKeys = setOf(+ "id", "ch_id", "video_id", "series_id", "name", "title", "tv_genre_id", "category_id",+ "genre_id", "category_name", "number", "logo", "screenshot_uri", "cover", "xmltv_id", "epg_id",+ "cmd", "cmd_1", "cmd_2", "cmd_3", "mc_cmd", "use_http_tmp_link", "nginx_secure_link",+ "flussonic_tmp_link", "wowza_tmp_link", "use_load_balancing", "allow_local_timeshift",+ "allow_local_pvr", "allow_remote_pvr", "archive", "description", "plot", "actors", "director",+ "genres_str", "genre", "year", "released", "added", "rating_imdb", "rating", "tmdb_id",+ "trailer_url", "backdrop_path", "container_extension", "censored", "is_series"+ )++ fun read(reader: JsonReader): StalkerLiveRowFields {+ val scalars = HashMap<String, String?>()+ var commands: List<Pair<String, String>> = emptyList()+ var invalidCommandsShape = false+ reader.beginObject()+ while (reader.hasNext()) {+ when (val key = reader.nextName()) {+ "cmds" -> {+ invalidCommandsShape = reader.peek() != JsonToken.BEGIN_ARRAY+ commands = if (invalidCommandsShape) { reader.skipValue(); emptyList() } else readCommands(reader)+ }+ in scalarKeys -> scalars[key] = readScalar(reader)+ else -> reader.skipValue()+ }+ }+ reader.endObject()+ return StalkerLiveRowFields(scalars, commands, invalidCommandsShape)+ }++ private fun readCommands(reader: JsonReader): List<Pair<String, String>> {+ val commands = ArrayList<Pair<String, String>>()+ reader.beginArray()+ var index = 0+ while (reader.hasNext()) {+ if (reader.peek() == JsonToken.BEGIN_OBJECT) {+ var url: String? = null+ var cmd: String? = null+ reader.beginObject()+ while (reader.hasNext()) {+ when (reader.nextName()) {+ "url" -> url = readScalar(reader)+ "cmd" -> cmd = readScalar(reader)+ else -> reader.skipValue()+ }+ }+ reader.endObject()+ (url ?: cmd)?.let { commands += "cmds[$index]" to it }+ } else reader.skipValue()+ index+++ }+ reader.endArray()+ return commands+ }++ private fun readScalar(reader: JsonReader): String? = when (reader.peek()) {+ JsonToken.STRING, JsonToken.NUMBER -> reader.nextString().trim().takeIf(String::isNotBlank)+ JsonToken.BOOLEAN -> reader.nextBoolean().toString()+ JsonToken.NULL -> { reader.nextNull(); null }+ else -> { reader.skipValue(); null }+ }+}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.ktindex 56db9efa..6bfe8614 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt@@ -48,6 +48,7 @@ import java.security.MessageDigestimport java.util.Base64import java.util.Localeimport java.util.concurrent.ConcurrentHashMap+import kotlinx.coroutines.delaydata class StalkerPlaybackInfo(val url: String,@@ -123,7 +124,8 @@ class StalkerProvider(private val portalStateStore: StalkerPortalStateStore? = null,private val discoveryCoordinator: StalkerDiscoveryCoordinator =StalkerDiscoveryCoordinator(api),- private val onProgress: ((String) -> Unit)? = null+ private val onProgress: ((String) -> Unit)? = null,+ private val resolvedCategoryHandoffKey: String? = null) : ProviderAuthenticator,LiveCatalogSource,VodCatalogSource,@@ -153,6 +155,7 @@ internal companion object {private val missingVodClassificationLogged = ConcurrentHashMap.newKeySet<Long>()fun clearSharedAuthCacheForTests() {+ StalkerResolvedCategoryHandoff.clear()sharedAuthCache.clear()sharedPortalAuthCache.clear()sharedAuthFailureCache.clear()@@ -165,6 +168,7 @@ internal companion object {/** Provider deletion hook for process-lifetime authentication and URL caches. */fun clearCachesForProvider(providerId: Long) {if (providerId <= 0L) return+ StalkerResolvedCategoryHandoff.clearProvider(providerId)val authPrefix = "provider:$providerId|"sharedAuthCache.keys.filter { it.startsWith(authPrefix) }.forEach(sharedAuthCache::remove)val portalPrefix = "portal:$providerId|"@@ -220,6 +224,29 @@ internal companion object {val name: String)+ /** Retains first-list-match semantics even when ID and name point at different seeds. */+ private class CategoryLookup(val seeds: List<CategorySeed>) {+ private val byRawId = HashMap<String, IndexedValue<CategorySeed>>()+ private val byName = java.util.TreeMap<String, IndexedValue<CategorySeed>>(String.CASE_INSENSITIVE_ORDER)++ init {+ seeds.withIndex().forEach { entry ->+ byRawId.putIfAbsent(entry.value.rawId, entry)+ byName.putIfAbsent(entry.value.name, entry)+ }+ }++ fun resolve(rawId: String?, name: String?): CategorySeed? {+ val raw = rawId?.let(byRawId::get)+ val named = name?.let(byName::get)+ return when {+ raw == null -> named?.value+ named == null || raw.index <= named.index -> raw.value+ else -> named.value+ }+ }+ }+// Authentication lock identity must remain stable for the provider lifetime. Evicting a// configuration-scoped lock while an older provider instance still holds it permits a second// mutex to be created and defeats same-provider authentication serialization.@@ -227,14 +254,19 @@ internal companion object {private var accountProfileCache: StalkerProviderProfile? = nullprivate var authFailureCache: CachedAuthFailure? = nullprivate val categoryCache = mutableMapOf<ContentType, List<CategorySeed>>()+ private val categoryLookups = mutableMapOf<ContentType, CategoryLookup>()+ private var resolvedCategorySnapshot: StalkerResolvedCategoryHandoff.Snapshot? = nullprivate val remoteIdentityCache = ConcurrentHashMap<Pair<ContentType, String>, Long>()suspend fun invalidateAuthentication() {+ resolvedCategorySnapshot = null+ resolvedCategoryHandoffKey?.let(StalkerResolvedCategoryHandoff::invalidate)sharedAuthMutexes.withLock(authMutexKey()) {sessionCache = nullaccountProfileCache = nullauthFailureCache = nullcategoryCache.clear()+ categoryLookups.clear()sharedAuthCache.remove(authCacheKey())if (providerId > 0L) {sharedPortalAuthCache.remove(portalIdentityKey())@@ -281,6 +313,7 @@ internal companion object {val profile = authResult.data.secondval catalogDetection = detectCatalogLayout(authResult.data.first, profile)val catalogLayout = catalogDetection.layout+ resolvedCategorySnapshot = resolvedCategorySnapshot?.copy(layout = catalogLayout)val learnedDeviceProfile = buildLearnedDeviceProfile(profile)val hostLabel = portalUrl.substringAfter("://").substringBefore('/').ifBlank { "portal" }val providerName = profile.accountName?.takeUnless { it.isBlank() || it == "0" }@@ -361,6 +394,7 @@ internal companion object {val device = buildLearnedDeviceProfile(profile)val seriesResult = api.getSeriesCategories(session, device)+ if (seriesResult is Result.Success) rememberResolvedCategories(session, ContentType.SERIES, seriesResult.data)if (seriesResult is Result.Success && seriesResult.data.isNotEmpty()) {StalkerTelemetry.catalogLayoutDetected(providerId,@@ -377,7 +411,9 @@ internal companion object {return CatalogLayoutDetection(catalogLayoutHint, conclusive = false)}- return when (val vodResult = api.getVodCategories(session, device)) {+ val vodResult = api.getVodCategories(session, device)+ if (vodResult is Result.Success) rememberResolvedCategories(session, ContentType.MOVIE, vodResult.data)+ return when (vodResult) {is Result.Success -> if (vodResult.data.isNotEmpty()) {StalkerTelemetry.catalogLayoutDetected(providerId,@@ -426,56 +462,108 @@ internal companion object {return session to profile}+ private fun rememberResolvedCategories(session: StalkerSession, type: ContentType, records: List<StalkerCategoryRecord>) {+ val previous = resolvedCategorySnapshot?.takeIf { it.matches(session) }+ resolvedCategorySnapshot = StalkerResolvedCategoryHandoff.Snapshot(+ session, previous?.categories.orEmpty() + (type to records.toList())+ )+ }++ internal fun handoffResolvedCategories(key: String) {+ resolvedCategorySnapshot?.let { StalkerResolvedCategoryHandoff.publish(key, it) }+ }+suspend fun streamLiveStreams(maxChannels: Int? = null,+ batchRows: Int = LIVE_IDENTITY_BATCH_SIZE,+ batchBytes: Long = 1024L * 1024L,+ onAttemptStart: suspend () -> Unit = {},+ awaitCategoryContext: suspend () -> Unit = {},+ onReadProgress: () -> Unit = {},+ onLocalWork: (Boolean) -> Unit = {},onChannel: suspend (Channel) -> Unit- ): Result<Int> {- return runWithAuthorizedSession { session, _ ->- val pendingItems = ArrayList<StalkerItemRecord>(LIVE_IDENTITY_BATCH_SIZE)- val limit = maxChannels?.takeIf { it > 0 }- var acceptedCount = 0-- suspend fun flushPendingItems() {- if (pendingItems.isEmpty()) return- bindRemoteIds(ContentType.LIVE, pendingItems.map(StalkerItemRecord::id))- pendingItems.forEach { item ->- toChannel(item)?.let { channel ->- onChannel(channel)+ ): Result<Int> = runWithAuthorizedSession { session, _ ->+ onAttemptStart()+ val limit = maxChannels?.takeIf { it > 0 }+ var acceptedCount = 0+ runStalkerLivePipeline(+ batchRows = batchRows,+ batchBytes = batchBytes,+ localWork = onLocalWork,+ read = { emit ->+ val result = try {+ api.streamLiveStreams(session, currentDeviceProfile()) { item ->+ onReadProgress()+ if (limit != null && acceptedCount >= limit) throw LiveStreamLimitReached+ emit(item)+ acceptedCount++}+ } catch (capReached: LiveStreamLimitReached) {+ Result.success(acceptedCount)}- pendingItems.clear()- }-- val result = try {- api.streamLiveStreams(session, currentDeviceProfile()) { item ->- if (limit != null && acceptedCount >= limit) {- throw LiveStreamLimitReached- }- pendingItems += item- acceptedCount++- if (pendingItems.size >= LIVE_IDENTITY_BATCH_SIZE) {- flushPendingItems()- }+ when (result) {+ is Result.Error -> if (result.exception is LiveStreamLimitReached) Result.success(acceptedCount) else result+ is Result.Loading -> Result.error("Unexpected loading state")+ is Result.Success -> result}- } catch (capReached: LiveStreamLimitReached) {- flushPendingItems()- return@runWithAuthorizedSession Result.success(acceptedCount)+ },+ consume = { items ->+ // Bulk HTTP may begin before category metadata when the portal safely admits+ // two requests. Keep the single mapping owner behind this barrier so category+ // IDs/names are resolved against a complete immutable seed set.+ awaitCategoryContext()+ bindRemoteIds(ContentType.LIVE, items.map(StalkerItemRecord::id))+ items.forEach { item -> toChannel(item)?.let { onChannel(it) } }}+ )+ }- when (result) {- is Result.Success -> {- flushPendingItems()- Result.success(result.data)- }- is Result.Error -> {- if (result.exception is LiveStreamLimitReached) {- flushPendingItems()- Result.success(acceptedCount)- } else Result.error(result.message, result.exception)+ /** Streams one category with bounded row batches for isolated fallback staging. */+ suspend fun streamLiveCategory(+ categoryId: Long,+ batchRows: Int,+ batchBytes: Long,+ onAttemptStart: suspend () -> Unit = {},+ onMappedBatch: suspend (List<Channel>) -> Unit+ ): Result<Int> = runWithAuthorizedSession { session, _ ->+ val rawCategoryId = resolveRawCategoryId(ContentType.LIVE, categoryId)+ ?.takeIf(String::isNotBlank)+ ?: return@runWithAuthorizedSession Result.error("Live category $categoryId is unavailable")+ var attempt = 0+ var finalResult: Result<Int>? = null+ while (finalResult == null) {+ // Each retry gets a new staging session only after the previous pipeline has+ // drained its consumer and returned, so no failed rows can cross attempts.+ onAttemptStart()+ val result = runStalkerLivePipeline(+ batchRows = batchRows,+ batchBytes = batchBytes,+ localWork = {},+ read = { emit ->+ api.streamLiveStreamsByCategory(+ session = session,+ profile = currentDeviceProfile(),+ categoryId = rawCategoryId,+ onItem = emit+ )+ },+ consume = { items ->+ bindRemoteIds(ContentType.LIVE, items.map(StalkerItemRecord::id))+ val channels = items.mapNotNull(::toChannel)+ if (channels.isNotEmpty()) onMappedBatch(channels)}- is Result.Loading -> Result.error("Unexpected loading state")+ )+ val error = (result as? Result.Error)?.exception+ val retryable = error is StalkerApiError.Transport ||+ (error is StalkerApiError.Server && (error.httpStatus ?: 500) >= 500)+ if (!retryable || attempt >= 2) {+ finalResult = result+ } else {+ delay(250L shl attempt)+ attempt++}}+ requireNotNull(finalResult)}override suspend fun getVodCategories(): Result<List<Category>> =@@ -484,7 +572,7 @@ internal companion object {}suspend fun getUnifiedVodCategories(): Result<List<Category>> =- mapCategories(ContentType.VOD) { session, profile ->+ mapCategories(ContentType.VOD, resolvedType = ContentType.MOVIE) { session, profile ->api.getVodCategories(session, profile)}@@ -1430,10 +1518,21 @@ is Result.Success -> {private suspend fun mapCategories(type: ContentType,+ resolvedType: ContentType = type,loader: suspend (StalkerSession, StalkerDeviceProfile) -> Result<List<StalkerCategoryRecord>>): Result<List<Category>> {return runWithAuthorizedSession { session, _ ->- when (val result = loader(session, currentDeviceProfile())) {+ if (resolvedCategorySnapshot?.matches(session) != true) resolvedCategorySnapshot = null+ if (resolvedCategorySnapshot == null) {+ resolvedCategorySnapshot = resolvedCategoryHandoffKey?.let {+ StalkerResolvedCategoryHandoff.take(it, session, catalogLayoutHint)+ }+ }+ val cachedRecords = resolvedCategorySnapshot?.categories?.get(resolvedType)+ if (cachedRecords != null) {+ resolvedCategorySnapshot = resolvedCategorySnapshot?.let { it.copy(categories = it.categories - resolvedType) }+ }+ when (val result = cachedRecords?.let { Result.success(it) } ?: loader(session, currentDeviceProfile())) {is Result.Success -> {val categoryRecords = result.data.ifEmpty {when (type) {@@ -2691,11 +2790,11 @@ private fun playbackTransportChallengeFor(url: String): StalkerTransportChallengprivate fun resolveCategory(type: ContentType, rawId: String?, rawName: String?): CategorySeed {val normalizedName = rawName?.trim().takeUnless { it.isNullOrBlank() }val normalizedRawId = rawId?.trim().takeUnless { it.isNullOrBlank() }- val cached = categoryCache[type]- ?.firstOrNull { category ->- category.rawId == normalizedRawId ||- (normalizedName != null && category.name.equals(normalizedName, ignoreCase = true))- }+ val cached = categoryCache[type]?.let { seeds ->+ val lookup = categoryLookups[type]?.takeIf { it.seeds === seeds }+ ?: CategoryLookup(seeds).also { categoryLookups[type] = it }+ lookup.resolve(normalizedRawId, normalizedName)+ }if (cached != null) {return cached}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.ktindex e4efd70b..0f0324d1 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt@@ -43,7 +43,7 @@ class StalkerRemoteIdentityResolver private constructor(val key = "$providerId/${contentType.name}"return locks.withLock(key) {transactionRunner.inTransaction {- normalizedIds.associateWith { rawId -> resolveLocked(providerId, contentType, rawId) }+ resolveBatchLocked(providerId, contentType, normalizedIds)}}}@@ -72,11 +72,75 @@ class StalkerRemoteIdentityResolver private constructor(val key = "$providerId/${contentType.name}"return locks.withLock(key) {transactionRunner.inTransaction {- normalized.associate { (rawId, _) ->- rawId to resolveLocked(providerId, contentType, rawId, preferred[rawId])+ resolveBatchLocked(providerId, contentType, normalized.map { it.first }, preferred)+ }+ }+ }++ private suspend fun resolveBatchLocked(+ providerId: Long,+ contentType: ContentType,+ rawIds: List<String>,+ preferred: Map<String, Long?> = emptyMap()+ ): Map<String, Long> {+ val resolved = LinkedHashMap<String, Long>(rawIds.size)+ rawIds.chunked(SQL_BATCH_SIZE).forEach { chunk ->+ dao.getByRawIds(providerId, contentType.name, chunk).forEach {+ resolved[it.rawId] = it.surrogateId+ }+ }+ // Chunk candidates and pending inserts as well as SQL parameters. The caller's input+ // remains the identity batch; no provider-wide identity snapshot is retained.+ var highestAllocated: Long? = null+ rawIds.filterNot(resolved::containsKey).chunked(SQL_BATCH_SIZE).forEach { chunk ->+ val candidates = chunk.associateWith { rawId ->+ listOfNotNull(+ preferred[rawId]?.takeIf { it > 0L },+ rawId.toLongOrNull()?.takeIf { it > 0L },+ legacyId(providerId, contentType, rawId)+ )+ }+ val occupied = HashSet<Long>()+ candidates.values.flatten().distinct().chunked(SQL_BATCH_SIZE).forEach { ids ->+ dao.getBySurrogateIds(providerId, contentType.name, ids).forEach {+ occupied += it.surrogateId+ }+ }+ val pending = chunk.map { rawId ->+ val candidate = candidates.getValue(rawId).firstOrNull { it !in occupied }+ ?: run {+ if (highestAllocated == null) {+ highestAllocated = dao.maxAllocatedSurrogate(+ providerId, contentType.name, HIGH_SURROGATE_FLOOR+ ) ?: (HIGH_SURROGATE_FLOOR - 1L)+ }+ (requireNotNull(highestAllocated) + 1L).coerceAtMost(Long.MAX_VALUE - 1L)+ }+ occupied += candidate+ if (candidate >= HIGH_SURROGATE_FLOOR) {+ // Include identities assigned earlier in this pending batch, just as the+ // previous sequential INSERT path did when allocating its next high ID.+ if (highestAllocated == null) {+ highestAllocated = dao.maxAllocatedSurrogate(+ providerId, contentType.name, HIGH_SURROGATE_FLOOR+ ) ?: (HIGH_SURROGATE_FLOOR - 1L)+ }+ highestAllocated = maxOf(requireNotNull(highestAllocated), candidate)+ }+ val now = System.currentTimeMillis()+ StalkerRemoteIdentityEntity(providerId, contentType, rawId, candidate, now, now)+ }+ val inserted = dao.insertAll(pending)+ pending.zip(inserted).forEach { (entity, rowId) ->+ resolved[entity.rawId] = if (rowId != -1L) entity.surrogateId else {+ // A competing mapping must never be overwritten. Resolve ignored rows+ // through the established collision recovery logic.+ highestAllocated = null+ resolveLocked(providerId, contentType, entity.rawId, preferred[entity.rawId])}}}+ return rawIds.associateWith { resolved.getValue(it) }}private suspend fun resolveLocked(@@ -123,6 +187,7 @@ class StalkerRemoteIdentityResolver private constructor(}private companion object {+ const val SQL_BATCH_SIZE = 400const val HIGH_SURROGATE_FLOOR = 4_000_000_000L}}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.ktindex f799e703..771e0db2 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt@@ -228,6 +228,14 @@ class StalkerRequestCoordinator @Inject constructor(}}+ /** Returns the currently admitted metadata limit after loading persisted portal health. */+ suspend fun effectiveConcurrencyLimit(providerId: Long): Int {+ if (providerId <= 0L) return NORMAL_METADATA_CONCURRENCY+ val state = states.computeIfAbsent(providerId) { ProviderState() }+ hydratePersistedState(providerId, state)+ return state.mutex.withLock { state.currentLimit(System.currentTimeMillis()) }+ }+suspend fun recordFailure(providerId: Long, error: Throwable?) {if (providerId <= 0L) returnerror?.findRateLimit()?.let { rateLimit ->diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerResolvedCategoryHandoff.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerResolvedCategoryHandoff.ktnew file mode 100644index 00000000..275a6335--- /dev/null+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerResolvedCategoryHandoff.kt@@ -0,0 +1,52 @@+package com.streamvault.data.remote.stalker++import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.StalkerConfig+import com.google.gson.Gson+import java.security.MessageDigest+import java.util.concurrent.ConcurrentHashMap++/** One-shot, process-local reuse of successful layout probes, never authentication authority. */+internal object StalkerResolvedCategoryHandoff {+ private const val TTL_MILLIS = 60_000L+ private const val MAX_ENTRIES = 256+ private val pending = ConcurrentHashMap<String, Snapshot>()+ private val gson = Gson()++ data class Snapshot(+ val session: StalkerSession,+ val categories: Map<ContentType, List<StalkerCategoryRecord>>,+ val createdAt: Long = System.currentTimeMillis(),+ val layout: CatalogLayout = CatalogLayout.UNKNOWN+ ) {+ fun matches(current: StalkerSession, now: Long = System.currentTimeMillis()): Boolean =+ now - createdAt in 0 until TTL_MILLIS && !session.isExpired(now) &&+ session.loadUrl == current.loadUrl && session.token == current.token &&+ session.authEpoch == current.authEpoch && session.sessionScopeKey == current.sessionScopeKey+ }++ fun key(providerId: Long, generation: Long, config: StalkerConfig): String {+ // Credentials/configuration participate in matching, but are not retained in map keys.+ val digest = MessageDigest.getInstance("SHA-256")+ .digest(gson.toJson(config).toByteArray(Charsets.UTF_8))+ val hex = "0123456789abcdef"+ return "$providerId/$generation/" + buildString(digest.size * 2) {+ digest.forEach { append(hex[(it.toInt() and 255) ushr 4]); append(hex[it.toInt() and 15]) }+ }+ }++ fun publish(key: String, snapshot: Snapshot) {+ val now = System.currentTimeMillis()+ pending.entries.removeIf { now - it.value.createdAt >= TTL_MILLIS }+ pending[key] = snapshot.copy(categories = snapshot.categories.mapValues { it.value.toList() })+ while (pending.size > MAX_ENTRIES) pending.keys.firstOrNull()?.let(pending::remove) ?: break+ }++ fun take(key: String, session: StalkerSession, layout: CatalogLayout = CatalogLayout.UNKNOWN): Snapshot? =+ pending.remove(key)?.takeIf { it.matches(session) && (layout == CatalogLayout.UNKNOWN || it.layout == layout) }++ fun invalidate(key: String) { pending.remove(key) }+ fun clearProvider(providerId: Long) { pending.keys.filter { it.startsWith("$providerId/") }.forEach(pending::remove) }+ fun clear() { pending.clear() }+}diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex 5cc1b880..0d49f1fc 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -36,6 +36,7 @@ import com.streamvault.data.provider.guidePolicyimport com.streamvault.data.provider.logoPolicyimport com.streamvault.data.remote.jellyfin.JellyfinProviderimport com.streamvault.data.remote.stalker.StalkerApiService+import com.streamvault.data.remote.stalker.StalkerResolvedCategoryHandoffimport com.streamvault.data.remote.stalker.StalkerPlaybackModeimport com.streamvault.data.remote.stalker.StalkerProviderimport com.streamvault.data.remote.stalker.StalkerPortalStateStore@@ -1208,6 +1209,16 @@ class ProviderRepositoryImpl @Inject constructor()}+ if (!acceptedWithoutVerification) {+ val handoffProvider = onboardingTarget.providerForSync+ authenticatedProvider.handoffResolvedCategories(+ StalkerResolvedCategoryHandoff.key(+ handoffProvider.id,+ handoffProvider.stalkerConfigurationGeneration,+ handoffProvider.toTypedConfiguration() as StalkerConfig+ )+ )+ }val onboardingResult = try {if (acceptedWithoutVerification) {syncManager.scheduleProviderSyncResume(diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.ktindex 00963111..cc7d20d4 100644--- a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt+++ b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt@@ -9,6 +9,7 @@ import com.streamvault.data.local.dao.MovieCategoryHydrationDaoimport com.streamvault.data.local.dao.MovieDaoimport com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.StalkerLiveCategoryRetryDaoimport com.streamvault.data.local.dao.VodCategoryHydrationDaoimport com.streamvault.data.local.dao.VodCatalogEntryDaoimport com.streamvault.data.local.entity.CategoryEntity@@ -18,6 +19,8 @@ import com.streamvault.data.remote.dto.XtreamCategoryimport com.streamvault.data.remote.stalker.StalkerApiErrorimport com.streamvault.data.remote.stalker.StalkerProviderimport com.streamvault.data.remote.stalker.StalkerProviderProfile+import com.streamvault.data.remote.stalker.StalkerRequestCoordinator+import com.streamvault.data.remote.stalker.StalkerRequestDescriptorimport com.streamvault.data.remote.stalker.StalkerTelemetryimport com.streamvault.data.provider.toProviderSnapshotimport com.streamvault.data.util.UrlSecurityPolicy@@ -29,12 +32,16 @@ import com.streamvault.domain.model.LegacyProvider as Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StalkerCatalogMode+import com.streamvault.domain.model.StalkerRequestPriorityimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.model.VodSyncModeimport com.streamvault.domain.repository.ProviderSnapshotRepositoryimport com.streamvault.domain.repository.SyncMetadataRepositoryimport com.streamvault.domain.sync.Sectionimport kotlinx.coroutines.CancellationException+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.withContextimport kotlinx.coroutines.asyncimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delay@@ -42,7 +49,9 @@ import kotlinx.coroutines.isActiveimport kotlinx.coroutines.launchimport kotlinx.coroutines.flow.firstimport java.io.IOException+import java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.atomic.AtomicLong+import java.util.concurrent.atomic.AtomicIntegerprivate const val STALKER_EXECUTOR_TAG = "StalkerCatalogSync"private const val STALKER_MAX_PARALLEL_CATEGORY_FETCHES = 2@@ -75,6 +84,8 @@ internal class StalkerCatalogSyncExecutor(private val categoryRecoverySupport: SyncManagerXtreamSupport,private val sectionExecutor: StalkerCatalogSectionExecutor,private val readinessTracker: StalkerReadinessTracker,+ private val stalkerRequestCoordinator: StalkerRequestCoordinator,+ private val liveCategoryRetryDao: StalkerLiveCategoryRetryDao,private val createProvider: (Provider) -> StalkerProvider,private val syncProviderEpg: suspend (Provider, SyncMetadata, Long, Boolean, ((String) -> Unit)?) -> ProviderGuideSyncResult,private val progress: (Long, ((String) -> Unit)?, String) -> Unit,@@ -168,16 +179,21 @@ internal class StalkerCatalogSyncExecutor(requiredHiddenLiveCategoryIds = requiredHiddenLiveCategoryIds,onProgress = onProgress,maxChannels = STALKER_BOOTSTRAP_LIVE_CHANNEL_CAP.takeIf { bootstrap },- afterCatalogApply = catalogCommitCallback+ afterCatalogApply = catalogCommitCallback,+ retryPendingCategoriesOnly = !force && !bootstrap)+ val committedLiveCount = if (liveCatalogResult.catalogApplied) {+ channelDao.getCount(provider.id).first()+ } else metadata.liveCountmetadata = metadata.copy(lastLiveSync = now,- lastLiveSuccess = if (bootstrap) metadata.lastLiveSuccess else now,- liveCount = liveCatalogResult.acceptedCount+ lastLiveSuccess = if (!bootstrap && liveCatalogResult.coverageComplete) now+ else metadata.lastLiveSuccess,+ liveCount = committedLiveCount)- liveCount = liveCatalogResult.acceptedCount+ liveCount = committedLiveCountactivatedLiveMutations = liveCatalogResult.acceptedCount- if (liveCatalogResult.acceptedCount > 0) {+ if (liveCatalogResult.catalogApplied) {catalogActivated = true} else {preservedActiveCatalog = true@@ -400,12 +416,18 @@ internal class StalkerCatalogSyncExecutor(provider,hiddenLiveCategoryIds,requiredHiddenLiveCategoryIds,- onProgress+ onProgress,+ retryPendingCategoriesOnly = true)- val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)).copy(+ val previousMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)+ val committedLiveCount = if (liveCatalogResult.catalogApplied) {+ channelDao.getCount(provider.id).first()+ } else previousMetadata.liveCount+ val metadata = previousMetadata.copy(lastLiveSync = now,- lastLiveSuccess = now,- liveCount = liveCatalogResult.acceptedCount+ lastLiveSuccess = if (liveCatalogResult.coverageComplete) now+ else previousMetadata.lastLiveSuccess,+ liveCount = committedLiveCount)syncMetadataRepository.updateMetadata(metadata)emitCatalogProgress(provider.id, Section.LIVE, null, liveCatalogResult.acceptedCount)@@ -414,7 +436,7 @@ internal class StalkerCatalogSyncExecutor(partial = warnings.isNotEmpty(),warnings = warnings.distinct(),stagedMutations = liveCatalogResult.acceptedCount,- activation = if (liveCatalogResult.acceptedCount > 0) {+ activation = if (liveCatalogResult.catalogApplied) {SyncActivation.ACTIVATED_CATALOG} else {SyncActivation.PRESERVED_ACTIVE_CATALOG@@ -429,31 +451,67 @@ internal class StalkerCatalogSyncExecutor(requiredHiddenLiveCategoryIds: Set<Long>,onProgress: ((String) -> Unit)?,afterCatalogApply: suspend () -> Unit = {},- maxChannels: Int? = null- ): StagedStalkerLiveCatalogResult {+ maxChannels: Int? = null,+ retryPendingCategoriesOnly: Boolean = false+ ): StagedStalkerLiveCatalogResult = coroutineScope {val warnings = mutableListOf<String>()var categoriesErrorMessage: String? = null- val preferredCategories = when (val categoriesResult = api.getLiveCategories()) {- is Result.Success -> categoriesResult.data- .map { it.toEntity(provider.id) }- .filterNot { it.categoryId in hiddenLiveCategoryIds && it.categoryId !in requiredHiddenLiveCategoryIds }- is Result.Error -> {- Log.w(- STALKER_EXECUTOR_TAG,- "Stalker live categories failed for provider ${provider.id}; streaming bulk live channels with fallback categories: ${categoriesResult.message}",- categoriesResult.exception+ data class CategoryContextLoad(+ val categories: List<CategoryEntity>?,+ val errorMessage: String? = null+ )+ suspend fun loadPreferredCategories(): CategoryContextLoad {+ val categoriesResult = stalkerRequestCoordinator.execute(+ providerId = provider.id,+ priority = StalkerRequestPriority.OPEN_CATEGORY,+ descriptor = StalkerRequestDescriptor(+ contentType = ContentType.LIVE.name,+ action = "GET_CATEGORIES")- warnings += "Live categories failed; recovered using bulk live channels."- categoriesErrorMessage = categoriesResult.message- null+ ) { api.getLiveCategories() }+ if (categoriesResult is Result.Error) {+ stalkerRequestCoordinator.recordFailure(provider.id, categoriesResult.exception)+ }+ return when (categoriesResult) {+ is Result.Success -> CategoryContextLoad(+ categoriesResult.data+ .map { it.toEntity(provider.id) }+ .filterNot { it.categoryId in hiddenLiveCategoryIds && it.categoryId !in requiredHiddenLiveCategoryIds }+ )+ is Result.Error -> {+ Log.w(+ STALKER_EXECUTOR_TAG,+ "Stalker live categories failed for provider ${provider.id}; streaming bulk live channels with fallback categories: ${categoriesResult.message}",+ categoriesResult.exception+ )+ CategoryContextLoad(categories = null, errorMessage = categoriesResult.message)+ }+ is Result.Loading -> throw IllegalStateException("Unexpected loading state")}- is Result.Loading -> throw IllegalStateException("Unexpected loading state")}+ var preferredCategories: List<CategoryEntity>? = null+ var categoryContextApplied = false+ val categoryContextDeferred = async(start = kotlinx.coroutines.CoroutineStart.UNDISPATCHED) {+ loadPreferredCategories()+ }+ suspend fun awaitCategoryContext(): List<CategoryEntity>? {+ val loaded = categoryContextDeferred.await()+ if (!categoryContextApplied) {+ categoryContextApplied = true+ preferredCategories = loaded.categories+ categoriesErrorMessage = loaded.errorMessage+ if (loaded.errorMessage != null) {+ warnings += "Live categories failed; recovered using bulk live channels."+ }+ }+ return preferredCategories+ }+ val runtimeProfile = CatalogSyncRuntimeProfile.from(applicationContext)progress(provider.id, onProgress, "Loading live channels...")- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.LIVE)+ var fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.LIVE)val seenStreamIds = HashSet<Long>()- val batch = ArrayList<Channel>(FALLBACK_STAGE_BATCH_SIZE)+ val batch = ArrayList<Channel>(runtimeProfile.stageBatchSize)var stagedSessionId: Long? = nullvar acceptedCount = 0var bulkRowsWithResolvedCategories = 0@@ -465,14 +523,45 @@ internal class StalkerCatalogSyncExecutor(items = batch,seenStreamIds = seenStreamIds,fallbackCollector = fallbackCollector,- sessionId = stagedSessionId+ sessionId = stagedSessionId,+ useLiveAdmissionCount = true)stagedSessionId = staged.sessionIdacceptedCount += staged.acceptedCountbatch.clear()}- suspend fun finalizeStagedImport(): StagedStalkerLiveCatalogResult {+ suspend fun deleteRetryCategoryIds(categoryIds: Collection<Long>) {+ categoryIds.distinct().chunked(400).forEach { ids ->+ if (ids.isNotEmpty()) liveCategoryRetryDao.deleteCategories(provider.id, ids)+ }+ }++ suspend fun finalizeStagedImport(+ completeCategoryIds: Set<Long>? = null,+ pruneCategories: Boolean = true,+ coverageComplete: Boolean = false,+ failedCategoryScopes: List<StalkerLiveCategoryFailure> = emptyList(),+ retryOnlyPendingCategories: Boolean = false+ ): StagedStalkerLiveCatalogResult {+ val hasCompletedScopes = !completeCategoryIds.isNullOrEmpty()+ val sessionId = stagedSessionId ?: if (hasCompletedScopes) {+ syncCatalogStore.newSessionId()+ } else null+ suspend fun recordFailures() {+ if (maxChannels != null) return+ val attemptedAt = System.currentTimeMillis()+ failedCategoryScopes.forEach { failure ->+ liveCategoryRetryDao.recordFailure(+ providerId = provider.id,+ categoryId = failure.categoryId,+ categoryName = failure.categoryName.take(250),+ configurationGeneration = provider.stalkerConfigurationGeneration,+ attemptedAt = attemptedAt,+ errorMessage = failure.errorMessage?.take(1_000)+ )+ }+ }stagedSessionId?.let { sessionId ->if (hiddenLiveCategoryIds.isNotEmpty()) {mergeHiddenChannelsIntoStaging(provider.id, sessionId, hiddenLiveCategoryIds)@@ -488,24 +577,137 @@ internal class StalkerCatalogSyncExecutor(fallbackCollector.entities().takeIf { it.isNotEmpty() }).orEmpty() + hiddenCategories).distinctBy { it.categoryId to it.type }.takeIf { it.isNotEmpty() }- val sessionId = stagedSessionId- if (acceptedCount == 0 || sessionId == null) {+ if ((acceptedCount == 0 && !hasCompletedScopes) || sessionId == null) {sessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }+ recordFailures()return StagedStalkerLiveCatalogResult(acceptedCount = 0,+ catalogApplied = false,+ coverageComplete = false,warnings = (warnings + "Live TV returned no usable channels; keeping the last verified Live catalog.").distinct())}- syncCatalogStore.applyStagedLiveCatalog(provider.id, sessionId, categories, afterCatalogApply)- return StagedStalkerLiveCatalogResult(acceptedCount, warnings)+ suspend fun updateRetryQueue() {+ afterCatalogApply()+ if (maxChannels != null) return+ if (completeCategoryIds == null) {+ liveCategoryRetryDao.deleteForProvider(provider.id)+ } else {+ recordFailures()+ if (completeCategoryIds.isNotEmpty()) {+ deleteRetryCategoryIds(completeCategoryIds)+ }+ }+ }+ when {+ completeCategoryIds != null -> syncCatalogStore.applyStagedLiveCatalogWithCoverage(+ provider.id,+ sessionId,+ categories,+ completeCategoryIds,+ pruneCategories,+ ::updateRetryQueue+ )+ maxChannels != null -> syncCatalogStore.applyStagedLiveCatalogUpsertOnly(+ provider.id, sessionId, categories, afterCatalogApply+ )+ else -> syncCatalogStore.applyStagedLiveCatalog(+ provider.id,+ sessionId,+ categories+ ) {+ updateRetryQueue()+ }+ }+ val pendingRetries = if (maxChannels == null) {+ liveCategoryRetryDao.getForProvider(provider.id, provider.stalkerConfigurationGeneration)+ } else emptyList()+ val resolvedCoverage = when {+ maxChannels != null -> false+ completeCategoryIds == null -> coverageComplete && pendingRetries.isEmpty()+ retryOnlyPendingCategories -> pendingRetries.isEmpty()+ else -> coverageComplete && pendingRetries.isEmpty()+ }+ return StagedStalkerLiveCatalogResult(+ acceptedCount = acceptedCount,+ warnings = warnings,+ catalogApplied = true,+ coverageComplete = resolvedCoverage+ )}try {+ if (maxChannels == null) {+ liveCategoryRetryDao.deleteForOtherConfigurations(+ provider.id,+ provider.stalkerConfigurationGeneration+ )+ }+ if (retryPendingCategoriesOnly && maxChannels == null) {+ val pendingRetries = liveCategoryRetryDao.getForProvider(+ provider.id,+ provider.stalkerConfigurationGeneration+ )+ if (pendingRetries.isNotEmpty()) {+ val currentCategories = awaitCategoryContext().orEmpty()+ val availableIds = currentCategories.mapTo(HashSet()) { it.categoryId }+ val obsoleteIds = pendingRetries.asSequence()+ .map { it.categoryId }+ .filterNot(availableIds::contains)+ .distinct()+ .toList()+ if (obsoleteIds.isNotEmpty()) {+ deleteRetryCategoryIds(obsoleteIds)+ }+ val pendingIds = pendingRetries.asSequence()+ .map { it.categoryId }+ .filter(availableIds::contains)+ .toSet()+ val retryCategories = currentCategories.filter { it.categoryId in pendingIds }+ if (retryCategories.isNotEmpty()) {+ progress(+ provider.id,+ onProgress,+ "Retrying ${retryCategories.size} failed Live TV categories..."+ )+ val retryResult = fetchStalkerLiveChannelsByCategory(+ provider,+ api,+ retryCategories.map {+ XtreamCategory(it.categoryId.toString(), it.name, isAdult = it.isAdult)+ },+ onProgress,+ runtimeProfile = CatalogSyncRuntimeProfile.from(applicationContext),+ maxChannels = null,+ hiddenCategoryIds = hiddenLiveCategoryIds,+ requiredHiddenCategoryIds = requiredHiddenLiveCategoryIds+ )+ warnings += retryResult.warnings+ stagedSessionId = retryResult.sessionId+ acceptedCount = retryResult.acceptedCount+ retryResult.fallbackCategories.forEach { category ->+ fallbackCollector.record(category.categoryId, category.name, category.isAdult)+ }+ return@coroutineScope finalizeStagedImport(+ completeCategoryIds = retryResult.completeCategoryIds,+ pruneCategories = false,+ coverageComplete = retryResult.coverageComplete,+ failedCategoryScopes = retryResult.failedCategoryScopes,+ retryOnlyPendingCategories = true+ )+ }+ }+ }var bulkFailure: Exception? = nullval learnedState = api.validatedPortalState()val bulkUnsupportedVerdictFresh = learnedState?.bulkLiveSupported == false &&learnedState.validatedAt > 0L &&System.currentTimeMillis() - learnedState.validatedAt <= STALKER_BULK_LIVE_UNSUPPORTED_TTL_MILLIS+ val bulkRouteKnownToBeCategoryOnly = bulkUnsupportedVerdictFresh ||+ learnedState?.bulkLiveCategoryFidelity == false+ val mayOverlapMetadata = stalkerRequestCoordinator.effectiveConcurrencyLimit(provider.id) > 1 &&+ !bulkRouteKnownToBeCategoryOnly+ if (!mayOverlapMetadata) awaitCategoryContext()val shouldTryBulk = (!bulkUnsupportedVerdictFresh && learnedState?.bulkLiveCategoryFidelity != false) ||preferredCategories.isNullOrEmpty()StalkerTelemetry.strategySelected(@@ -520,24 +722,66 @@ internal class StalkerCatalogSyncExecutor(})val streamResult = if (shouldTryBulk) {- withBulkLiveStallTimeout { markBulkProgress ->- api.streamLiveStreams(maxChannels = maxChannels) { channel ->- markBulkProgress()- if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds && channel.categoryId !in requiredHiddenLiveCategoryIds) return@streamLiveStreams- if (channel.categoryId != null) bulkRowsWithResolvedCategories++- if (maxChannels == null || acceptedCount + batch.size < maxChannels) batch += channel- if (batch.size >= FALLBACK_STAGE_BATCH_SIZE) {- flushBatch()- progress(provider.id, onProgress, "Loading live channels... $acceptedCount imported")+ var attemptNumber = 0+ stalkerRequestCoordinator.execute(+ providerId = provider.id,+ priority = StalkerRequestPriority.OPEN_CATEGORY,+ descriptor = StalkerRequestDescriptor(+ contentType = ContentType.LIVE.name,+ action = "STREAM_ALL"+ )+ ) {+ withBulkLiveStallTimeout { markBulkProgress, localWork ->+ api.streamLiveStreams(+ maxChannels = maxChannels,+ batchRows = runtimeProfile.stageBatchSize,+ batchBytes = runtimeProfile.liveBatchBytes,+ onAttemptStart = {+ stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }+ stagedSessionId = null+ acceptedCount = 0+ bulkRowsWithResolvedCategories = 0+ batch.clear()+ seenStreamIds.clear()+ fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.LIVE)+ if (attemptNumber++ > 0) {+ awaitCategoryContext()+ val reloaded = loadPreferredCategories()+ preferredCategories = reloaded.categories+ categoriesErrorMessage = reloaded.errorMessage+ if (reloaded.errorMessage != null) {+ warnings += "Live categories failed; recovered using bulk live channels."+ }+ }+ markBulkProgress()+ },+ awaitCategoryContext = { awaitCategoryContext() },+ onReadProgress = markBulkProgress,+ onLocalWork = localWork+ ) { channel ->+ if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds && channel.categoryId !in requiredHiddenLiveCategoryIds) return@streamLiveStreams+ if (channel.categoryId != null) bulkRowsWithResolvedCategories+++ if (maxChannels == null || acceptedCount + batch.size < maxChannels) batch += channel+ if (batch.size >= runtimeProfile.stageBatchSize) {+ flushBatch()+ progress(provider.id, onProgress, "Loading live channels... $acceptedCount imported")+ }}}}} else null+ if (streamResult is Result.Error) {+ stalkerRequestCoordinator.recordFailure(provider.id, streamResult.exception)+ }+ awaitCategoryContext()when (streamResult) {is Result.Success -> {flushBatch()- api.recordBulkLiveCapability(true, acceptedCount == 0 || bulkRowsWithResolvedCategories > 0)- return finalizeStagedImport()+ if (maxChannels == null) api.recordBulkLiveCapability(true, acceptedCount == 0 || bulkRowsWithResolvedCategories > 0)+ return@coroutineScope finalizeStagedImport(+ completeCategoryIds = if (maxChannels != null) emptySet() else null,+ coverageComplete = maxChannels == null+ )}is Result.Error -> {if (isDefinitiveBulkLiveFailure(streamResult.exception)) api.recordBulkLiveCapability(false)@@ -562,9 +806,10 @@ internal class StalkerCatalogSyncExecutor(acceptedCount = 0batch.clear()seenStreamIds.clear()+ fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.LIVE)val fallbackCategories = preferredCategories.orEmpty()if (fallbackCategories.isEmpty()) {- return StagedStalkerLiveCatalogResult(+ return@coroutineScope StagedStalkerLiveCatalogResult(acceptedCount = 0,warnings = (warnings + listOfNotNull("Live TV provider exposed no live channels; continuing with VOD and series only.",@@ -579,24 +824,34 @@ internal class StalkerCatalogSyncExecutor(provider,api,fallbackCategories.map { XtreamCategory(it.categoryId.toString(), it.name, isAdult = it.isAdult) },- onProgress+ onProgress,+ runtimeProfile,+ maxChannels,+ hiddenLiveCategoryIds,+ requiredHiddenLiveCategoryIds)warnings += fallbackResult.warnings- fallbackResult.channels- .take(maxChannels ?: Int.MAX_VALUE)- .forEach { channel ->- if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds && channel.categoryId !in requiredHiddenLiveCategoryIds) return@forEach- batch += channel- if (batch.size >= FALLBACK_STAGE_BATCH_SIZE) flushBatch()- }- flushBatch()- return finalizeStagedImport()+ stagedSessionId = fallbackResult.sessionId+ acceptedCount = fallbackResult.acceptedCount+ fallbackResult.fallbackCategories.forEach { category ->+ fallbackCollector.record(category.categoryId, category.name, category.isAdult)+ }+ return@coroutineScope finalizeStagedImport(+ completeCategoryIds = fallbackResult.completeCategoryIds,+ pruneCategories = categoriesErrorMessage == null,+ coverageComplete = fallbackResult.coverageComplete,+ failedCategoryScopes = fallbackResult.failedCategoryScopes+ )} catch (error: CancellationException) {- stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }+ withContext(NonCancellable) {+ stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }+ }throw error} catch (error: Exception) {stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }throw error+ } finally {+ categoryContextDeferred.cancelAndJoin()}}@@ -614,80 +869,292 @@ internal class StalkerCatalogSyncExecutor(provider: Provider,api: StalkerProvider,categories: List<XtreamCategory>,- onProgress: ((String) -> Unit)?+ onProgress: ((String) -> Unit)?,+ runtimeProfile: CatalogSyncRuntimeProfile,+ maxChannels: Int?,+ hiddenCategoryIds: Set<Long>,+ requiredHiddenCategoryIds: Set<Long>): StalkerLiveCategoryLoadResult {- if (categories.isEmpty()) return StalkerLiveCategoryLoadResult(emptyList())- val runtimeProfile = CatalogSyncRuntimeProfile.from(applicationContext)- val concurrency = minOf(categories.size, runtimeProfile.maxCategoryConcurrency, STALKER_MAX_PARALLEL_CATEGORY_FETCHES).coerceAtLeast(1)- val executionPlan = categoryRecoverySupport.executeCategoryRecoveryPlan(- provider = provider,- categories = categories,- initialConcurrency = concurrency,- sectionLabel = "Live TV",- sequentialModeWarning = LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING,- onProgress = onProgress,- fetch = { category -> fetchStalkerLiveCategoryOutcome(api, category) }+ if (categories.isEmpty()) return StalkerLiveCategoryLoadResult()++ data class CategoryAttemptStage(+ var sessionId: Long,+ val seenStreamIds: MutableSet<Long> = HashSet(),+ val bootstrapCandidateIds: MutableSet<Long> = HashSet(),+ var fallbackCategories: FallbackCategoryCollector,+ var stagedRows: Boolean = false,+ var capReached: Boolean = false)- var timedOutcomes = executionPlan.outcomes- val categoryOutcomes = timedOutcomes.map { it.outcome }- val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }- val fastFailureCount = timedOutcomes.count { it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure }- val downgradeRecommended = catalogStrategySupport.shouldDowngradeCategorySync(categories.size, failureCount, fastFailureCount, categoryOutcomes)- var warnings = executionPlan.warnings.toMutableList()- if (concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(- categories.size,- failureCount,- downgradeRecommended,- categoryOutcomes- )- ) {- val failedRetryTotal = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }- progress(provider.id, onProgress, "Retrying failed Live TV categories 0/$failedRetryTotal...")- timedOutcomes = categoryRecoverySupport.continueFailedCategoryOutcomes(- provider,- timedOutcomes,- fetchSequentially = { category -> fetchStalkerLiveCategoryOutcome(api, category) },- onCategoryRetried = { completed, total, _ ->- progress(provider.id, onProgress, "Retrying failed Live TV categories $completed/$total...")- }++ val activeSessions = ConcurrentHashMap.newKeySet<Long>()+ val completedStages = ConcurrentHashMap<String, CategoryAttemptStage>()+ val capReachedCategoryIds = ConcurrentHashMap.newKeySet<String>()+ val bootstrapSeenIds = HashSet<Long>()+ var stagedSessionId: Long? = null+ var stagedAcceptedCount = 0+ var keepTargetStage = false+ val fallbackCategories = FallbackCategoryCollector(provider.id, ContentType.LIVE)++ fun newStage(): CategoryAttemptStage {+ val sessionId = syncCatalogStore.newSessionId()+ activeSessions += sessionId+ return CategoryAttemptStage(+ sessionId = sessionId,+ fallbackCategories = FallbackCategoryCollector(provider.id, ContentType.LIVE))- if (downgradeRecommended) warnings += LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING}- val finalOutcomes = timedOutcomes.map { it.outcome }- val channels = finalOutcomes.filterIsInstance<CategoryFetchOutcome.Success<Channel>>()- .flatMap { it.items }.distinctBy { it.streamId }- val outcomeWarnings = finalOutcomes.filterIsInstance<CategoryFetchOutcome.Failure>()- .map { categoryFailureWarning("Live TV", it.categoryName, it.error) }- return StalkerLiveCategoryLoadResult(channels, (outcomeWarnings + warnings).distinct())- }- private suspend fun fetchStalkerLiveCategoryOutcome(- api: StalkerProvider,- category: XtreamCategory- ): TimedCategoryOutcome<Channel> {- val startedAt = System.currentTimeMillis()- val outcome = try {+ suspend fun discardStage(stage: CategoryAttemptStage) {+ syncCatalogStore.discardStagedImport(provider.id, stage.sessionId)+ activeSessions.remove(stage.sessionId)+ }++ suspend fun fetchAndStage(category: XtreamCategory): TimedCategoryOutcome<Channel> {+ val startedAt = System.currentTimeMillis()val categoryId = category.categoryId.toLongOrNull()- ?: throw IllegalArgumentException("Invalid Stalker live category id '${category.categoryId}'")- val channels = requireResult(api.getLiveStreams(categoryId), "Failed to load live channels for ${category.categoryName}")- .distinctBy { it.streamId }- if (channels.isEmpty()) CategoryFetchOutcome.Empty(category.categoryName)- else CategoryFetchOutcome.Success(category.categoryName, channels, channels.size)- } catch (error: CancellationException) {- throw error- } catch (error: Throwable) {- CategoryFetchOutcome.Failure(category.categoryName, error)+ var attempt = newStage()+ var outcome: CategoryFetchOutcome<Channel>+ try {+ if (categoryId == null) throw IllegalArgumentException(+ "Invalid Stalker live category id '${category.categoryId}'"+ )+ val result = stalkerRequestCoordinator.execute(+ providerId = provider.id,+ priority = StalkerRequestPriority.OPEN_CATEGORY,+ descriptor = StalkerRequestDescriptor(+ contentType = ContentType.LIVE.name,+ action = "STREAM_CATEGORY",+ categoryKey = category.categoryId+ )+ ) {+ api.streamLiveCategory(+ categoryId = categoryId,+ batchRows = runtimeProfile.stageBatchSize,+ batchBytes = runtimeProfile.liveBatchBytes,+ onAttemptStart = {+ discardStage(attempt)+ attempt = newStage()+ }+ ) { rows ->+ val visibleRows = rows.filterNot { channel ->+ channel.categoryId != null &&+ channel.categoryId in hiddenCategoryIds &&+ channel.categoryId !in requiredHiddenCategoryIds+ }+ val stageRows = if (maxChannels == null) {+ visibleRows+ } else {+ val remaining = (maxChannels - stagedAcceptedCount).coerceAtLeast(0)+ val candidates = ArrayList<Channel>(minOf(visibleRows.size, remaining))+ visibleRows.forEach { channel ->+ val id = channel.streamId.takeIf { it > 0L } ?: channel.id+ if (id <= 0L || id in bootstrapSeenIds || id in attempt.bootstrapCandidateIds) {+ return@forEach+ }+ if (attempt.bootstrapCandidateIds.size >= remaining) {+ attempt.capReached = true+ } else {+ attempt.bootstrapCandidateIds += id+ candidates += channel+ }+ }+ candidates+ }+ if (stageRows.isNotEmpty()) {+ attempt.stagedRows = true+ catalogStager.stageChannelItems(+ providerId = provider.id,+ items = stageRows,+ seenStreamIds = attempt.seenStreamIds,+ fallbackCollector = attempt.fallbackCategories,+ sessionId = attempt.sessionId,+ useLiveAdmissionCount = true+ )+ }+ }+ }+ when (result) {+ is Result.Success -> {+ outcome = if (attempt.seenStreamIds.isEmpty()) {+ CategoryFetchOutcome.Empty(category.categoryName)+ } else {+ CategoryFetchOutcome.Success(category.categoryName, emptyList(), attempt.seenStreamIds.size)+ }+ completedStages[category.categoryId] = attempt+ }+ is Result.Error -> {+ stalkerRequestCoordinator.recordFailure(provider.id, result.exception)+ throw IllegalStateException(result.message, result.exception)+ }+ is Result.Loading -> throw IllegalStateException("Unexpected loading state")+ }+ } catch (error: CancellationException) {+ discardStage(attempt)+ throw error+ } catch (error: Throwable) {+ discardStage(attempt)+ completedStages.remove(category.categoryId)+ outcome = CategoryFetchOutcome.Failure(category.categoryName, error)+ }+ return TimedCategoryOutcome(category, outcome, System.currentTimeMillis() - startedAt)+ }++ suspend fun mergeCategoryStage(category: XtreamCategory): Boolean {+ val attempt = completedStages.remove(category.categoryId) ?: return false+ if (attempt.capReached) capReachedCategoryIds += category.categoryId+ if (attempt.stagedRows) {+ val target = stagedSessionId ?: syncCatalogStore.newSessionId().also { stagedSessionId = it }+ val moved = syncCatalogStore.mergeCompletedLiveCategory(provider.id, attempt.sessionId, target)+ stagedAcceptedCount += moved+ if (maxChannels != null) bootstrapSeenIds += attempt.bootstrapCandidateIds+ } else if (maxChannels == null) {+ // A verified empty category still needs a target session so its stale rows can+ // be pruned transactionally during scope promotion.+ if (stagedSessionId == null) stagedSessionId = syncCatalogStore.newSessionId()+ }+ attempt.fallbackCategories.entities().forEach {+ fallbackCategories.record(it.categoryId, it.name, it.isAdult)+ }+ discardStage(attempt)+ return true+ }++ suspend fun mergeCompletedInProviderOrder(outcomes: List<TimedCategoryOutcome<Channel>>) {+ val successfulIds = outcomes.asSequence()+ .filter { it.outcome !is CategoryFetchOutcome.Failure }+ .map { it.category.categoryId }+ .toSet()+ categories.forEach { category ->+ if (category.categoryId in successfulIds) mergeCategoryStage(category)+ }+ }++ var finalOutcomes = emptyList<TimedCategoryOutcome<Channel>>()+ val warnings = mutableListOf<String>()+ try {+ val concurrency = if (maxChannels != null) 1 else minOf(+ categories.size,+ runtimeProfile.maxCategoryConcurrency,+ STALKER_MAX_PARALLEL_CATEGORY_FETCHES+ ).coerceAtLeast(1)+ if (maxChannels != null) {+ // Bootstrap is a deterministic prefix: finish one category, merge it, then+ // stop before requesting later categories as soon as the cap is reached.+ val attempted = mutableListOf<TimedCategoryOutcome<Channel>>()+ for ((index, category) in categories.withIndex()) {+ if (stagedAcceptedCount >= maxChannels) break+ progress(provider.id, onProgress, "Downloading Live TV by category ${index + 1}/${categories.size}...")+ val outcome = fetchAndStage(category)+ attempted += outcome+ if (outcome.outcome !is CategoryFetchOutcome.Failure) mergeCategoryStage(category)+ if (category.categoryId in capReachedCategoryIds) break+ }+ finalOutcomes = attempted+ } else {+ val executionPlan = categoryRecoverySupport.executeCategoryRecoveryPlan(+ provider = provider,+ categories = categories,+ initialConcurrency = concurrency,+ sectionLabel = "Live TV",+ sequentialModeWarning = LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING,+ onProgress = onProgress,+ fetch = ::fetchAndStage,+ refillWorkers = true,+ shouldStopOnFailure = ::isPortalWideStalkerCategoryFailure+ )+ var timedOutcomes = executionPlan.outcomes+ val categoryOutcomes = timedOutcomes.map { it.outcome }+ val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }+ val fastFailureCount = timedOutcomes.count {+ it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure+ }+ val downgradeRecommended = catalogStrategySupport.shouldDowngradeCategorySync(+ categories.size, failureCount, fastFailureCount, categoryOutcomes+ )+ warnings += executionPlan.warnings+ val hasPortalWideFailure = categoryOutcomes.filterIsInstance<CategoryFetchOutcome.Failure>()+ .any { isPortalWideStalkerCategoryFailure(it.error) }+ if (executionPlan.stopReason == null && !hasPortalWideFailure && concurrency > 1 &&+ catalogStrategySupport.shouldRetryFailedCategories(+ categories.size, failureCount, downgradeRecommended, categoryOutcomes+ )+ ) {+ val failedRetryTotal = failureCount+ progress(provider.id, onProgress, "Retrying failed Live TV categories 0/$failedRetryTotal...")+ timedOutcomes = categoryRecoverySupport.continueFailedCategoryOutcomes(+ provider,+ timedOutcomes,+ fetchSequentially = ::fetchAndStage,+ onCategoryRetried = { completed, total, _ ->+ progress(provider.id, onProgress, "Retrying failed Live TV categories $completed/$total...")+ }+ )+ if (downgradeRecommended) warnings += LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING+ }+ finalOutcomes = timedOutcomes+ mergeCompletedInProviderOrder(finalOutcomes)+ }++ val finalCategoryOutcomes = finalOutcomes.map { it.outcome }+ val outcomeWarnings = finalCategoryOutcomes.filterIsInstance<CategoryFetchOutcome.Failure>()+ .map { categoryFailureWarning("Live TV", it.categoryName, it.error) }+ val failedCategoryScopes = finalOutcomes.mapNotNull { timedOutcome ->+ val failure = timedOutcome.outcome as? CategoryFetchOutcome.Failure ?: return@mapNotNull null+ val categoryId = timedOutcome.category.categoryId.toLongOrNull() ?: return@mapNotNull null+ if (isPortalWideStalkerCategoryFailure(failure.error)) return@mapNotNull null+ StalkerLiveCategoryFailure(+ categoryId = categoryId,+ categoryName = timedOutcome.category.categoryName,+ errorMessage = sanitizeThrowableMessage(failure.error).takeIf(String::isNotBlank)+ )+ }+ val completeCategoryIds = finalOutcomes.asSequence()+ .filter { it.outcome !is CategoryFetchOutcome.Failure }+ .filterNot { it.category.categoryId in capReachedCategoryIds }+ .mapNotNull { it.category.categoryId.toLongOrNull() }+ .toSet()+ keepTargetStage = true+ return StalkerLiveCategoryLoadResult(+ sessionId = stagedSessionId,+ acceptedCount = stagedAcceptedCount,+ fallbackCategories = fallbackCategories.entities(),+ completeCategoryIds = completeCategoryIds,+ failedCategoryScopes = failedCategoryScopes,+ coverageComplete = maxChannels == null &&+ finalOutcomes.size == categories.size &&+ finalOutcomes.all { it.outcome !is CategoryFetchOutcome.Failure },+ warnings = (outcomeWarnings + warnings).distinct()+ )+ } finally {+ withContext(NonCancellable) {+ activeSessions.toList().forEach { sessionId ->+ syncCatalogStore.discardStagedImport(provider.id, sessionId)+ }+ if (!keepTargetStage) {+ stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }+ }+ }}- return TimedCategoryOutcome(category, outcome, System.currentTimeMillis() - startedAt)}- private suspend fun <T> withBulkLiveStallTimeout(block: suspend (() -> Unit) -> T): T? = coroutineScope {+ private suspend fun <T> withBulkLiveStallTimeout(block: suspend (() -> Unit, (Boolean) -> Unit) -> T): T? = coroutineScope {val lastProgressAt = AtomicLong(System.currentTimeMillis())- val streamDeferred = async { block { lastProgressAt.set(System.currentTimeMillis()) } }+ val localWorkCount = AtomicInteger()+ val streamDeferred = async {+ block(+ { lastProgressAt.set(System.currentTimeMillis()) },+ { started ->+ if (started) localWorkCount.incrementAndGet() else {+ lastProgressAt.set(System.currentTimeMillis())+ localWorkCount.decrementAndGet()+ }+ }+ )+ }val watchdog = launch {while (isActive) {delay(STALKER_BULK_LIVE_STALL_CHECK_INTERVAL_MILLIS)- if (System.currentTimeMillis() - lastProgressAt.get() >= STALKER_BULK_LIVE_STALL_TIMEOUT_MILLIS) {+ if (localWorkCount.get() == 0 && System.currentTimeMillis() - lastProgressAt.get() >= STALKER_BULK_LIVE_STALL_TIMEOUT_MILLIS) {streamDeferred.cancel()break}@@ -717,6 +1184,17 @@ internal class StalkerCatalogSyncExecutor(else -> false}+ private fun isPortalWideStalkerCategoryFailure(error: Throwable): Boolean =+ generateSequence(error) { it.cause }.any { cause ->+ cause is StalkerApiError.Authorization ||+ cause is StalkerApiError.ModelRejected ||+ cause is StalkerApiError.AccountBlocked ||+ cause is StalkerApiError.BlockedOrConfiguration ||+ cause is StalkerApiError.RateLimited ||+ cause is StalkerApiError.TransportConsentRequired ||+ (cause is StalkerApiError.Server && cause.httpStatus in setOf(401, 403))+ }+private suspend fun stalkerCatalogAccessDiagnostic(api: StalkerProvider,primaryMessage: String,@@ -749,12 +1227,25 @@ internal class StalkerCatalogSyncExecutor(}private data class StalkerLiveCategoryLoadResult(- val channels: List<Channel>,+ val sessionId: Long? = null,+ val acceptedCount: Int = 0,+ val fallbackCategories: List<CategoryEntity> = emptyList(),+ val completeCategoryIds: Set<Long> = emptySet(),+ val failedCategoryScopes: List<StalkerLiveCategoryFailure> = emptyList(),+ val coverageComplete: Boolean = false,val warnings: List<String> = emptyList())+ private data class StalkerLiveCategoryFailure(+ val categoryId: Long,+ val categoryName: String,+ val errorMessage: String?+ )+private data class StagedStalkerLiveCatalogResult(val acceptedCount: Int,+ val catalogApplied: Boolean = false,+ val coverageComplete: Boolean = false,val warnings: List<String> = emptyList())}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.ktindex 4dd9f6c2..a42d5624 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt@@ -42,6 +42,7 @@ internal class SyncCatalogStore(companion object {private const val TAG = "SyncCatalogStore"private const val STAGE_BATCH_SIZE = 500+ private const val CATEGORY_SCOPE_QUERY_CHUNK_SIZE = 400private val TEXT_WHITESPACE = Regex("\\s+")private const val HEX_DIGITS = "0123456789abcdef"}@@ -173,6 +174,35 @@ internal class SyncCatalogStore(}}+ /** Promotes completed category scopes while retaining channels from failed/unvisited scopes. */+ suspend fun applyStagedLiveCatalogWithCoverage(+ providerId: Long,+ sessionId: Long,+ categories: List<CategoryEntity>?,+ completeCategoryIds: Set<Long>,+ pruneCategories: Boolean,+ afterCatalogApply: suspend () -> Unit = {}+ ) {+ try {+ providerTransaction(providerId) {+ categories?.let { stageCategories(providerId, sessionId, it) }+ categories?.let {+ applyCategories(providerId, sessionId, ContentType.LIVE.name, pruneStale = pruneCategories)+ }+ catalogSyncDao.updateChangedChannelsFromStage(providerId, sessionId)+ catalogSyncDao.insertMissingChannelsFromStage(providerId, sessionId)+ completeCategoryIds.chunked(CATEGORY_SCOPE_QUERY_CHUNK_SIZE).forEach { ids ->+ if (ids.isNotEmpty()) {+ catalogSyncDao.deleteStaleChannelsForStageInCategories(providerId, sessionId, ids)+ }+ }+ afterCatalogApply()+ }+ } finally {+ clearSession(providerId, sessionId)+ }+ }+suspend fun applyStagedMovieCatalog(providerId: Long,sessionId: Long,diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 1c135ad7..ba9bbae7 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -15,6 +15,7 @@ import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.ProviderWorkflowDaoimport com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.StalkerLiveCategoryRetryDaoimport com.streamvault.data.local.dao.TmdbIdentityDaoimport com.streamvault.data.local.dao.VodCategoryHydrationDaoimport com.streamvault.data.local.dao.VodCatalogEntryDao@@ -194,6 +195,7 @@ class SyncManager @Inject constructor(private val tmdbIdentityDao: TmdbIdentityDao,private val xtreamContentIndexDao: XtreamContentIndexDao,private val xtreamIndexJobDao: XtreamIndexJobDao,+ private val stalkerLiveCategoryRetryDao: StalkerLiveCategoryRetryDao,private val stalkerIndexJobStore: StalkerIndexJobStore,private val xtreamLiveOnboardingDao: XtreamLiveOnboardingDao,private val episodeDao: EpisodeDao,@@ -626,6 +628,8 @@ class SyncManager @Inject constructor(categoryRecoverySupport = xtreamSupport,sectionExecutor = stalkerCatalogSectionExecutor,readinessTracker = stalkerReadinessTracker,+ stalkerRequestCoordinator = stalkerRequestCoordinator,+ liveCategoryRetryDao = stalkerLiveCategoryRetryDao,createProvider = ::createStalkerSyncProvider,syncProviderEpg = providerEpgExecutor::syncStalkerProviderEpg,progress = ::progress,@@ -1698,62 +1702,25 @@ class SyncManager @Inject constructor(if (page != 1 || recovered !is Result.Success || recovered.data.items.isNotEmpty()) {return recovered}- val fallback = fetchStalkerSummaryFirstPageFallback(api, contentType, categoryId)- return if (fallback is Result.Success && fallback.data.items.isNotEmpty()) {- Log.i(- TAG,- "Recovered empty paged Stalker ${contentType.name} first page with non-paged fallback for category $categoryId"- )- fallback- } else if (fallback is Result.Error && fallback.exception is StalkerApiError.CatalogTruncated) {- val truncation = fallback.exception as StalkerApiError.CatalogTruncated- Result.success(- com.streamvault.data.remote.stalker.StalkerPagedResult(- items = emptyList(),- page = 1,- totalPages = truncation.pageLimit,- pageSize = 0,- hasAdvertisedTotal = true,- advertisedTotalPages = truncation.advertisedTotalPages,- isTruncated = true,- terminationReason = "page_limit"- )- )- } else {- recovered- }- }-- private suspend fun fetchStalkerSummaryFirstPageFallback(- api: StalkerProvider,- contentType: ContentType,- categoryId: Long- ): Result<com.streamvault.data.remote.stalker.StalkerPagedResult<out Any>> = when (contentType) {- ContentType.MOVIE -> when (val result = api.getVodStreams(categoryId)) {- is Result.Success -> Result.success(- com.streamvault.data.remote.stalker.StalkerPagedResult(- items = result.data,- page = 1,- totalPages = 1,- pageSize = result.data.size- )- )- is Result.Error -> Result.error(result.message, result.exception)- is Result.Loading -> Result.error("Unexpected loading state from Stalker movie first-page fallback")- }- ContentType.SERIES -> when (val result = api.getSeriesList(categoryId)) {- is Result.Success -> Result.success(- com.streamvault.data.remote.stalker.StalkerPagedResult(- items = result.data,- page = 1,- totalPages = 1,- pageSize = result.data.size- )- )- is Result.Error -> Result.error(result.message, result.exception)- is Result.Loading -> Result.error("Unexpected loading state from Stalker series first-page fallback")+ // Some portals return an empty first response transiently. Keep the historical+ // second-request recovery, but retry only this page: getVodStreams/getSeriesList+ // use the same ordered-list route and otherwise accumulate the whole category,+ // losing the real page and coverage receipt. getSeriesListPage retains its native+ // series -> VOD is_series compatibility fallback on each bounded attempt.+ val retry = fetch()+ return when (retry) {+ is Result.Success -> {+ if (retry.data.items.isNotEmpty()) {+ Log.i(+ TAG,+ "Recovered empty paged Stalker ${contentType.name} first page with a bounded page retry for category $categoryId"+ )+ }+ retry+ }+ is Result.Error -> retry+ is Result.Loading -> Result.error("Unexpected loading state from Stalker first-page retry")}- else -> Result.error("Unsupported Stalker summary first-page fallback section: $contentType")}private suspend fun fetchStalkerWildcardSummaryPageWithRecovery(diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.ktindex f9b69813..4f3df4db 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt@@ -41,13 +41,14 @@ internal class SyncManagerXtreamSupport(onProgress: ((String) -> Unit)?,fetch: suspend (XtreamCategory) -> TimedCategoryOutcome<T>,refillWorkers: Boolean = false,- onCategoryCompleted: ((completed: Int, total: Int, currentLabel: String) -> Unit)? = null+ onCategoryCompleted: ((completed: Int, total: Int, currentLabel: String) -> Unit)? = null,+ shouldStopOnFailure: (Throwable) -> Boolean = { false }): CategoryExecutionPlan<T> {if (categories.isEmpty()) {return CategoryExecutionPlan(emptyList())}if (refillWorkers) return executeRefilledCategoryPlan(provider, categories, initialConcurrency,- sectionLabel, sequentialModeWarning, onProgress, fetch, onCategoryCompleted)+ sectionLabel, sequentialModeWarning, onProgress, fetch, onCategoryCompleted, shouldStopOnFailure)val outcomes = mutableListOf<TimedCategoryOutcome<T>>()val warnings = mutableListOf<String>()@@ -55,6 +56,7 @@ internal class SyncManagerXtreamSupport(var forceSequential = initialConcurrency <= 1var consecutiveSequentialStressFailures = 0var stoppedEarly = false+ var stopReason: CategoryExecutionStopReason? = nullwhile (nextIndex < categories.size && !stoppedEarly) {val windowConcurrency = if (forceSequential) 1 else initialConcurrency@@ -75,6 +77,15 @@ internal class SyncManagerXtreamSupport(outcomes += windowOutcomesnextIndex += window.size+ if (windowOutcomes.any { timed ->+ val error = (timed.outcome as? CategoryFetchOutcome.Failure)?.error+ error != null && shouldStopOnFailure(error)+ }+ ) {+ stoppedEarly = true+ stopReason = CategoryExecutionStopReason.AUTHENTICATION+ }+val completed = outcomes.sizeprogress(provider.id, onProgress, "Downloading $sectionLabel by category $completed/${categories.size}...")// Hook d'emission optionnel (M1 — T4) : permet aux strategies d'emettre un@@ -83,7 +94,7 @@ internal class SyncManagerXtreamSupport(// concurrent, la fenetre est petite donc le label reste representatif).onCategoryCompleted?.invoke(completed, categories.size, window.last().categoryName)- if (!forceSequential && shouldRecoverRemainingCategoryRequests(categories.size, completed, outcomes.map { it.outcome })) {+ if (!stoppedEarly && !forceSequential && shouldRecoverRemainingCategoryRequests(categories.size, completed, outcomes.map { it.outcome })) {forceSequential = truewarnings += sequentialModeWarningLog.w(@@ -118,7 +129,7 @@ internal class SyncManagerXtreamSupport(return CategoryExecutionPlan(outcomes = outcomes,warnings = warnings.distinct(),- stopReason = if (stoppedEarly) CategoryExecutionStopReason.PROVIDER_STRESS else null+ stopReason = stopReason ?: if (stoppedEarly) CategoryExecutionStopReason.PROVIDER_STRESS else null)}@@ -130,7 +141,8 @@ internal class SyncManagerXtreamSupport(sequentialModeWarning: String,onProgress: ((String) -> Unit)?,fetch: suspend (XtreamCategory) -> TimedCategoryOutcome<T>,- onCategoryCompleted: ((Int, Int, String) -> Unit)?+ onCategoryCompleted: ((Int, Int, String) -> Unit)?,+ shouldStopOnFailure: (Throwable) -> Boolean): CategoryExecutionPlan<T> = coroutineScope {val limit = initialConcurrency.coerceIn(1, categories.size)val completed = Channel<Pair<Int, TimedCategoryOutcome<T>>>(limit)@@ -166,7 +178,9 @@ internal class SyncManagerXtreamSupport(val error = (outcome as? CategoryFetchOutcome.Failure)?.errorprogress(provider.id, onProgress, "Downloading $sectionLabel by category ${results.size}/${categories.size}...")onCategoryCompleted?.invoke(results.size, categories.size, result.second.category.categoryName)- if (error is XtreamAuthenticationException) stopReason = CategoryExecutionStopReason.AUTHENTICATION+ if (error is XtreamAuthenticationException || (error != null && shouldStopOnFailure(error))) {+ stopReason = CategoryExecutionStopReason.AUTHENTICATION+ }if (!sequential && shouldRecoverRemainingCategoryRequests(categories.size, results.size, results.map { it.second.outcome })) {sequential = truewarnings += sequentialModeWarningdiff --git a/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt b/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.ktindex a17370c7..d5b8131b 100644--- a/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt+++ b/data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt@@ -131,17 +131,12 @@ internal class VodCategoryHydrationCoordinator(hydration!!.lastError ?: "Portal repeated a catalog page")}- val category = categoryDao.getByProviderAndTypeSync(providerId, ContentType.VOD.name)- .firstOrNull { it.categoryId == categoryId }- val protected = category?.isUserProtected == trueval movies = page.items.mapNotNull { entry ->(entry.item as? VodCatalogItem.MovieItem)?.movie- ?.copy(isUserProtected = protected)?.toEntity()}val series = page.items.mapNotNull { entry ->(entry.item as? VodCatalogItem.SeriesItem)?.series- ?.copy(isUserProtected = protected)?.toEntity()}val entries = page.items.mapIndexed { rawIndex, entry ->@@ -174,8 +169,22 @@ internal class VodCategoryHydrationCoordinator(val terminationReason = page.terminationReason?: "page_limit".takeIf { pageLimitReached }transactionRunner.inTransaction {- movieDao.upsertCategoryPage(providerId, movies)- seriesDao.upsertCategoryPage(providerId, series)+ // Protection can be edited while the network request is in flight.+ // Read just this category at commit time so a long COMPLETE request+ // cannot apply a stale cached flag and the page/checkpoint stay atomic.+ val protected = categoryDao.getByProviderTypeAndCategoryId(+ providerId = providerId,+ type = ContentType.VOD.name,+ categoryId = categoryId+ )?.isUserProtected == true+ movieDao.upsertCategoryPage(+ providerId,+ movies.map { it.copy(isUserProtected = protected) }+ )+ seriesDao.upsertCategoryPage(+ providerId,+ series.map { it.copy(isUserProtected = protected) }+ )vodCatalogEntryDao.replacePage(providerId, categoryId, page.page, entries)val persistedCount = vodCatalogEntryDao.countByCategory(providerId, categoryId)hydration = VodCategoryHydrationEntity(diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerLivePipelineTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerLivePipelineTest.ktnew file mode 100644index 00000000..e7f3218c--- /dev/null+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerLivePipelineTest.kt@@ -0,0 +1,115 @@+package com.streamvault.data.remote.stalker++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Result+import java.util.concurrent.atomic.AtomicInteger+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.supervisorScope+import kotlinx.coroutines.test.runTest+import org.junit.Test++class StalkerLivePipelineTest {+ @Test fun fullQueueBackpressuresReaderAndDrainsInOrder() = runTest {+ val enteredWriter = CompletableDeferred<Unit>()+ val releaseWriter = CompletableDeferred<Unit>()+ val thirdSend = CompletableDeferred<Unit>()+ val emitted = AtomicInteger()+ val localWork = AtomicInteger()+ val rows = mutableListOf<String>()+ val task = async {+ runStalkerLivePipeline(1, 16_384L, { if (it) localWork.incrementAndGet() else localWork.decrementAndGet() },+ read = { emit ->+ repeat(4) { index ->+ if (index == 2) thirdSend.complete(Unit)+ emit(StalkerItemRecord(index.toString(), "Channel"))+ emitted.incrementAndGet()+ }+ Result.success(4)+ },+ consume = { batch ->+ if (batch.first().id == "0") { enteredWriter.complete(Unit); releaseWriter.await() }+ rows += batch.map { it.id }+ }+ )+ }+ enteredWriter.await()+ thirdSend.await()+ assertThat(emitted.get()).isEqualTo(2)+ releaseWriter.complete(Unit)+ assertThat(task.await()).isInstanceOf(Result.Success::class.java)+ assertThat(rows).containsExactly("0", "1", "2", "3").inOrder()+ assertThat(localWork.get()).isEqualTo(0)+ }++ @Test fun readerErrorJoinsWriterBeforeReturningFailedAttempt() = runTest {+ val enteredWriter = CompletableDeferred<Unit>()+ val stoppedWriter = CompletableDeferred<Unit>()+ val result = runStalkerLivePipeline(1, 16_384L, {},+ read = { emit ->+ emit(StalkerItemRecord("1", "Channel"))+ enteredWriter.await()+ Result.error("expired", StalkerApiError.SessionExpired("expired"))+ },+ consume = {+ enteredWriter.complete(Unit)+ try { awaitCancellation() } finally { stoppedWriter.complete(Unit) }+ }+ )+ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat(stoppedWriter.isCompleted).isTrue()+ }++ @Test fun cancellationWhileQueueIsFullStopsReaderAndWriter() = runTest {+ val enteredWriter = CompletableDeferred<Unit>()+ val thirdSend = CompletableDeferred<Unit>()+ val stoppedReader = CompletableDeferred<Unit>()+ val stoppedWriter = CompletableDeferred<Unit>()+ val task = async {+ runStalkerLivePipeline(1, 16_384L, {},+ read = { emit ->+ try {+ repeat(4) { index ->+ if (index == 2) thirdSend.complete(Unit)+ emit(StalkerItemRecord(index.toString(), "Channel"))+ }+ Result.success(4)+ } finally { stoppedReader.complete(Unit) }+ },+ consume = {+ enteredWriter.complete(Unit)+ try { awaitCancellation() } finally { stoppedWriter.complete(Unit) }+ }+ )+ }+ enteredWriter.await()+ thirdSend.await()+ task.cancelAndJoin()+ assertThat(stoppedReader.isCompleted).isTrue()+ assertThat(stoppedWriter.isCompleted).isTrue()+ }++ @Test fun writerFailureInterruptsReaderAndRejectsOversizedRows() = runTest {+ supervisorScope {+ val stoppedReader = CompletableDeferred<Unit>()+ val task = async {+ runStalkerLivePipeline(1, 16_384L, {},+ read = { emit ->+ try { emit(StalkerItemRecord("1", "Channel")); awaitCancellation() }+ finally { stoppedReader.complete(Unit) }+ }, consume = { error("disk failure") }+ )+ }+ assertThat(runCatching { task.await() }.exceptionOrNull()?.message).isEqualTo("disk failure")+ assertThat(stoppedReader.isCompleted).isTrue()+ }+ assertThat(runCatching {+ runStalkerLivePipeline(1, 1024L, {},+ read = { emit -> emit(StalkerItemRecord("1", "x".repeat(2048))); Result.success(1) },+ consume = { error("must not write") }+ )+ }.exceptionOrNull()).isInstanceOf(StalkerApiError.ResponseTooLarge::class.java)+ }+}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerLiveRowReaderTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerLiveRowReaderTest.ktnew file mode 100644index 00000000..ed68e647--- /dev/null+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerLiveRowReaderTest.kt@@ -0,0 +1,71 @@+package com.streamvault.data.remote.stalker++import com.google.common.truth.Truth.assertThat+import com.google.gson.Gson+import com.google.gson.stream.JsonReader+import kotlinx.serialization.json.Json+import okhttp3.OkHttpClient+import org.junit.Test+import java.io.StringReader+import java.time.ZoneId++class StalkerLiveRowReaderTest {+ private val service = OkHttpStalkerApiService(OkHttpClient(), Json { ignoreUnknownKeys = true })++ private fun decode(payload: String, direct: Boolean) = JsonReader(StringReader(payload)).use { reader ->+ reader.isLenient = true+ service.readLiveItem(reader, ZoneId.of("Asia/Jerusalem"), direct)+ }++ @Test fun directReaderMatchesLegacyForCompleteMappedFields() {+ val payload = """{+ "id":" 001 ","name":" News 世界 ","tv_genre_id":"20","category_name":"Adult",+ "number":"12","logo":"null","screenshot_uri":"/image.png","xmltv_id":"epg.channel",+ "cmd":"ffmpeg http://localhost/ch/1_","cmd_1":"http://cdn.example/one.m3u8",+ "cmd_2":"http://cdn.example/one.m3u8","cmd_3":"http://cdn.example/two.ts",+ "mc_cmd":"http://cdn.example/three.ts","cmds":[null,7,{"url":" ","cmd":"http://cdn.example/four.ts"},{"url":"http://cdn.example/five.ts"}],+ "use_http_tmp_link":"1","nginx_secure_link":true,"flussonic_tmp_link":"yes",+ "wowza_tmp_link":"TRUE","use_load_balancing":1,"allow_local_timeshift":"1",+ "allow_local_pvr":true,"allow_remote_pvr":"yes","archive":"true","censored":"1",+ "description":"plot","actors":"cast","director":"director","genres_str":"genre",+ "year":"2020","added":"2026-10-10 12:00:00","rating_imdb":"7.2","tmdb_id":42,+ "trailer_url":"trailer","backdrop_path":"/backdrop.jpg","container_extension":"ts","is_series":"0",+ "ignored":{"array":[{"nested":[1,2,3]}]}+ }"""+ val legacy = decode(payload, false)+ assertThat(legacy).isNotNull()+ assertThat(decode(payload, true)).isEqualTo(legacy)+ }++ @Test fun directReaderMatchesMixedScalarAliasesAndDefaults() {+ val gson = Gson()+ val values: List<Any?> = listOf(null, "", " null ", " 1 ", "yes", "false", 0, 1, 1.5, true, false, listOf(1), mapOf("ignored" to true))+ val keys = listOf("id", "ch_id", "video_id", "series_id", "name", "title", "tv_genre_id", "category_id", "genre_id", "category_name", "number", "logo", "cover", "screenshot_uri", "xmltv_id", "epg_id", "cmd", "cmd_1", "mc_cmd", "archive", "censored", "allow_remote_pvr", "is_series", "year", "added", "rating", "rating_imdb", "tmdb_id", "container_extension")+ repeat(1000) { row ->+ val fields = keys.mapIndexed { index, key -> key to values[(row * 7 + index * 3) % values.size] }.toMap()+ val payload = gson.toJson(fields)+ assertThat(decode(payload, true)).isEqualTo(decode(payload, false))+ }+ }++ @Test fun duplicateKeysUseLastValueAndAliasesKeepPrecedence() {+ val rows = listOf(+ """{"id":"first","id":null,"ch_id":12,"name":"first","name":" final ","cmd":"http://cdn.example/a.ts"}""",+ """{"id":1,"name":"name","cmds":{},"cmds":[{"url":true,"url":"http://cdn.example/a.ts"}]}""",+ """{"id":1,"name":"name","category_id":1,"tv_genre_id":2,"archive":1,"archive":false}""",+ """{"name":"missing id","cmds":{}}"""+ )+ rows.forEach { assertThat(decode(it, true)).isEqualTo(decode(it, false)) }+ }++ @Test fun malformedCommandShapesAndTruncatedRowsFail() {+ listOf(+ """{"id":1,"name":"name","cmds":null}""",+ """{"id":1,"name":"name","cmds":{}}""",+ """{"id":1,"name":"name","cmds":[{"url":"http://cdn.example/a.ts"}"""+ ).forEach { payload ->+ assertThat(runCatching { decode(payload, false) }.isFailure).isTrue()+ assertThat(runCatching { decode(payload, true) }.isFailure).isTrue()+ }+ }+}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.ktindex ce3005ad..d7b68419 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt@@ -7,6 +7,7 @@ import com.streamvault.data.local.dao.StalkerRemoteIdentityDaoimport com.streamvault.data.local.entity.StalkerPortalStateEntityimport com.streamvault.data.local.entity.StalkerRemoteIdentityEntityimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.provider.toTypedConfigurationimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.ProviderStatus@@ -31,6 +32,109 @@ class StalkerProviderTest {StalkerProvider.clearResolvedStreamUrlCacheForTests()}+ private fun categoryReuseProvider(api: StalkerApiService, key: String? = null) = StalkerProvider(+ providerId = 7L, api = api, portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56", deviceProfile = "MAG250", timezone = "UTC", locale = "en",+ resolvedCategoryHandoffKey = key+ )++ @Test+ fun layoutDetectionCategoriesAreConsumedOnceWithoutRepeatingDiscovery() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ seriesCategories = listOf(StalkerCategoryRecord("20", "Series"))+ )+ val provider = categoryReuseProvider(api)+ assertThat((provider.authenticate() as Result.Success).data.catalogLayout).isEqualTo(CatalogLayout.SPLIT)+ val probeCalls = api.seriesCategoryCalls+ assertThat((provider.getSeriesCategories() as Result.Success).data.single().name).isEqualTo("Series")+ assertThat(api.seriesCategoryCalls).isEqualTo(probeCalls)+ provider.getSeriesCategories()+ assertThat(api.seriesCategoryCalls).isEqualTo(probeCalls + 1)+ }++ @Test+ fun unifiedLayoutReusesSuccessfulVodProbe() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("10", "Mixed"))+ )+ val provider = categoryReuseProvider(api)+ assertThat((provider.authenticate() as Result.Success).data.catalogLayout).isEqualTo(CatalogLayout.UNIFIED_VOD)+ val probeCalls = api.vodCategoryCalls+ assertThat((provider.getUnifiedVodCategories() as Result.Success).data.single().name).isEqualTo("Mixed")+ assertThat(api.vodCategoryCalls).isEqualTo(probeCalls)+ }++ @Test+ fun categorySnapshotHandoffUsesValidatedSessionAndNormalMapping() = runTest {+ val sourceApi = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ seriesCategories = listOf(StalkerCategoryRecord("20", "Resolved"))+ )+ val source = categoryReuseProvider(sourceApi)+ source.authenticate()+ source.handoffResolvedCategories("handoff")+ val targetApi = FakeStalkerApiService(profile = StalkerProviderProfile(accountName = "Room"))+ val target = categoryReuseProvider(targetApi, "handoff")+ assertThat((target.getSeriesCategories() as Result.Success).data.single().name).isEqualTo("Resolved")+ assertThat(targetApi.restoreSessionCalls).isEqualTo(1)+ assertThat(targetApi.seriesCategoryCalls).isEqualTo(0)+ target.invalidateAuthentication()+ target.getSeriesCategories()+ assertThat(targetApi.seriesCategoryCalls).isEqualTo(1)+ }++ @Test+ fun categoryHandoffSurvivesNewProviderIdThroughExistingPersistedSession() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ seriesCategories = listOf(StalkerCategoryRecord("20", "Resolved"))+ )+ val source = StalkerProvider(+ providerId = 0L, api = api, portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56", deviceProfile = "MAG250", timezone = "UTC", locale = "en"+ )+ val resolved = (source.authenticate() as Result.Success).data.copy(id = 25L, stalkerConfigurationGeneration = 1L)+ val config = resolved.toTypedConfiguration()+ val key = StalkerResolvedCategoryHandoff.key(25L, 1L, config as com.streamvault.domain.model.StalkerConfig)+ val store = StalkerPortalStateStore(FakePortalStateDao(), TestCredentialCrypto())+ val (session, profile) = source.validatedAuthenticationSnapshot()!!+ store.recordAuthentication(25L, session, profile, configurationGeneration = 1L)+ source.handoffResolvedCategories(key)+ val targetApi = FakeStalkerApiService(profile = StalkerProviderProfile(accountName = "Room"))+ val target = StalkerProvider(+ providerId = 25L, api = targetApi, portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56", deviceProfile = "MAG250", timezone = "UTC", locale = "en",+ configurationGeneration = 1L, portalStateStore = store, catalogLayoutHint = resolved.catalogLayout,+ catalogLayoutDetectionVersionHint = resolved.catalogLayoutDetectionVersion,+ resolvedCategoryHandoffKey = key+ )+ assertThat(target.authenticate()).isInstanceOf(Result.Success::class.java)+ assertThat((target.getSeriesCategories() as Result.Success).data.single().name).isEqualTo("Resolved")+ assertThat(targetApi.authenticateCalls).isEqualTo(0)+ assertThat(targetApi.seriesCategoryCalls).isEqualTo(0)+ }++ @Test+ fun categoryLookupPreservesFirstMatchWhenIdAndNameDisagree() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ liveCategoryResults = ArrayDeque(listOf(Result.success(listOf(+ StalkerCategoryRecord("10", "News"), StalkerCategoryRecord("20", "Sports"),+ StalkerCategoryRecord("30", "SPORTS")+ )))),+ liveStreams = listOf(+ StalkerItemRecord("1", "Channel", categoryId = "20", categoryName = "NEWS", cmd = "ffmpeg http://localhost/ch/1_"),+ StalkerItemRecord("2", "Channel", categoryId = "30", categoryName = "sports", cmd = "ffmpeg http://localhost/ch/2_")+ )+ )+ val provider = categoryReuseProvider(api)+ provider.getLiveCategories()+ val rows = (provider.getLiveStreams() as Result.Success).data+ assertThat(rows.map { it.categoryName }).containsExactly("News", "Sports").inOrder()+ }+@Testfun truncated_page_is_never_reported_complete() {val page = StalkerPagedResult(@@ -1648,6 +1752,8 @@ class StalkerProviderTest {) : StalkerApiService {var createLinkCalls: Int = 0private set+ var seriesCategoryCalls: Int = 0+ var vodCategoryCalls: Int = 0var authenticateCalls: Int = 0private setvar restoreSessionCalls: Int = 0@@ -1702,7 +1808,10 @@ class StalkerProviderTest {override suspend fun getVodCategories(session: StalkerSession,profile: StalkerDeviceProfile- ) = vodCategoriesResult ?: Result.success(vodCategories)+ ): Result<List<StalkerCategoryRecord>> {+ vodCategoryCalls+++ return vodCategoriesResult ?: Result.success(vodCategories)+ }override suspend fun getVodStreams(session: StalkerSession,@@ -1740,7 +1849,10 @@ class StalkerProviderTest {override suspend fun getSeriesCategories(session: StalkerSession,profile: StalkerDeviceProfile- ) = seriesCategoriesResult ?: Result.success(seriesCategories)+ ): Result<List<StalkerCategoryRecord>> {+ seriesCategoryCalls+++ return seriesCategoriesResult ?: Result.success(seriesCategories)+ }override suspend fun getSeries(session: StalkerSession,@@ -1940,6 +2052,19 @@ class StalkerProviderTest {private class FakeIdentityDao : StalkerRemoteIdentityDao {private val rows = mutableListOf<StalkerRemoteIdentityEntity>()+ override suspend fun getByRawIds(providerId: Long, contentType: String, rawIds: List<String>) =+ rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.rawId in rawIds }++ override suspend fun getBySurrogateIds(providerId: Long, contentType: String, surrogateIds: List<Long>) =+ rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId in surrogateIds }++ override suspend fun insertAll(entities: List<StalkerRemoteIdentityEntity>): List<Long> =+ entities.map { entity ->+ if (rows.any { it.providerId == entity.providerId && it.contentType == entity.contentType &&+ (it.rawId == entity.rawId || it.surrogateId == entity.surrogateId) }) -1L+ else { insert(entity); rows.size.toLong() }+ }+override suspend fun getByRawId(providerId: Long, contentType: String, rawId: String) =rows.firstOrNull { row ->row.providerId == providerId && row.contentType.name == contentType && row.rawId == rawIddiff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.ktindex 4b020593..d7d00a25 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt@@ -33,14 +33,85 @@ class StalkerRemoteIdentityResolverTest {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()}+ @Test+ fun batchedResolutionMatchesSequentialIdentityRulesAcrossSqlChunks() = runTest {+ val dao = FakeIdentityDao()+ val providerId = 7L+ val type = ContentType.LIVE+ dao.insert(StalkerRemoteIdentityEntity(providerId, type, "existing", 23L, 0L, 0L))+ dao.insert(StalkerRemoteIdentityEntity(providerId, type, "occupied-number", 12L, 0L, 0L))+ dao.insert(StalkerRemoteIdentityEntity(providerId, type, "occupied-hash", stalkerStableHashId(providerId, type, "12"), 0L, 0L))+ val ids = (listOf(" existing ", "12", "012", "12", "", "nonnumeric") ++ (1..1200).map { "row-$it" }).map(String::trim).filter(String::isNotEmpty).distinct().sorted()+ val expected = linkedMapOf("existing" to 23L, "occupied-number" to 12L,+ "occupied-hash" to stalkerStableHashId(providerId, type, "12"))+ ids.forEach { rawId ->+ if (rawId !in expected) {+ expected[rawId] = listOfNotNull(rawId.toLongOrNull()?.takeIf { it > 0L }, stalkerStableHashId(providerId, type, rawId))+ .firstOrNull { it !in expected.values }+ ?: ((expected.values.filter { it >= 4_000_000_000L }.maxOrNull() ?: 3_999_999_999L) + 1L)+ }+ }+ val resolver = StalkerRemoteIdentityResolver(dao, DirectTransactionRunner)+ val result = resolver.resolveAll(providerId, type, ids)+ assertThat(result).isEqualTo(ids.associateWith(expected::getValue))+ assertThat(result.values.toSet()).hasSize(ids.size)+ assertThat(dao.maxQueryParameters).isAtMost(400)+ assertThat(dao.singleRawLookups).isEqualTo(0)+ assertThat(dao.singleSurrogateLookups).isEqualTo(0)+ val initialBatches = dao.insertBatches+ assertThat(resolver.resolveAll(providerId, type, ids)).isEqualTo(result)+ assertThat(dao.insertBatches).isEqualTo(initialBatches)+ assertThat(resolver.resolveAll(8L, type, listOf("existing"))["existing"]).isEqualTo(stalkerStableHashId(8L, type, "existing"))+ }++ @Test+ fun ignoredBatchConflictReusesWinningIdentity() = runTest {+ val dao = FakeIdentityDao()+ dao.beforeBatchInsert = { dao.insert(StalkerRemoteIdentityEntity(7L, ContentType.LIVE, "12", 99L, 0L, 0L)) }+ val resolver = StalkerRemoteIdentityResolver(dao, DirectTransactionRunner)+ assertThat(resolver.resolveAll(7L, ContentType.LIVE, listOf("12", "13")))+ .containsExactly("12", 99L, "13", 13L)+ assertThat(resolver.reverse(7L, ContentType.LIVE, 99L)).isEqualTo("12")+ }+private class FakeIdentityDao : StalkerRemoteIdentityDao {private val rows = mutableListOf<StalkerRemoteIdentityEntity>()+ var maxQueryParameters = 0+ var singleRawLookups = 0+ var singleSurrogateLookups = 0+ var insertBatches = 0+ var beforeBatchInsert: (suspend () -> Unit)? = null- override suspend fun getByRawId(providerId: Long, contentType: String, rawId: String) =- rows.firstOrNull { it.providerId == providerId && it.contentType.name == contentType && it.rawId == rawId }+ override suspend fun getByRawIds(providerId: Long, contentType: String, rawIds: List<String>): List<StalkerRemoteIdentityEntity> {+ maxQueryParameters = maxOf(maxQueryParameters, rawIds.size)+ return rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.rawId in rawIds }+ }- override suspend fun getBySurrogateId(providerId: Long, contentType: String, surrogateId: Long) =- rows.firstOrNull { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId == surrogateId }+ override suspend fun getBySurrogateIds(providerId: Long, contentType: String, surrogateIds: List<Long>): List<StalkerRemoteIdentityEntity> {+ maxQueryParameters = maxOf(maxQueryParameters, surrogateIds.size)+ return rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId in surrogateIds }+ }++ override suspend fun insertAll(entities: List<StalkerRemoteIdentityEntity>): List<Long> {+ insertBatches+++ beforeBatchInsert?.also { beforeBatchInsert = null }?.invoke()+ return entities.map { entity ->+ if (rows.any { it.providerId == entity.providerId && it.contentType == entity.contentType &&+ (it.rawId == entity.rawId || it.surrogateId == entity.surrogateId) }) -1L+ else { insert(entity); rows.size.toLong() }+ }+ }++ override suspend fun getByRawId(providerId: Long, contentType: String, rawId: String): StalkerRemoteIdentityEntity? {+ singleRawLookups+++ return rows.firstOrNull { it.providerId == providerId && it.contentType.name == contentType && it.rawId == rawId }+ }++ override suspend fun getBySurrogateId(providerId: Long, contentType: String, surrogateId: Long): StalkerRemoteIdentityEntity? {+ singleSurrogateLookups+++ return rows.firstOrNull { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId == surrogateId }+ }override suspend fun maxAllocatedSurrogate(providerId: Long, contentType: String, floor: Long): Long? =rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId >= floor }diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.ktindex 660f2f48..6f1b8e25 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt@@ -2,6 +2,7 @@ package com.streamvault.data.remote.stalkerimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.StalkerRequestPriority+import java.net.SocketTimeoutExceptionimport java.util.concurrent.atomic.AtomicIntegerimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.async@@ -115,4 +116,58 @@ class StalkerRequestCoordinatorTest {jobs.forEach { it.await() }assertThat(peak.get()).isEqualTo(2)}++ @Test+ fun effectiveMetadataLimitDropsToOneAfterProviderStress() = runTest {+ val coordinator = StalkerRequestCoordinator()+ assertThat(coordinator.effectiveConcurrencyLimit(31L)).isEqualTo(2)++ coordinator.recordFailure(+ providerId = 31L,+ error = StalkerApiError.Transport("portal timed out", SocketTimeoutException())+ )++ assertThat(coordinator.effectiveConcurrencyLimit(31L)).isEqualTo(1)+ }++ @Test+ fun categoryAdmissionAtLimitOneFinishesBeforeBulkCanHoldTheSlot() = runTest {+ val coordinator = StalkerRequestCoordinator()+ coordinator.recordFailure(+ providerId = 32L,+ error = StalkerApiError.Transport("portal timed out", SocketTimeoutException())+ )+ val categoryStarted = CompletableDeferred<Unit>()+ val releaseCategory = CompletableDeferred<Unit>()+ val bulkStarted = CompletableDeferred<Unit>()++ val category = async {+ coordinator.execute(+ 32L,+ StalkerRequestPriority.OPEN_CATEGORY,+ StalkerRequestDescriptor("LIVE", "GET_CATEGORIES")+ ) {+ categoryStarted.complete(Unit)+ releaseCategory.await()+ }+ }+ categoryStarted.await()+ val bulk = async {+ coordinator.execute(+ 32L,+ StalkerRequestPriority.OPEN_CATEGORY,+ StalkerRequestDescriptor("LIVE", "STREAM_ALL")+ ) {+ bulkStarted.complete(Unit)+ }+ }+ runCurrent()+ assertThat(bulkStarted.isCompleted).isFalse()++ releaseCategory.complete(Unit)+ advanceUntilIdle()+ category.await()+ bulk.await()+ assertThat(bulkStarted.isCompleted).isTrue()+ }}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerResolvedCategoryHandoffTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerResolvedCategoryHandoffTest.ktnew file mode 100644index 00000000..5a1ac801--- /dev/null+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerResolvedCategoryHandoffTest.kt@@ -0,0 +1,53 @@+package com.streamvault.data.remote.stalker++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.StalkerDeviceIdentity+import org.junit.After+import org.junit.Test++class StalkerResolvedCategoryHandoffTest {+ @After fun clear() = StalkerResolvedCategoryHandoff.clear()++ @Test fun scopesIncludeProviderGenerationAndCompleteConfiguration() {+ val config = StalkerConfig("https://portal.example/c/", StalkerDeviceIdentity(macAddress = "00:1A:79:12:34:56"))+ val key = StalkerResolvedCategoryHandoff.key(7L, 1L, config)+ assertThat(key).isNotEqualTo(StalkerResolvedCategoryHandoff.key(8L, 1L, config))+ assertThat(key).isNotEqualTo(StalkerResolvedCategoryHandoff.key(7L, 2L, config))+ assertThat(key).isNotEqualTo(StalkerResolvedCategoryHandoff.key(7L, 1L, config.copy(httpHeaders = "changed")))+ }++ @Test fun snapshotIsOneShotAndRetainsSuccessfulEmptyCategories() {+ val session = StalkerSession("https://portal.example/load.php", "https://portal.example/c/", "token")+ StalkerResolvedCategoryHandoff.publish("7/1/config", StalkerResolvedCategoryHandoff.Snapshot(session, mapOf(ContentType.SERIES to emptyList())))+ assertThat(StalkerResolvedCategoryHandoff.take("7/1/config", session)?.categories)+ .containsEntry(ContentType.SERIES, emptyList<StalkerCategoryRecord>())+ assertThat(StalkerResolvedCategoryHandoff.take("7/1/config", session)).isNull()+ }++ @Test fun replacedSessionAndExpiredSnapshotsAreRejected() {+ val session = StalkerSession("https://portal.example/load.php", "https://portal.example/c/", "token", authEpoch = 1L)+ val snapshot = StalkerResolvedCategoryHandoff.Snapshot(session, emptyMap())+ assertThat(snapshot.matches(session.copy(token = "replacement"))).isFalse()+ assertThat(snapshot.matches(session.copy(authEpoch = 2L))).isFalse()+ assertThat(snapshot.matches(session.copy(loadUrl = "https://other.example/load.php"))).isFalse()+ assertThat(snapshot.matches(session, snapshot.createdAt + 60_000L)).isFalse()+ StalkerResolvedCategoryHandoff.publish("7/1/config", snapshot)+ assertThat(StalkerResolvedCategoryHandoff.take("7/1/config", session.copy(authEpoch = 2L))).isNull()+ assertThat(StalkerResolvedCategoryHandoff.take("7/1/config", session)).isNull()+ }++ @Test fun incompatibleLayoutAndDeletionDiscardHandoff() {+ val session = StalkerSession("https://portal.example/load.php", "https://portal.example/c/", "token")+ val snapshot = StalkerResolvedCategoryHandoff.Snapshot(session, emptyMap(), layout = CatalogLayout.SPLIT)+ StalkerResolvedCategoryHandoff.publish("7/1/config", snapshot)+ assertThat(StalkerResolvedCategoryHandoff.take("7/1/config", session, CatalogLayout.UNIFIED_VOD)).isNull()+ StalkerResolvedCategoryHandoff.publish("7/1/config", snapshot)+ StalkerResolvedCategoryHandoff.publish("8/1/config", snapshot)+ StalkerResolvedCategoryHandoff.clearProvider(7L)+ assertThat(StalkerResolvedCategoryHandoff.take("7/1/config", session)).isNull()+ assertThat(StalkerResolvedCategoryHandoff.take("8/1/config", session)).isNotNull()+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex 04035360..fba0e4b8 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -18,6 +18,7 @@ import com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.StalkerIndexJobDao+import com.streamvault.data.local.dao.StalkerLiveCategoryRetryDaoimport com.streamvault.data.local.dao.StalkerRemoteIdentityDaoimport com.streamvault.data.local.dao.TmdbIdentityDaoimport com.streamvault.data.local.dao.VodCategoryHydrationDao@@ -154,6 +155,19 @@ class SyncManagerTest {private class FakeStalkerRemoteIdentityDao : StalkerRemoteIdentityDao {private val rows = mutableListOf<StalkerRemoteIdentityEntity>()+ override suspend fun getByRawIds(providerId: Long, contentType: String, rawIds: List<String>) =+ rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.rawId in rawIds }++ override suspend fun getBySurrogateIds(providerId: Long, contentType: String, surrogateIds: List<Long>) =+ rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId in surrogateIds }++ override suspend fun insertAll(entities: List<StalkerRemoteIdentityEntity>): List<Long> =+ entities.map { entity ->+ if (rows.any { it.providerId == entity.providerId && it.contentType == entity.contentType &&+ (it.rawId == entity.rawId || it.surrogateId == entity.surrogateId) }) -1L+ else { insert(entity); rows.size.toLong() }+ }+override suspend fun getByRawId(providerId: Long, contentType: String, rawId: String) =rows.firstOrNull { row ->row.providerId == providerId && row.contentType.name == contentType && row.rawId == rawId@@ -276,6 +290,7 @@ class SyncManagerTest {private val tmdbIdentityDao: TmdbIdentityDao = mock()private val xtreamContentIndexDao: XtreamContentIndexDao = mock()private val xtreamIndexJobDao: XtreamIndexJobDao = mock()+ private val stalkerLiveCategoryRetryDao: StalkerLiveCategoryRetryDao = mock()private val xtreamLiveOnboardingDao: XtreamLiveOnboardingDao = mock()private val movieCategoryHydrationDao: MovieCategoryHydrationDao = mock()private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao = mock()@@ -319,6 +334,7 @@ class SyncManagerTest {tmdbIdentityDao,xtreamContentIndexDao,xtreamIndexJobDao,+ stalkerLiveCategoryRetryDao,xtreamLiveOnboardingDao,epgRepo,epgSourceRepo,@@ -344,6 +360,9 @@ class SyncManagerTest {org.mockito.kotlin.whenever(preferencesRepo.xtreamBase64TextCompatibility).thenReturn(flowOf(false))org.mockito.kotlin.whenever(preferencesRepo.getHiddenCategoryIds(any(), any())).thenReturn(flowOf(emptySet()))runBlocking {+ org.mockito.kotlin.whenever(+ stalkerLiveCategoryRetryDao.getForProvider(any(), any())+ ).thenReturn(emptyList())org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(any(), any())).thenReturn(emptyList())org.mockito.kotlin.whenever(channelDao.getCount(any())).thenReturn(flowOf(0))org.mockito.kotlin.whenever(channelDao.getByProviderSync(any())).thenReturn(emptyList())@@ -432,6 +451,31 @@ class SyncManagerTest {portalStateStore: com.streamvault.data.remote.stalker.StalkerPortalStateStore = mock()): SyncManager {val configuredProvider = if (providerPresent) providerEntity ?: sampleProvider(providerType) else null+ // Keep the existing sync fixtures on the streaming fallback contract while their+ // category payloads remain stubbed through the legacy list method.+ runBlocking {+ org.mockito.kotlin.whenever(+ stalkerApiService.streamLiveStreamsByCategory(any(), any(), any(), any())+ ).doSuspendableAnswer { invocation ->+ val session = invocation.arguments[0] as com.streamvault.data.remote.stalker.StalkerSession+ val profile = invocation.arguments[1] as StalkerDeviceProfile+ val categoryId = invocation.arguments[2] as String+ @Suppress("UNCHECKED_CAST")+ val onItem = invocation.arguments[3] as suspend (StalkerItemRecord) -> Unit+ @Suppress("UNCHECKED_CAST")+ val legacyResult = stalkerApiService.getLiveStreams(session, profile, categoryId)+ as? Result<List<StalkerItemRecord>>+ when (legacyResult) {+ is Result.Success -> {+ legacyResult.data.forEach { onItem(it) }+ Result.success(legacyResult.data.size)+ }+ is Result.Error -> Result.error(legacyResult.message, legacyResult.exception)+ is Result.Loading -> Result.error("Unexpected loading state")+ null -> Result.error("No category fallback fixture for $categoryId")+ }+ }+ }val stalkerRemoteIdentityResolver = StalkerRemoteIdentityResolver(dao = FakeStalkerRemoteIdentityDao(),transactionRunner = transactionRunner,@@ -463,6 +507,7 @@ class SyncManagerTest {tmdbIdentityDao = tmdbIdentityDao,xtreamContentIndexDao = xtreamContentIndexDao,xtreamIndexJobDao = xtreamIndexJobDao,+ stalkerLiveCategoryRetryDao = stalkerLiveCategoryRetryDao,stalkerIndexJobStore = StalkerIndexJobStore(object : StalkerIndexJobDao {override fun observeForProvider(providerId: Long): Flow<List<StalkerIndexJobEntity>> = flowOf(emptyList())@@ -2736,7 +2781,7 @@ class SyncManagerTest {}@Test- fun `processQueuedStalkerIndexJobs falls back to non paged movie fetch when first page is empty`() = runTest {+ fun `processQueuedStalkerIndexJobs retries only the empty first page and keeps its page receipt`() = runTest {val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(serverUrl = "http://example.com",username = "",@@ -2798,19 +2843,35 @@ class SyncManagerTest {items = emptyList(),page = 1,totalPages = 1,- pageSize = 14+ pageSize = 0,+ hasAdvertisedTotal = false+ )+ ),+ Result.success(+ StalkerPagedItems(+ items = listOf(+ StalkerItemRecord(+ id = "100",+ name = "Movie 100",+ categoryId = "5",+ cmd = "ffmpeg http://example.com/100.ts"+ )+ ),+ page = 1,+ totalPages = 2,+ pageSize = 14,+ advertisedTotalPages = 2)))- org.mockito.kotlin.whenever(stalkerApiService.getVodStreams(any(), any(), eq("5"))).thenReturn(+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(2))).thenReturn(Result.success(- listOf(- StalkerItemRecord(- id = "100",- name = "Movie 100",- categoryId = "5",- cmd = "ffmpeg http://example.com/100.ts"- )+ StalkerPagedItems(+ items = emptyList(),+ page = 2,+ totalPages = 2,+ pageSize = 14,+ advertisedTotalPages = 2)))@@ -2823,13 +2884,18 @@ class SyncManagerTest {if (result is Result.Error) fail(result.exception?.stackTraceToString() ?: result.message)assertThat(result.isSuccess).isTrue()- verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("5"), eq(1))- verify(stalkerApiService).getVodStreams(any(), any(), eq("5"))+ verify(stalkerApiService, org.mockito.kotlin.times(2)).getVodStreamsPage(any(), any(), eq("5"), eq(1))+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("5"), eq(2))+ verify(stalkerApiService, org.mockito.kotlin.never()).getVodStreams(any(), any(), eq("5"))verify(movieDao).insertAll(check { movies ->assertThat(movies).hasSize(1)assertThat(movies.first().providerId).isEqualTo(1L)assertThat(movies.first().streamId).isEqualTo(100L)})+ assertThat(movieHydrationByCategory.getValue(movieCategoryId).lastSuccessfulPage).isEqualTo(2)+ assertThat(movieHydrationByCategory.getValue(movieCategoryId).totalPages).isEqualTo(2)+ assertThat(movieHydrationByCategory.getValue(movieCategoryId).itemCount).isEqualTo(1)+ assertThat(movieHydrationByCategory.getValue(movieCategoryId).isComplete).isTrue()}@Test@@ -3522,6 +3588,218 @@ class SyncManagerTest {verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeriesPage(any(), any(), anyOrNull(), any())}+ @Test+ fun sync_stalker_authorization_retry_discards_staged_rows_before_new_attempt() = runTest {+ val provider = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com", username = "", password = "",+ stalkerMacAddress = "00:11:22:33:44:55", epgSyncMode = ProviderEpgSyncMode.SKIP+ )+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = provider)+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(Result.success(+ StalkerSession("http://example.com/stalker_portal/server/load.php", "http://example.com/c/", "token") to+ StalkerProviderProfile(accountName = "Stalker")+ ))+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(+ Result.success(listOf(StalkerCategoryRecord("10", "News")))+ )+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(emptyList()))+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(emptyList()))+ val staged = CompletableDeferred<Unit>()+ org.mockito.kotlin.whenever(catalogSyncDao.insertChannelStages(any())).doSuspendableAnswer {+ staged.complete(Unit)+ Unit+ }+ var attempts = 0+ org.mockito.kotlin.whenever(stalkerApiService.streamLiveStreams(any(), any(), any())).doSuspendableAnswer { invocation ->+ @Suppress("UNCHECKED_CAST")+ val emit = invocation.arguments[2] as suspend (StalkerItemRecord) -> Unit+ if (attempts++ == 0) {+ repeat(1000) { index -> emit(StalkerItemRecord((index + 1).toString(), "Discarded", categoryId = "10", cmd = "ffmpeg http://example.com/old.ts")) }+ staged.await()+ Result.error("Session expired", com.streamvault.data.remote.stalker.StalkerApiError.SessionExpired("Session expired"))+ } else {+ emit(StalkerItemRecord("2000", "Verified", categoryId = "10", cmd = "ffmpeg http://example.com/new.ts"))+ Result.success(1)+ }+ }+ assertThat(manager.sync(1L, force = false)).isInstanceOf(Result.Success::class.java)+ val writes = argumentCaptor<List<com.streamvault.data.local.entity.ChannelImportStageEntity>>()+ verify(catalogSyncDao, atLeastOnce()).insertChannelStages(writes.capture())+ val failedSession = writes.allValues.flatten().first { it.streamId == 1L }.sessionId+ val verifiedSession = writes.allValues.flatten().single { it.streamId == 2000L }.sessionId+ assertThat(verifiedSession).isNotEqualTo(failedSession)+ verify(catalogSyncDao).clearChannelStages(1L, failedSession)+ verify(catalogSyncDao).insertMissingChannelsFromStage(1L, verifiedSession)+ verify(catalogSyncDao, org.mockito.kotlin.never()).insertMissingChannelsFromStage(1L, failedSession)+ verify(stalkerApiService, org.mockito.kotlin.times(2)).getLiveCategories(any(), any())+ }++ @Test+ fun sync_stalker_bootstrap_imports_prefix_without_certifying_bulk_fidelity() = runTest {+ val provider = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com", username = "", password = "",+ stalkerMacAddress = "00:11:22:33:44:55", epgSyncMode = ProviderEpgSyncMode.SKIP+ )+ val portalState = mock<com.streamvault.data.remote.stalker.StalkerPortalStateStore>()+ val readinessTracker = StalkerReadinessTracker()+ val manager = buildManager(+ providerType = ProviderType.STALKER_PORTAL,+ providerEntity = provider,+ readinessTracker = readinessTracker,+ portalStateStore = portalState+ )+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(Result.success(+ StalkerSession("http://example.com/stalker_portal/server/load.php", "http://example.com/c/", "token") to+ StalkerProviderProfile(accountName = "Stalker")+ ))+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(Result.success(listOf(StalkerCategoryRecord("10", "News"))))+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(emptyList()))+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(emptyList()))+ stalkerApiService.stubStreamLiveStreams((1..1000).map { StalkerItemRecord(it.toString(), "Channel", categoryId = "10", cmd = "ffmpeg http://example.com/live.ts") })+ assertThat(manager.sync(1L, bootstrap = true)).isInstanceOf(Result.Success::class.java)+ val writes = argumentCaptor<List<com.streamvault.data.local.entity.ChannelImportStageEntity>>()+ verify(catalogSyncDao, atLeastOnce()).insertChannelStages(writes.capture())+ assertThat(writes.allValues.flatten()).hasSize(200)+ verify(portalState, org.mockito.kotlin.never()).recordBulkLive(any(), eq(true), anyOrNull(), any(), anyOrNull())+ assertThat(readinessTracker.current(1L)?.state)+ .isEqualTo(com.streamvault.domain.model.StalkerReadiness.READY)+ assertThat(syncMetadataRepo.getMetadata(1L)?.lastLiveSuccess).isEqualTo(0L)+ verify(workScheduler).scheduleProviderResume(1L)+ }++ @Test+ fun sync_stalker_bootstrap_category_fallback_stops_after_the_accepted_prefix() = runTest {+ val provider = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com", username = "", password = "",+ stalkerMacAddress = "00:11:22:33:44:55", epgSyncMode = ProviderEpgSyncMode.SKIP+ )+ val portalState = mock<com.streamvault.data.remote.stalker.StalkerPortalStateStore>()+ val manager = buildManager(+ providerType = ProviderType.STALKER_PORTAL,+ providerEntity = provider,+ portalStateStore = portalState+ )+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(+ Result.success(+ StalkerSession(+ loadUrl = "http://example.com/stalker_portal/server/load.php",+ portalReferer = "http://example.com/stalker_portal/c/",+ token = "token"+ ) to StalkerProviderProfile(accountName = "Stalker")+ )+ )+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(+ Result.success(listOf(StalkerCategoryRecord("10", "News"), StalkerCategoryRecord("20", "Sports")))+ )+ stalkerApiService.stubStreamLiveStreamsError("Bulk live request failed")+ org.mockito.kotlin.whenever(stalkerApiService.getLiveStreams(any(), any(), eq("10"))).thenReturn(+ Result.success((1..250).map { id ->+ StalkerItemRecord(id.toString(), "Channel $id", categoryId = "10", cmd = "ffmpeg http://example.com/$id.ts")+ })+ )+ org.mockito.kotlin.whenever(stalkerApiService.getLiveStreams(any(), any(), eq("20"))).thenReturn(+ Result.success(listOf(StalkerItemRecord("999", "Sports", categoryId = "20", cmd = "ffmpeg http://example.com/999.ts")))+ )+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(emptyList()))+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(emptyList()))++ assertThat(manager.sync(providerId = 1L, bootstrap = true)).isInstanceOf(Result.Success::class.java)++ val writes = argumentCaptor<List<com.streamvault.data.local.entity.ChannelImportStageEntity>>()+ verify(catalogSyncDao, atLeastOnce()).insertChannelStages(writes.capture())+ assertThat(writes.allValues.flatten()).hasSize(200)+ verify(stalkerApiService).getLiveStreams(any(), any(), eq("10"))+ verify(stalkerApiService, org.mockito.kotlin.never()).getLiveStreams(any(), any(), eq("20"))+ verify(portalState, org.mockito.kotlin.never()).recordBulkLive(any(), eq(true), anyOrNull(), any(), anyOrNull())+ verify(workScheduler).scheduleProviderResume(1L)+ }++ @Test+ fun sync_stalker_starts_bulk_live_while_category_context_is_still_loading() = runTest {+ val provider = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com", username = "", password = "",+ stalkerMacAddress = "00:11:22:33:44:55", epgSyncMode = ProviderEpgSyncMode.SKIP+ )+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = provider)+ val categoryStarted = CompletableDeferred<Unit>()+ val releaseCategories = CompletableDeferred<Unit>()+ val bulkStarted = CompletableDeferred<Unit>()++ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(+ Result.success(+ StalkerSession(+ loadUrl = "http://example.com/stalker_portal/server/load.php",+ portalReferer = "http://example.com/stalker_portal/c/",+ token = "token"+ ) to StalkerProviderProfile(accountName = "Stalker")+ )+ )+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).doSuspendableAnswer {+ categoryStarted.complete(Unit)+ releaseCategories.await()+ Result.success(listOf(StalkerCategoryRecord("10", "News")))+ }+ org.mockito.kotlin.whenever(stalkerApiService.streamLiveStreams(any(), any(), any())).doSuspendableAnswer { invocation ->+ bulkStarted.complete(Unit)+ @Suppress("UNCHECKED_CAST")+ val onItem = invocation.arguments[2] as suspend (StalkerItemRecord) -> Unit+ onItem(StalkerItemRecord("100", "News", categoryId = "10", cmd = "ffmpeg http://example.com/live.ts"))+ Result.success(1)+ }+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(emptyList()))+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(emptyList()))++ val sync = async { manager.sync(providerId = 1L, force = false) }+ categoryStarted.await()+ bulkStarted.await()+ assertThat(sync.isCompleted).isFalse()++ releaseCategories.complete(Unit)+ assertThat(sync.await()).isInstanceOf(Result.Success::class.java)+ }++ @Test+ fun sync_stalker_keeps_live_coverage_stale_when_a_fallback_category_fails() = runTest {+ val provider = sampleProvider(ProviderType.STALKER_PORTAL).copy(+ serverUrl = "http://example.com", username = "", password = "",+ stalkerMacAddress = "00:11:22:33:44:55", epgSyncMode = ProviderEpgSyncMode.SKIP+ )+ val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = provider)+ syncMetadataRepo.updateMetadata(SyncMetadata(providerId = 1L, lastLiveSuccess = 123L, liveCount = 1))++ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(+ Result.success(+ StalkerSession(+ loadUrl = "http://example.com/stalker_portal/server/load.php",+ portalReferer = "http://example.com/stalker_portal/c/",+ token = "token"+ ) to StalkerProviderProfile(accountName = "Stalker")+ )+ )+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(+ Result.success(listOf(StalkerCategoryRecord("10", "News"), StalkerCategoryRecord("20", "Sports")))+ )+ stalkerApiService.stubStreamLiveStreamsError("Bulk live request failed")+ org.mockito.kotlin.whenever(stalkerApiService.getLiveStreams(any(), any(), eq("10"))).thenReturn(+ Result.success(listOf(StalkerItemRecord("100", "News", categoryId = "10", cmd = "ffmpeg http://example.com/news.ts")))+ )+ org.mockito.kotlin.whenever(stalkerApiService.getLiveStreams(any(), any(), eq("20"))).thenReturn(+ Result.error("Temporary category failure")+ )+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(Result.success(emptyList()))+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(emptyList()))++ val result = manager.sync(providerId = 1L, force = false)++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(manager.currentSyncState(1L)).isInstanceOf(SyncState.Partial::class.java)+ val metadata = syncMetadataRepo.getMetadata(1L)+ assertThat(metadata?.lastLiveSync).isGreaterThan(123L)+ assertThat(metadata?.lastLiveSuccess).isEqualTo(123L)+ verify(stalkerApiService).getLiveStreams(any(), any(), eq("10"))+ verify(stalkerApiService, atLeast(2)).getLiveStreams(any(), any(), eq("20"))+ }+@Testfun sync_stalker_recovers_when_live_categories_fail_but_bulk_channels_work() = runTest {val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(diff --git a/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.ktindex 0265c117..cde8fb07 100644--- a/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/VodCategoryHydrationCoordinatorTest.kt@@ -9,16 +9,23 @@ import com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.VodCategoryHydrationDaoimport com.streamvault.data.local.dao.VodCatalogEntryDao+import com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.remote.stalker.StalkerPagedResultimport com.streamvault.data.remote.stalker.StalkerProvider+import com.streamvault.data.remote.stalker.StalkerVodCatalogItemimport com.streamvault.domain.model.LegacyProvider+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Movieimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.VodCatalogItemimport com.streamvault.domain.model.VodCategoryHydrationRequestimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.test.runTestimport org.junit.Test+import org.mockito.kotlin.eqimport org.mockito.kotlin.mock+import org.mockito.kotlin.verifyimport org.mockito.kotlin.wheneverclass VodCategoryHydrationCoordinatorTest {@@ -75,6 +82,66 @@ class VodCategoryHydrationCoordinatorTest {assertThat(catalogBodyCompleted).isTrue()}+ @Test+ fun `unified page reads current category protection inside its commit transaction`() = runTest {+ val categoryDao = mock<CategoryDao>()+ val movieDao = mock<MovieDao>()+ var transactionActive = false+ whenever(categoryDao.getByProviderTypeAndCategoryId(7L, ContentType.VOD.name, 11L)).thenAnswer {+ assertThat(transactionActive).isTrue()+ CategoryEntity(+ providerId = 7L,+ categoryId = 11L,+ name = "Protected",+ type = ContentType.VOD,+ isUserProtected = true+ )+ }+ val api = mock<StalkerProvider>()+ whenever(api.getUnifiedVodPage(11L, 1)).thenReturn(+ Result.success(+ StalkerPagedResult(+ items = listOf(+ StalkerVodCatalogItem(+ rawItemId = "movie-1",+ item = VodCatalogItem.MovieItem(+ Movie(id = 101L, streamId = 101L, name = "Movie")+ )+ )+ ),+ page = 1,+ totalPages = 1,+ pageSize = 1+ )+ )+ )+ val coordinator = coordinator(+ api = api,+ categoryDao = categoryDao,+ movieDao = movieDao+ ) { block ->+ transactionActive = true+ try {+ block()+ } finally {+ transactionActive = false+ }+ }++ val result = coordinator.hydrateUnifiedVodCategory(7L, 11L, VodCategoryHydrationRequest.OPEN)++ assertThat(result).isInstanceOf(Result.Success::class.java)+ verify(categoryDao).getByProviderTypeAndCategoryId(7L, ContentType.VOD.name, 11L)+ verify(categoryDao, org.mockito.kotlin.never()).getByProviderAndTypeSync(7L, ContentType.VOD.name)+ verify(movieDao).upsertCategoryPage(+ eq(7L),+ org.mockito.kotlin.check { movies ->+ assertThat(movies).hasSize(1)+ assertThat(movies.single().isUserProtected).isTrue()+ }+ )+ }+private suspend fun successfulEmptyPageApi(): StalkerProvider = mock<StalkerProvider>().also { api ->whenever(api.getUnifiedVodPage(11L, 1)).thenReturn(Result.success(@@ -90,8 +157,13 @@ class VodCategoryHydrationCoordinatorTest {private suspend fun coordinator(api: StalkerProvider,+ categoryDao: CategoryDao? = null,+ movieDao: MovieDao = mock(),transaction: suspend (suspend () -> Unit) -> Unit): VodCategoryHydrationCoordinator {+ val resolvedCategoryDao = categoryDao ?: mock<CategoryDao>().also {+ whenever(it.getByProviderAndTypeSync(7L, "VOD")).thenReturn(emptyList())+ }val provider = LegacyProvider(id = 7L,name = "test",@@ -100,13 +172,11 @@ class VodCategoryHydrationCoordinatorTest {)return VodCategoryHydrationCoordinator(providerSyncLocks = ProviderSyncLockRegistry(),- categoryDao = mock<CategoryDao>().also {- whenever(it.getByProviderAndTypeSync(7L, "VOD")).thenReturn(emptyList())- },+ categoryDao = resolvedCategoryDao,movieCategoryHydrationDao = mock<MovieCategoryHydrationDao>(),seriesCategoryHydrationDao = mock<SeriesCategoryHydrationDao>(),vodCategoryHydrationDao = mock<VodCategoryHydrationDao>(),- movieDao = mock<MovieDao>(),+ movieDao = movieDao,seriesDao = mock<SeriesDao>(),vodCatalogEntryDao = mock<VodCatalogEntryDao>().also {whenever(it.countByCategory(7L, 11L)).thenReturn(0)diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex d4e23216..4e73a9e9 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -28,6 +28,10 @@ All notable product changes are recorded in this document.### Changed+- Reduced duplicate category requests and per-row identity database work during Stalker provider setup, preserving portal verification and stable catalog IDs.+- Added direct Stalker live-row decoding and bounded ingestion with isolated authorization retries; incomplete responses cannot promote a full catalog, and bootstrap prefixes do not certify bulk catalog fidelity.+- Overlapped Stalker live-category and bulk requests when provider admission allows it; category fallback now streams isolated attempts, preserves failed scopes, stops bootstrap after its accepted prefix, and leaves incomplete live coverage eligible for durable refresh.+- Reworked Xtream Live sync with streamed decoding and bounded staging, and made bulk-first `AUTO` the normal-build default with category fallback for safety conditions and bulk failures.- Applied the Xtream live strategy to Add Provider and Settings refresh, including hidden-category routing and clearer sync progress.- Reduced repeated Xtream movie/series summary work with fingerprint checks and bounded resumable indexing; prioritized catalog work before guide refreshes and coalesced duplicate imports.diff --git a/docs/STALKER_SYNC_IMPROVEMENT_PLAN.md b/docs/STALKER_SYNC_IMPROVEMENT_PLAN.mdnew file mode 100644index 00000000..54343310--- /dev/null+++ b/docs/STALKER_SYNC_IMPROVEMENT_PLAN.md@@ -0,0 +1,311 @@+# Stalker Add Provider and catalog ingestion improvement plan++Status: S1-S6 implementation is applied and focused correctness/recovery checks+pass. Real-provider onboarding and sustained live playback acceptance remain+unverified because this workspace has no installed app/provider session.+Prepared: 2026-10-10 against the current working tree, including the uncommitted+Xtream sync improvements.++Implementation evidence: [S1/S2 implementation](STALKER_SYNC_S1_S2_IMPLEMENTATION.md).+S3/S4 evidence: [S3/S4 implementation](STALKER_SYNC_S3_S4_IMPLEMENTATION.md).+S4-S6 follow-up: [overlap, category coverage, readiness, and continuation](STALKER_SYNC_S4_S6_IMPLEMENTATION.md).++## Goal and boundaries++VOD follow-up: [Stalker VOD ingestion improvement plan](STALKER_VOD_IMPROVEMENT_PLAN.md).+It retains pagination and tracks bounded recovery, repeated page work, and+conditional pipeline/decoder improvements separately from S1-S6.++Reduce avoidable work when adding a Stalker provider and when completing its+live catalog in the background. Apply the same ingestion improvements to+Settings live refresh where the existing shared path permits it.++Preserve the existing upfront resolver/discovery flow. Its portal selection,+authentication, compatibility/profile checks, capability validation, content+type detection, and split versus unified catalog decisions are working behavior+to retain. Do not bypass checks, weaken verification, reorder discovery recipes,+or change classification heuristics as part of this plan.++Optimize how successful resolved results are reused and how accepted catalog+rows are decoded, mapped, identified, and persisted after resolution. The+remote-ID database resolver discussed below is a separate persistence concern;+its identity rules also remain unchanged.++No baseline, before/after timing comparison, performance benchmark suite,+physical-device tuning campaign, or numerical speedup gate is required. Validate+correctness, compatibility, bounded resource use, and successful completion.+Do not claim a measured speedup without measurements.++## Current behavior to retain++- New-provider onboarding uses bootstrap sync: at most 200 live rows are read,+ category shells are prepared, and durable full-catalog work is queued.+ This is initial availability, not a complete lineup.+- Provider edits validate and promote the replacement catalog through the+ existing staged configuration and commit callback.+- Bulk live loading already precedes category fallback, with learned capability+ state, a stall watchdog, and provider-aware request admission.+- Movie/series item indexing and guide work already have continuation paths.+- Authentication/session caches, custom headers, transport configuration,+ request priority, throttling, and stress cooldown remain authoritative.+- Shared Xtream work already supplies the cheaper logical group-ID calculation+ and staged live promotion using Room FTS content-sync triggers. Reuse those+ changes; do not implement duplicates or reintroduce global FTS rebuilds.++Relevant source:++- `data/.../repository/ProviderRepositoryImpl.kt`: discovery and onboarding.+- `data/.../remote/stalker/StalkerDiscoveryCoordinator.kt`: upfront discovery.+- `data/.../remote/stalker/StalkerProvider.kt`: layout detection, mapping, caches.+- `data/.../remote/stalker/OkHttpStalkerApiService.kt`: streaming row parsing.+- `data/.../remote/stalker/StalkerRemoteIdentityResolver.kt`: persistent IDs.+- `data/.../sync/StalkerCatalogSyncExecutor.kt`: live staging and fallback.+- `data/.../sync/SyncCatalogStore.kt`: transactional catalog promotion.++## S1 — Reuse successful discovery results++Status: **Implemented and correctness validated** (all five implementation items).++Keep every required discovery request and decision. Retain successful category+responses already obtained during layout detection so the subsequent setup flow+does not fetch the identical categories again.++Implementation:++1. Introduce an internal resolved-category snapshot containing the raw category+ records, endpoint/content type, resolved layout, and the session/configuration+ identity needed to establish that it belongs to the current provider.+2. Retain successful empty responses as successful empty responses. A failure,+ timeout, or inconclusive result must not become an authoritative empty list.+3. Hand the snapshot from the discovery client to the sync client through an+ explicit, short-lived in-memory handoff. Account for the new provider ID+ assigned after discovery; map remote IDs only in the final provider scope.+ Do not put session tokens or raw category payloads in sanitized discovery+ summaries or persist them as new credential copies.+4. Consume it through the existing category mapping and classification path,+ including adult flags, wildcard category behavior, and unified/split routing.+5. Invalidate on configuration changes, authentication invalidation/session+ replacement, incompatible layout, deletion, or expiry. A process restart or+ cache miss uses the current network path normally.++Acceptance: setup consumes matching successful discovery categories without a+duplicate request; misses and stale snapshots still fetch normally. Existing+resolver outcomes and error behavior remain equivalent.++## S2 — Reduce per-row database and category lookup work++Status: **Implemented and correctness validated** (all five implementation items).++Optimize identity persistence without changing assigned IDs or collision rules.++Implementation:++1. Add chunked DAO queries for existing raw IDs and occupied candidate surrogate+ IDs. Respect SQLite bind limits; never build an unbounded `IN` query.+2. Under the existing provider/content-type lock and transaction, reuse known+ identities and assign missing identities in the current sorted order.+ Preserve preferred category IDs, numeric candidates, legacy hash candidates,+ and high-surrogate fallback precedence.+3. Track occupied/new candidates within the batch, batch-insert new records, and+ retain conflict recovery for external writers. Avoid `REPLACE`, which could+ silently change an established mapping. Read high-surrogate allocation state+ once when needed and advance it safely within the transaction.+4. Keep memory bounded to the current identity batch. Preserve reverse lookup+ and category migration/name reconciliation behavior.+5. Build immutable category lookup maps when category seeds change. Preserve+ the existing first-match behavior when raw ID and name matches disagree or+ duplicate names exist, case-insensitive name matching, fallback names, and+ category ordering. Rebuild maps when projection adds category seeds.++Acceptance: numeric, nonnumeric, duplicate, colliding, and preexisting identities+resolve identically; refresh preserves local IDs and user state; category mapping+matches the existing list-based implementation.++## S3 — Add a direct live-row decoder++Status: **Implemented and correctness validated** (all five implementation items).++Replace per-row Gson trees only on the bulk live ingestion path. Keep generic+VOD, series, detail, and guide decoders outside this change.++Implementation:++1. Read retained live fields directly from `JsonReader` into a live record or+ compatible `StalkerItemRecord`; skip irrelevant nested payloads without+ allocating their trees.+2. Preserve field aliases, scalar coercion, null/default behavior, duplicate-key+ handling, text decoding, and supported array/wrapper/object-keyed shapes.+3. Preserve all fields needed for channel admission and playback: raw identity,+ name/order, category, logo, EPG ID, adult status, command/direct URL, extension,+ temporary-link/playback descriptors, archive and timeshift/PVR capabilities.+ Audit `toItemRecord` and `toChannel` together before selecting retained fields.+4. Preserve portal error and invalid-token detection. A truncated document or+ transport failure cannot be accepted as a complete catalog. Separate invalid+ rows from invalid document structure and retain current admission limits.+5. Keep the legacy reader available internally until differential compatibility+ checks pass. Do not add user-facing experimental decoder options.++Acceptance: fixture rows produce equivalent accepted channel fields and playback+descriptors; malformed/error/truncated responses retain failure semantics.++## S4 — Overlap live metadata and bounded ingestion++Status: **Implemented; focused concurrency and recovery checks pass**.++- [x] One producer, one queued raw batch, and one mapping/staging consumer.+- [x] Runtime row budgets and estimated retained-byte batch limits.+- [x] Consumer-owned counters, deduplication, and deferred fallback-category snapshots.+- [x] Fresh staging state and refreshed category context on authorization retry.+- [x] Joined reader/writer cancellation and failed-attempt cleanup.+- [x] Preserve the 200-row bootstrap prefix without recording full fidelity.+- [x] Watchdog distinguishes local work/backpressure from network stalls.+- [x] Overlap eligible live-category and bulk HTTP requests.+- [x] Keep limit-one/stressed portals sequential to avoid holding the only permit+ while the bulk consumer waits for category context.+- [x] Exercise overlap with a blocked category response and verify the bulk HTTP+ request starts before categories complete.++After upfront resolution completes, fetch live categories and the selected bulk+live response concurrently when admitted by the existing Stalker coordinator.+Use one bulk request, a bounded queue of raw live-row batches, and one consumer+that resolves identities, maps channels, and writes staging batches.++Implementation:++1. Reuse Xtream pipeline concepts without forcing Xtream DTOs or category rules+ onto Stalker. Resolve immutable category context once before mapping rows.+2. Preserve learned bulk support/fidelity selection. Known category-only portals+ enter fallback directly. When category discovery is needed for route selection,+ retain that dependency; overlap only where the bulk choice is already valid.+3. Respect existing metadata concurrency, cooldowns, priorities, and network+ permits. Category retrieval must remain able to finish while the bounded+ reader queue is full, including when the provider limit has dropped to one;+ never create a request-permit/queue deadlock.+4. Start conservatively with one queued batch and existing row batch sizes.+ Count reader, queued, and writer batches in retained memory. Add a retained-byte+ bound for wide records using the existing admission policy.+5. Keep counters, deduplication, category collection, and staging-session ownership+ in the single consumer. Materialize fallback categories at completion rather+ than copying their growing snapshot after every batch.+6. Give each bulk attempt a fresh staging session. Automatic authorization+ retry must restart the whole attempt after cleanup, rather than replay rows+ into the previous attempt's writer state. Join cancelled work before fallback.+7. Cancellation or writer failure closes the response and queue and discards+ staging. Promotion requires a valid completed response and drained writes.+8. Treat the existing 200-row bootstrap limit as an intentional partial result.+ Preserve its current admission/count semantics and durable full-sync handoff;+ never mark the partial bootstrap as a complete catalog or bulk-fidelity proof.+9. Distinguish network read progress from local writer/backpressure time so the+ bulk stall watchdog does not misclassify healthy database work as a stalled+ portal. Retain prompt timeout and cancellation for actual network stalls.++Acceptance: concurrency limits hold, slow categories and a full queue terminate,+writer/reader failures cannot promote partial attempts, and bootstrap still queues+full sync. No unbounded lineup list is introduced on the bulk route.++## S5 — Stage category fallback as categories finish++Status: **Implemented; bounded streaming and durable failed-scope retries are wired**.++Keep the current category concurrency cap and stress-based downgrade policy.+Replace retained whole-lineup outcomes with bounded category staging.++Implementation:++1. Stage each category attempt separately. Merge its rows into the import only+ after that attempt succeeds; discard a failed attempt before retrying it.+2. Retain compact coverage/count/error receipts instead of every completed+ category's channel list. Bound the remaining current-response memory; where+ the paged API still materializes a list, stream or consume bounded pages.+3. Preserve deterministic ordering and duplicate admission across categories.+ Concurrent completion order must not decide which duplicate row wins.+4. For bootstrap, stop after the current accepted prefix limit is satisfied;+ do not request later categories merely to truncate the combined list to 200.+ The full provider continuation remains durable.+5. For complete refresh, prune only confirmed complete scopes. Failed categories+ preserve existing verified rows, hidden categories remain preserved, and+ required hidden rows still participate under current rules.+6. Persist failed category IDs, names, configuration generation, attempt count,+ and sanitized error in the Room live-category retry queue. On the next ordinary+ sync, fetch only those still-visible scopes. Commit retry-queue updates in the+ same transaction as channel promotion; a successful full bulk refresh clears+ the queue. Keep `lastLiveSuccess` stale until all retry scopes complete.+ Portal-wide authentication/account/rate-limit failures are not stored as+ independent category retries.++Acceptance: fallback imports all successful scopes, partial failure preserves+verified data, retries do not retain failed rows, and bootstrap avoids unnecessary+remaining category downloads without claiming full coverage.++## S6 — Integrate readiness and durable follow-up++Status: **Readiness and durable bootstrap handoff verified in focused tests**;+the real-provider lifecycle acceptance below remains pending.++Preserve the current bootstrap/full-sync product behavior. Do not enlarge or+remove the 200-row cap as an incidental optimization.++- Publish readiness only after the relevant transaction commits. Distinguish+ initial availability, full live completion, category shells, item indexing,+ and guide completion using existing state models.+- Keep pending full live work ahead of optional item indexing and guide work.+ Use the current workflow locks, generations, and continuation scheduler;+ avoid competing work chains or duplicate scheduling.+- Ensure cancel, process restart, provider edit, and deletion cannot publish+ stale results or lose the bootstrap continuation.+- Keep setup completion/navigation and explicit save-with-verification-pending+ behavior intact. Reuse existing localized messages where possible.++## Correctness validation++Extend existing focused tests rather than introducing a performance harness.+Use fake request counts and coroutine barriers for reuse/concurrency assertions;+do not use elapsed-time speed assertions.++| Area | Required checks |+| --- | --- |+| Upfront resolver | Existing portal/profile/capability/type/layout fixtures retain their outcomes; no checks are skipped |+| Snapshot reuse | Split/unified layouts, successful empty response, error, session/configuration mismatch, new ID assignment, restart/cache miss |+| Identity persistence | Numeric/string IDs, collisions within/across batches, existing mappings, reverse lookup, provider/type isolation, transaction rollback |+| Decoder | Differential field equivalence, aliases/coercion, wrappers/keyed objects, descriptors, unknown nesting, errors, truncation, cancellation |+| Pipeline | Slow categories/writer, full queue, limit-one permits, authorization retry after staged rows, stall timeout, bounded wide rows |+| Fallback | Bulk unsupported/error, category retry/downgrade, deterministic duplicates, partial coverage, bootstrap early stop, hidden scopes |+| Catalog | Insert/update/delete/unchanged search, stable IDs/favorites/protection, provider isolation, atomic promotion |+| Lifecycle | Add Provider, staged edit, Settings refresh, full continuation, cancel, restart, supersession, deletion |++Run affected data/domain/provider unit tests and Room instrumentation for actual+identity constraints and promotion/search behavior. Exercise onboarding through+its real sync entry point and verify persisted rows and continuation state.+Build success alone is insufficient correctness evidence.++When ingestion or mapping changes affect playable channel fields, validate two+representative live channels in the emulator under `AGENTS.md`: preferably 61+screenshots per channel at 2-second intervals, progressing frames, media session+`PLAYING` with `error=null`, and sanitized logs with no fatal/stuck error or+unintended MPEG-TS fallback. Record channel names, capture counts/intervals,+unique hashes, session results, and log findings. This is playback correctness+validation, not a before/after speed comparison. Missing provider access remains+an explicit validation gap rather than a passing result.++## Implementation order and completion++S1-S6 are implemented in the current working tree. Keep changes independently+reviewable and preserve unrelated dirty Xtream work.+Prefer DAO/code changes without schema migration where current tables suffice.++- [x] S1 resolved category reuse and invalidation verified.+- [x] S2 batched identities and category lookup equivalence verified.+- [x] S3 live decoder compatibility verified.+- [x] S4 bounded ingestion, retry isolation, bootstrap prefix, and eligible+ category/bulk overlap verified; single-slot admission remains sequential.+- [x] S5 incremental category streaming, provider-order duplicate precedence,+ bootstrap early stop, and partial-scope preservation implemented.+- [x] S6 readiness milestones and durable bootstrap full-sync handoff verified.+- [x] Focused Stalker, SyncManager, and provider repository unit tests pass.+- [x] Implemented identity/import/promotion behavior passes Room integration checks.+- [ ] Real-provider onboarding and continuation acceptance verified.+- [ ] Playback correctness verified where playable imported fields changed.+- [x] Current validation gaps documented; no unsupported speedup claims.++Last updated: 2026-10-10. Checked items describe completed work in the current+working tree, not a claim that all provider/playback acceptance has passed.diff --git a/docs/STALKER_SYNC_S1_S2_IMPLEMENTATION.md b/docs/STALKER_SYNC_S1_S2_IMPLEMENTATION.mdnew file mode 100644index 00000000..768cd27d--- /dev/null+++ b/docs/STALKER_SYNC_S1_S2_IMPLEMENTATION.md@@ -0,0 +1,76 @@+# Stalker setup: resolved category reuse and identity persistence++Implemented 2026-10-10. Covers S1 and S2 of+[the improvement plan](STALKER_SYNC_IMPROVEMENT_PLAN.md). S3-S6 remain pending.++## Changes++Successful series/VOD category responses obtained by existing layout detection+are retained for one use by the subsequent category mapping path. Upfront portal+discovery, authentication, compatibility validation, and type/layout decisions+are unchanged. Failed probes are not converted into cached empty responses.++An explicit process-local handoff bridges the discovery client and the sync+client after the final provider ID is assigned. Its key includes provider ID,+configuration generation, and a digest of the complete typed configuration.+Consumption requires matching endpoint, token, authentication epoch, session+scope, expiry, and compatible resolved layout. The snapshot has a 60-second+lifetime; the shared cache is limited to 256 entries. Authentication invalidation+and provider deletion clear applicable handoffs. No new persistent session,+credential, or raw payload storage is introduced. The normal network path remains+the fallback after cache misses, restarts, mismatches, and expiration.++Unified VOD consumes the VOD endpoint probe while continuing to map categories+under the VOD content type. Raw category IDs are translated only within the+final provider's identity scope. Existing category/adult/wildcard mapping remains+authoritative.++Identity resolution now uses chunked existing-raw-ID and occupied-surrogate-ID+queries, followed by batch inserts. SQL parameter chunks are capped at 400.+Existing mappings, sorted assignment order, preferred category IDs, numeric+candidates, legacy hash candidates, and high-surrogate allocation precedence+are preserved. Ignored insert conflicts take the existing collision recovery+path; established identities are never replaced. The current lock and database+transaction still own the operation. No schema migration is needed.++Immutable category lookup maps replace repeated list scanning during row mapping.+They preserve the earliest list match when ID and name disagree, duplicate-name+ordering, and case-insensitive name matching. They rebuild when the underlying+category seed list changes and clear when authentication is invalidated.++The existing 200-row bootstrap limit, catalog activation, continuation scheduling,+and setup navigation behavior are unchanged.++## Validation++The following command completed successfully:++```powershell+.\gradlew.bat :data:testDebugUnitTest --tests '*Stalker*Test' --tests '*SyncManagerTest' --tests '*ProviderRepositoryImplTest' :data:connectedDebugAndroidTest '-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StalkerIdentityIntegrationTest' --console=plain+```++- 346 unit tests across 24 suites passed, with no failures, errors, or skips.+- The Room identity integration test passed on `emulator-5554`, reported as+ `Television_4K_2(AVD) - 16` by the Android test runner.+- New coverage verifies one-shot split/unified category reuse, normal mapping,+ invalidation, new-provider ID handoff through the existing persisted session,+ configuration/generation/session/layout mismatches, expiry, and deletion.+- Identity checks cover more than one SQL chunk, equivalence with sequential+ assignment rules, numeric aliases, occupied numeric/hash candidates, refresh,+ provider isolation, and competing identity conflict recovery.+- Room checks verify actual unique constraints, ignored conflicts without+ replacement, reverse lookup, preferred category IDs, and transaction rollback.+- Category mapping checks preserve earlier name matches when a later ID match+ disagrees, including duplicate case-insensitive names.+- `git diff --check` passed.++The first Room run exposed an incorrect assertion that raw ID `1` necessarily+owned surrogate ID `1`. Existing sorted assignment lets `001` claim that ID+first. The assertion now checks the actual assigned surrogate; identity rules+were not changed to satisfy the test.++Validation output is under ignored `build/stalker-validation.log`, the Gradle+unit-test reports, and the connected Android test reports. No before/after+performance measurement was run or required. No measured speedup is claimed.+Real-provider onboarding and sustained playback were not exercised in this+implementation batch; the decoder and ingestion pipeline have not changed.diff --git a/docs/STALKER_SYNC_S3_S4_IMPLEMENTATION.md b/docs/STALKER_SYNC_S3_S4_IMPLEMENTATION.mdnew file mode 100644index 00000000..09894a73--- /dev/null+++ b/docs/STALKER_SYNC_S3_S4_IMPLEMENTATION.md@@ -0,0 +1,95 @@+# Stalker direct live decoding and bounded ingestion++This is the initial S3/S4 implementation snapshot. The follow-up completed the+remaining S4 overlap work and implemented S5/S6; see+[the follow-up report](STALKER_SYNC_S4_S6_IMPLEMENTATION.md) for current status.++Implemented 2026-10-10. Completes S3 and implements the ingestion/retry portion of+S4 in [the improvement plan](STALKER_SYNC_IMPROVEMENT_PLAN.md).++## Direct decoding++The bulk live response reader now consumes mapped scalar fields and command+variants directly from `JsonReader`. Unknown nested metadata is skipped without+building Gson trees. The direct and retained legacy readers share the existing+record mapper, preserving category/EPG fields, adult flags, command descriptors,+temporary-link and archive/PVR capabilities, extensions, and other mapped+metadata. Generic VOD, series, detail, guide, and upfront resolver decoding are+unchanged.++Scalar coercion, aliases, last-key-wins behavior, command-array indexes, malformed+command shapes, and missing-row identity/name admission are preserved. The+complete-response path now also checks `END_DOCUMENT`; extra JSON after a valid+catalog is a failure rather than a completed snapshot. Intentional bootstrap+prefix termination remains distinct from full-response completion.++## Bounded pipeline and attempt ownership++Bulk live loading now uses one raw-row producer, a one-batch queue, and one+consumer that owns identity mapping and staging callbacks. The consumer uses+the existing runtime row budgets, with estimated raw batch byte budgets of+256/512/1024 KiB for LOW/MID/HIGH. Wide rows exceeding the batch byte budget fail+explicitly. Direct callers without a runtime profile retain a 500-row limit and+a 1 MiB byte budget.++Memory accounting includes the producer's current batch, a queued batch, the+consumer's batch, and the separate mapped staging batch. The queue does not+remove the existing admitted-ID deduplication set, which remains governed by+the provider catalog row limit. The byte estimate limits retained batches; it+is not a measured total heap bound or a token-level scalar allocation limit.++Reader failure, writer failure, and cancellation close the queue and join the+consumer before retry or attempt cleanup. Normal writer cleanup does not turn+a returned portal error into cancellation. Authorization retry invokes an+attempt-start callback that discards the previous session, counters, duplicate+state, buffered rows, and fallback categories. It reloads category context after+reauthentication before starting the replacement stream.++Staging uses admitted-count accounting for fresh attempts and materializes+fallback categories at completion. The bulk stall watchdog distinguishes local+mapping/writes and queue backpressure from network inactivity. Cancelled staging+cleanup runs in a noncancellable context after the pipeline has stopped.++The 200-row bootstrap cap is preserved. A successful prefix no longer records+a positive bulk category-fidelity verdict; that evidence requires a completed+full response. Durable full sync still follows bootstrap through existing+continuation behavior.++## Initial follow-up status (superseded)++Live categories still load before bulk HTTP. Concurrent category/bulk requests+require explicit admission ordering so a bulk response holding the only portal+permit cannot fill its queue while its consumer waits for queued category work.+That ordering has not been implemented; S4 remains partially complete.++Incremental category fallback (S5), remaining readiness/scheduling integration+(S6), and final end-to-end provider/playback acceptance are also pending.++## Validation++- 356 unit tests across 26 suites passed, with no failures, errors, or skips:+ `:data:testDebugUnitTest --tests '*Stalker*Test' --tests '*SyncManagerTest' --tests '*ProviderRepositoryImplTest'`.+- Decoder differential tests compare the retained legacy path across complete+ mapped fields/descriptors, 1,000 mixed scalar/alias rows, duplicate keys,+ command shapes, and truncation.+- Coroutine-barrier tests verify reader backpressure, ordered drain, reader error,+ writer failure, full-queue cancellation, joined cleanup, and wide-row rejection.+- SyncManager tests force an authorization failure after actual staged writes,+ then verify a fresh session is promoted and the failed session is discarded.+ Bootstrap tests verify 200 staged rows without a positive fidelity verdict.+- Two `StalkerLiveIngestionIntegrationTest` tests passed on `emulator-5554`+ (`Television_4K_2(AVD) - 16`). They use the real HTTP decoder, Stalker mapper,+ identity resolver, pipeline, staging helpers, and Room promotion. Only initial+ authentication is supplied by the fixture; production discovery is unchanged.+- The Room tests verify additions/deletions, stable local IDs, retained favorites,+ EPG/archive fields, stream descriptor equivalence, and FTS rename behavior.+ Trailing and truncated documents leave the verified catalog intact and clear+ failed staging.+- `:app:assembleDebug -PcompatAbi=x86_64` passed. The APK was built, not installed.+- `git diff --check` passed.++Logs: ignored `build/stalker-s3-s4-validation.log`,+`build/stalker-s3-s4-room.log`, and `build/stalker-s3-s4-app-build.log`.+No before/after speed measurements were run and no measured speedup is claimed.+Real-provider setup and the two-channel sustained playback acceptance were not+run; synthetic import/Room checks do not count as playback validation.diff --git a/docs/STALKER_SYNC_S4_S6_IMPLEMENTATION.md b/docs/STALKER_SYNC_S4_S6_IMPLEMENTATION.mdnew file mode 100644index 00000000..b943d121--- /dev/null+++ b/docs/STALKER_SYNC_S4_S6_IMPLEMENTATION.md@@ -0,0 +1,75 @@+# Stalker S4-S6 follow-up implementation++Implemented 2026-10-10. This report extends the initial+[S3/S4 implementation snapshot](STALKER_SYNC_S3_S4_IMPLEMENTATION.md) and+records current status for the [improvement plan](STALKER_SYNC_IMPROVEMENT_PLAN.md).++## S4: eligible category and bulk overlap++The live category request starts before the bulk request. When the provider's+adaptive metadata limit permits two requests, bulk HTTP can run while categories+load; the single bulk consumer waits for the complete category context before+mapping any row. When stress state lowers admission to one, categories finish+before bulk starts, so bulk cannot hold the only slot while waiting on its own+consumer. Known category-only portals continue to use category fallback.++The coordinator retains request priority, rate-limit cooldown, provider stress,+and cancellation behavior. Existing bounded pipeline rules still own raw batches,+mapping, staging, authorization retry, and reader/writer cleanup.++## S5: incremental category fallback++Category fallback uses the validated paged `get_ordered_list` reader and bounded+mapped batches. Every full category attempt has a separate staging session. A+transport/server retry starts with a fresh session after the previous pipeline+drains; failed attempts are discarded. Completed categories merge into the+catalog stage in provider order, so concurrent completion order does not choose+the duplicate row winner.++Complete refreshes prune only successfully fetched category scopes. Failed or+unvisited scopes retain their verified channels. A partial category result does+not advance `lastLiveSuccess`. Failed category scopes are persisted in the Room+`stalker_live_category_retries` table with their category ID/name, configuration+generation, attempt count, and sanitized error. The next ordinary live/provider+sync fetches only queued, still-visible scopes; successful scope promotion and+queue deletion happen in the same Room transaction. A verified full bulk refresh+clears the queue. Entries for changed provider configurations, removed categories,+and intentionally hidden categories are discarded. Portal-wide authorization,+account, rate-limit, or transport-consent failures stop further category+scheduling and are not recorded as independent category retries.++Bootstrap fallback is sequential and stops requesting later categories once the+200-row accepted prefix is reached. The prefix uses upsert-only promotion, does+not certify bulk fidelity, and retains the existing durable full-provider+continuation.++## S6: readiness and continuation++Live readiness is published after staged promotion returns; category readiness+follows category-shell commits. The coordinator passes bootstrap's typed+`FULL_CATALOG` receipt to `ProviderContinuationScheduler`, which schedules the+existing provider-resume work. The focused bootstrap test verifies readiness,+the 200-row limit, stale full-catalog metadata, and the durable resume call.+Existing repository coverage continues to check save-with-verification-pending+and provider configuration revision behavior.++## Validation++- Focused unit run passed: 361 tests across 26 suites, no failures, errors, or+ skips. Command:+ `:data:testDebugUnitTest --tests '*Stalker*Test' --tests '*SyncManagerTest' --tests '*ProviderRepositoryImplTest'`.+- New `SyncManagerTest` cases cover overlap while category loading is blocked,+ fallback bootstrap stopping before the next category, and preserving a stale+ live-success timestamp after a category failure.+- `StalkerLiveIngestionIntegrationTest` passed on `emulator-5554`, covering Room+ promotion, partial-scope pruning, stable IDs/favorites/search, bounded category+ pages, and rejection of trailing/truncated catalogs.+- `git diff --check` passed on the final working tree.+- Durable per-category retry tracking was added after that validation run; it has+ not yet been covered by a test run in this follow-up. Production and unit-test+ Kotlin compilation passed, the app/Hilt graph compiled, and KSP generated the+ version 80 Room schema.+- The emulator has the sync benchmark packages but not the StreamVault app. No+ real provider credentials/session were available. Two-channel sustained live+ playback and real-provider onboarding/continuation therefore remain unverified.+- No before/after timing comparison was run; no numerical speedup is claimed.diff --git a/docs/STALKER_VOD_IMPROVEMENT_PLAN.md b/docs/STALKER_VOD_IMPROVEMENT_PLAN.mdnew file mode 100644index 00000000..fa9ff084--- /dev/null+++ b/docs/STALKER_VOD_IMPROVEMENT_PLAN.md@@ -0,0 +1,189 @@+# Stalker VOD ingestion improvement plan++Status: V1 and V2 are implemented; focused unit, Room, and app-build validation+passed. Real-provider browsing and playback remain unverified.+Prepared: 2026-10-10 against the current working tree.+Related: [Stalker live improvements](STALKER_SYNC_IMPROVEMENT_PLAN.md).+Implementation evidence: [V1/V2 implementation notes](STALKER_VOD_V1_V2_IMPLEMENTATION.md).++## Decision and boundaries++Keep paginated VOD loading as the default. Improve work around each page and+exceptional whole-category loading. Do not introduce a speculative single-request+bulk endpoint, request every page concurrently, or force full VOD ingestion into+Add Provider. An All/wildcard listing is still paginated.++Preserve the upfront resolver, authentication/profile checks, content detection,+split/unified layout decisions, movie/series classification, VOD-derived series,+playback descriptors, source order, and category protection. Preserve existing+interactive OPEN/NEXT_PAGE/COMPLETE behavior and background continuation policy.++No before/after measurements, benchmark suite, or numerical speedup gate is+required. Validate correctness and bounded processing; make no measured gain claims.++## Existing implementation to retain++- [x] Setup prepares category shells and defers item loading.+- [x] Interactive hydration commits page rows and checkpoints transactionally.+- [x] Successful-page checkpoints support continuation.+- [x] Existing page anomaly checks detect inconsistent totals/repeated pages.+- [x] Background indexing limits category concurrency and downgrades on stress.+- [x] Unified VOD preserves mixed movie/series classification and page ordering.+- [x] Page mapping uses the shared identity resolver improved by live work.+- [x] Limited wildcard strategy already exists with learned support.++These are existing behaviors observed in source, not new work completed by this+plan or a claim that all end-to-end acceptance has passed.++Relevant source:++- `data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt`+ (`getVodStreams`, `fetchPagedItems`, and single-page decoding).+- `data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt`+ (page mapping, classified split/unified VOD, identities).+- `data/src/main/java/com/streamvault/data/sync/SyncManager.kt`+ (`fetchStalkerSummaryPageWithRecovery`, operations adapters).+- `data/src/main/java/com/streamvault/data/sync/VodCategoryHydrationCoordinator.kt`+ (interactive hydration and page transactions).+- `data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutor.kt`+ (background fetch windows, checkpointing, pruning, wildcard strategy).+- `data/src/main/java/com/streamvault/data/sync/StalkerIndexPolicy.kt`+ (pagination, deduplication, and retry decisions).++## V1 — Bound exceptional complete-category recovery++Priority: first. Status: implemented.++The normal page path is incremental. However, empty-first-page summary recovery+calls `getVodStreams` or `getSeriesList`. The VOD list API calls `fetchPagedItems`,+accumulates all pages, and recovery wraps the result as page 1 of 1. This loses+real page provenance and can retain a whole category during a background slice.++- [x] Trace production callers of complete-list APIs and separate required public+ list contracts from internal ingestion callers. Do not change unrelated providers.+- [x] Identify the compatibility difference that makes this recovery useful using+ existing fixtures/request traces. Both VOD routes ultimately use ordered-list+ requests; preserve necessary recovery instead of assuming it is redundant.+- [x] Give ingestion recovery a bounded page/batch consumption contract with+ explicit coverage and termination receipts. Reuse proven pagination checks.+- [x] Preserve real page provenance or isolate complete-category recovery staging+ from normal page checkpoints; do not label a partial prefix as page 1 of 1.+- [x] Remove complete-category recovery from summary ingestion, so no staging+ attempt or concurrent page work remains to join or clean. A retry is page-scoped;+ cancellation unwinds before the existing page commit.+- [x] Keep each recovery attempt to one paged response and preserve its coverage+ receipt. Existing anomaly, truncation, page-limit, and background-slice handling+ remain authoritative; no client-side byte cap was added.+- [x] Preserve classified split/unified behavior, including derived series, when+ replacing list-based recovery. Verify native-series fallback separately.++Acceptance: ordinary and exceptional ingestion do not retain a complete category+list; failed recovery cannot publish complete coverage or prune verified data.+Any remaining public list-returning API is explicitly documented and excluded+from claims of bounded internal ingestion.++## V2 — Reduce repeated page-local database work++Priority: second. Status: implemented.++Unified hydration reloads all VOD categories to find one category's protection+settings on each page. Split hydration already resolves category context before+its loop. Background indexing also performs repeated hydration reads; audit+their role before removing them because they may observe concurrent progress.++- [x] Resolve immutable mapping context once per safe hydration scope or use a+ targeted DAO lookup instead of loading all categories per page.+- [x] Establish how edits/protection changes become visible during a long request.+ Retain provider/category locks and generation checks; refresh mutable protection+ at commit if required by existing behavior. Do not cache it across requests.+- [x] Audit repeated hydration/count/category lookups and avoid only those that+ have equivalent authoritative in-memory state inside the same locked scope.+- [x] Keep row writes, catalog-entry ordering, and successful-page checkpoint in+ one transaction. For background operations, inspect transaction boundaries+ before changing batching; prevent checkpoints advancing ahead of durable rows.+- [x] Preserve stable IDs, favorites, watch progress, protection, and duplicate+ rules. Use batch DAO operations where existing page methods already support them.++Acceptance: equivalent persisted content and checkpoint behavior with fewer+redundant lookups, asserted through fake call counts and Room state checks.++## V3 — Evaluate bounded background fetch/write overlap++Priority: after V1/V2. Status: evaluated; retain the bounded category windows.++Background indexing currently awaits all results in a bounded category window,+then validates and persists successful pages. This is already bounded; replacing+it is justified only if a small pipeline simplifies useful overlap without+weakening ordering, scheduling, or retry behavior.++- [x] Document category/duplicate precedence and page transaction ownership first.+- [x] Decide whether to retain windows or use admitted fetches feeding a single+ writer through a bounded queue. Record the decision and reason in this document.+- [ ] If adopted, keep pages sequential within each category, preserve category+ precedence independently of completion order, and bound any reorder buffer.+- [ ] Include producer, queue, writer, mapped rows, and active request responses+ in retained-memory accounting; bound row/byte payloads explicitly.+- [ ] Release network permits before waiting on writer backpressure. Verify the+ single-permit case, stress downgrade, cancellation, and authentication retry.+- [ ] Advance each checkpoint only after its page commit. Respect slice deadlines,+ interactive priority, cooldowns, and durable continuation without losing pages.++Acceptance: failure in one category cannot corrupt another; cancellation joins+all work; committed pages resume correctly; queue pressure cannot block a portal+permit needed by the consumer. If retained windows are the better fit, mark this+stage complete with that decision rather than adding concurrency for its own sake.++## V4 — Conditional direct VOD page decoding++Priority: optional follow-up. Status: evaluated and deferred.++VOD pages already bound typical response size. A direct decoder may avoid trees,+but the live reader is not a drop-in replacement for movie and series metadata.++- [x] Audit all retained fields consumed by movie, native-series, and classified+ VOD mappers, including playback descriptors and mixed item classification.+- [x] Decide whether direct decoding is warranted after V1-V3; record the decision.+- [ ] If adopted, preserve pagination metadata, wrappers/keyed shapes, aliases,+ coercion, duplicate keys, portal errors, malformed/truncated-document semantics,+ and cancellation. Keep generic detail/episode/guide decoding outside this scope.+- [ ] Retain an internal legacy comparison path until differential fixtures pass;+ do not add a user-facing decoder switch.++Acceptance: equivalent item fields, classification, ordering, and pagination+evidence. A malformed response must never become complete coverage.++## Wildcard policy++Do not broaden wildcard use by default in this plan. Existing limited support+remains authoritative. Wider catalog-wide pagination needs separate evidence of+complete coverage, correct item categories, hidden/protected-scope behavior,+mixed movie/series classification, and safe pruning before replacing category+requests. A returned list alone is not proof of those properties.++## Validation and completion tracking++Extend focused tests using call counts, coroutine barriers, and persisted state.+Do not use elapsed-time performance assertions.++- [x] V1 empty-first-page retry call counts and real page receipt verified.+- [x] V2 targeted protection lookup and transaction placement verified.+- [x] V3 decision documented; bounded windows retained, no pipeline adopted.+- [x] V4 decision documented; direct decoder deferred.+- [ ] Split and unified VOD, mixed movie/series, native and derived series verified.+- [ ] Empty/repeated/changing-total/truncated pages and page limits verified.+- [ ] Retry after committed pages resumes correctly; failed attempts do not advance+ checkpoints or delete verified rows.+- [x] Room verifies page ordering, stable identity, favorites, protection, watch+ progress, and successful-page coverage checkpoints.+- [ ] Room rollback, search updates, and coverage-safe pruning verified.+- [ ] Add Provider deferral, interactive OPEN/NEXT_PAGE/COMPLETE, background+ continuation, edit/supersession, cancellation, restart, and deletion verified.+- [x] Focused unit/instrumentation checks and app build pass.+- [ ] Real-provider VOD browsing, continuation, and representative movie/series+ playback verified where changed; unavailable access recorded as a validation gap.+- [ ] If shared live playback behavior is touched, required sustained multi-channel+ validation from `AGENTS.md` completed; build/synthetic tests do not substitute.+- [x] Implementation notes list completed stages, evidence, and remaining gaps.++Implement V1, then V2. Resolve V3/V4 decisions before expanding scope. Update+checkboxes as work lands; preserve unrelated dirty changes and existing live work.diff --git a/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.md b/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.mdnew file mode 100644index 00000000..538a4841--- /dev/null+++ b/docs/STALKER_VOD_V1_V2_IMPLEMENTATION.md@@ -0,0 +1,87 @@+# Stalker VOD V1/V2 implementation++Implemented 2026-10-10. Covers V1/V2 and the conditional V3/V4 decisions in+[the VOD improvement plan](STALKER_VOD_IMPROVEMENT_PLAN.md).++## V1: bounded empty-first-page recovery++Production background indexing now retries only the requested first page when+that page succeeds with no items. The retry uses the existing paged provider+route and returns its original page number, total-page count, advertised totals,+truncation state, and termination reason. The old recovery called+`getVodStreams`/`getSeriesList`, which used the same `get_ordered_list` requests+but accumulated a complete category and then represented it as page 1 of 1.++The retained compatibility behavior is the extra request after an empty first+response, which can recover a transient empty response. For Series, each paged+attempt still prefers the native series route and falls back to one VOD page+filtered by `is_series`; split VOD still uses the classified page path, preserving+movies and VOD-derived series. Existing provider tests cover mixed classification+and page order.++An error from the retry now propagates to the index executor, so it cannot turn+the original empty response into successful coverage. Cancellation unwinds+before any row write or successful-page checkpoint. The page result is committed+through the existing page flow; subsequent page errors preserve already committed+rows and resume from their durable checkpoint. Public list-returning provider+contracts remain available, but summary ingestion no longer calls them.++No category staging layer was needed: this recovery no longer performs a+complete-category attempt or emits rows while a request is in flight. It consumes+one normal paged response, so existing page anomaly checks and background slice+continuation remain authoritative.++## V2: page-local category work++Unified hydration no longer loads every VOD category to find one category's+protection bit. `CategoryDao` now has a targeted provider/type/category lookup.+Hydration reads that mutable flag inside the same Room transaction that writes+movie/series rows, replaces ordered catalog entries, counts persisted entries,+and writes the successful-page checkpoint. A protection edit made while the+network request is running is therefore read at commit time; protection is not+cached across pages or requests.++Split hydration already resolves the movie category before its page loop. Its+series/category counts and page checkpoint reads still affect eligibility,+native-series precedence, or persisted progress, so they remain. Background+indexing reloads hydration at window admission and after the slice to account for+durable progress and concurrent workers. Summary rows commit before their+successful-page checkpoint is advanced; a crash in between replays an idempotent+page rather than skipping uncommitted data.++## V3/V4 decisions++V3 keeps the existing bounded fetch windows. `awaitAll` preserves the requested+category order, pages remain sequential per category, and the writer processes+the validated window in that order. This is the current duplicate-precedence and+checkpoint ownership rule. A queue pipeline would add retained payloads,+backpressure, and portal-permit coordination without a correctness need, so no+fetch/write overlap was added.++V4 defers direct VOD decoding. Movie, native-series, and classified VOD mapping+consume different metadata and playback descriptors, and the live decoder cannot+stand in for those field contracts. V1 no longer needs a whole-category list, so+the separate decoder work is not required for this change.++## Validation++- Focused unit run passed:+ `:data:testDebugUnitTest --tests '*SyncManagerTest' --tests '*VodCategoryHydrationCoordinatorTest' --tests '*StalkerProviderTest'`.+ It covers empty-first-page retry call counts, actual page provenance, no+ whole-list fallback call, and targeted protection lookup inside the commit+ transaction.+- Room instrumentation run passed:+ `:data:connectedDebugAndroidTest` with+ `-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StalkerVodHydrationIntegrationTest`+ passed on the `Television_4K_2(AVD) - 16` emulator. It covers mixed+ movie/series page order, category protection, stable movie IDs, favorites,+ watch progress, and the completed-page checkpoint.+- App debug build and `git diff --check` passed. The diff check emitted only+ existing working-tree LF/CRLF normalization warnings.+- Real-provider VOD browsing and representative playback: not available in this+ workspace; record as a validation gap.+- Split/unified end-to-end behavior, retry failure after earlier committed pages,+ rollback, search updates, safe pruning, cancellation/restart, and provider edit+ or deletion behavior were not covered by these focused checks.+- No live playback path was changed. No before/after measurements or performance+ benchmark suite was run.