FTA7700 commited on
Commit
ef14e02
·
1 Parent(s): 6512c5c

Add live purge feature: catalogs + library, sourced from Stremio account API

Browse files
api/src/cache/mod.rs CHANGED
@@ -1,4 +1,4 @@
1
- use std::path::{Path, PathBuf};
2
  use std::time::{Instant, SystemTime};
3
 
4
  use sea_orm::*;
@@ -607,3 +607,29 @@ mod tests {
607
  assert!(!is_leap(2023)); // not divisible by 4
608
  }
609
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::path::{Path, PathBuf};
2
  use std::time::{Instant, SystemTime};
3
 
4
  use sea_orm::*;
 
607
  assert!(!is_leap(2023)); // not divisible by 4
608
  }
609
  }
610
+
611
+ /// Deletes every `image_meta` row whose `cache_key` starts with any of the
612
+ /// given prefixes (e.g. "imdb/tt1234567", "tmdb/movie-5678"). Since
613
+ /// `EXTERNAL_CACHE_ONLY=true` means the Postgres row *is* the cache, deleting
614
+ /// it is sufficient to force a fresh render on next request. Returns the
615
+ /// number of rows deleted.
616
+ pub async fn purge_by_id_prefixes(
617
+ db: &sea_orm::DatabaseConnection,
618
+ prefixes: &[String],
619
+ ) -> Result<u64, AppError> {
620
+ use crate::entity::image_meta;
621
+ use sea_orm::{ColumnTrait, Condition, QueryFilter, EntityTrait};
622
+ if prefixes.is_empty() {
623
+ return Ok(0);
624
+ }
625
+ let mut cond = Condition::any();
626
+ for p in prefixes {
627
+ cond = cond.add(image_meta::Column::CacheKey.starts_with(p.as_str()));
628
+ }
629
+ let res = image_meta::Entity::delete_many()
630
+ .filter(cond)
631
+ .exec(db)
632
+ .await
633
+ .map_err(|e| AppError::DbError(e.to_string()))?;
634
+ Ok(res.rows_affected)
635
+ }
api/src/config.rs CHANGED
@@ -21,6 +21,14 @@ pub struct Config {
21
  pub external_cache_only: bool,
22
  pub free_key_enabled: Option<bool>,
23
  pub disable_public_pages: bool,
 
 
 
 
 
 
 
 
24
  }
25
 
26
  impl std::fmt::Debug for Config {
@@ -45,6 +53,11 @@ impl std::fmt::Debug for Config {
45
  .field("external_cache_only", &self.external_cache_only)
46
  .field("free_key_enabled", &self.free_key_enabled)
47
  .field("disable_public_pages", &self.disable_public_pages)
 
 
 
 
 
48
  .finish()
49
  }
50
  }
@@ -64,6 +77,34 @@ fn optional_secret(key: &str) -> Option<String> {
64
  .filter(|s| !s.is_empty())
65
  }
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  impl Config {
68
  pub fn from_env() -> Self {
69
  let config = Self {
@@ -109,6 +150,8 @@ impl Config {
109
  disable_public_pages: env::var("DISABLE_PUBLIC_PAGES")
110
  .map(|v| v == "true" || v == "1")
111
  .unwrap_or(false),
 
 
112
  };
113
 
114
  if config.omdb_api_key.is_none()
 
21
  pub external_cache_only: bool,
22
  pub free_key_enabled: Option<bool>,
23
  pub disable_public_pages: bool,
24
+ pub stremio_accounts: Vec<StremioAccount>,
25
+ pub stremio_purge_exclude_addons: Vec<String>,
26
+ }
27
+
28
+ #[derive(Clone)]
29
+ pub struct StremioAccount {
30
+ pub label: String,
31
+ pub auth_key: String,
32
  }
33
 
34
  impl std::fmt::Debug for Config {
 
53
  .field("external_cache_only", &self.external_cache_only)
54
  .field("free_key_enabled", &self.free_key_enabled)
55
  .field("disable_public_pages", &self.disable_public_pages)
56
+ .field(
57
+ "stremio_accounts",
58
+ &self.stremio_accounts.iter().map(|a| a.label.clone()).collect::<Vec<_>>(),
59
+ )
60
+ .field("stremio_purge_exclude_addons", &self.stremio_purge_exclude_addons)
61
  .finish()
62
  }
63
  }
 
77
  .filter(|s| !s.is_empty())
78
  }
79
 
80
+ /// Parses up to 10 numbered Stremio account pairs:
81
+ /// STREMIO_ACCOUNT_USER_{n} and STREMIO_ACCOUNT_AUTHKEY_{n} (n = 1..10).
82
+ /// Both must be present (and non-empty) for slot n to count.
83
+ fn parse_stremio_accounts() -> Vec<StremioAccount> {
84
+ let mut accounts = Vec::new();
85
+ for i in 1..=10 {
86
+ let label = optional_secret(&format!("STREMIO_ACCOUNT_USER_{i}"));
87
+ let auth_key = optional_secret(&format!("STREMIO_ACCOUNT_AUTHKEY_{i}"));
88
+ if let (Some(label), Some(auth_key)) = (label, auth_key) {
89
+ accounts.push(StremioAccount { label, auth_key });
90
+ }
91
+ }
92
+ accounts
93
+ }
94
+
95
+ /// Parses a comma-separated list env var into trimmed, non-empty entries.
96
+ fn parse_exclude_list(key: &str) -> Vec<String> {
97
+ env::var(key)
98
+ .ok()
99
+ .map(|v| {
100
+ v.split(',')
101
+ .map(|s| s.trim().to_string())
102
+ .filter(|s| !s.is_empty())
103
+ .collect()
104
+ })
105
+ .unwrap_or_default()
106
+ }
107
+
108
  impl Config {
109
  pub fn from_env() -> Self {
110
  let config = Self {
 
150
  disable_public_pages: env::var("DISABLE_PUBLIC_PAGES")
151
  .map(|v| v == "true" || v == "1")
152
  .unwrap_or(false),
153
+ stremio_accounts: parse_stremio_accounts(),
154
+ stremio_purge_exclude_addons: parse_exclude_list("STREMIO_PURGE_EXCLUDE_ADDONS"),
155
  };
156
 
157
  if config.omdb_api_key.is_none()
api/src/handlers/admin.rs CHANGED
@@ -580,3 +580,115 @@ async fn fetch_logo_backdrop_image(
580
  bytes,
581
  ).into_response())
582
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  bytes,
581
  ).into_response())
582
  }
583
+
584
+ // --- Purge (catalogs + library, sourced live from configured Stremio accounts) ---
585
+
586
+ #[derive(Serialize)]
587
+ pub struct PurgeCatalogEntry {
588
+ pub account_label: String,
589
+ pub addon_name: String,
590
+ pub transport_url: String,
591
+ pub catalog_id: String,
592
+ pub catalog_type: String,
593
+ pub catalog_name: String,
594
+ }
595
+
596
+ #[derive(Serialize)]
597
+ pub struct PurgeSourcesResponse {
598
+ pub catalogs: Vec<PurgeCatalogEntry>,
599
+ pub library_accounts: Vec<String>,
600
+ }
601
+
602
+ pub async fn purge_sources(
603
+ State(state): State<Arc<AppState>>,
604
+ ) -> Result<Json<PurgeSourcesResponse>, AppError> {
605
+ let mut catalogs = Vec::new();
606
+ let mut library_accounts = Vec::new();
607
+
608
+ for account in &state.config.stremio_accounts {
609
+ library_accounts.push(account.label.clone());
610
+
611
+ let addons = crate::services::stremio_account::get_addon_collection(&state.http, &account.auth_key).await?;
612
+ let filtered = crate::services::stremio_account::filter_catalog_addons(
613
+ addons,
614
+ &state.config.stremio_purge_exclude_addons,
615
+ );
616
+
617
+ for addon in filtered {
618
+ for cat in &addon.manifest.catalogs {
619
+ let id = cat.get("id").and_then(|v| v.as_str()).unwrap_or_default().to_string();
620
+ let ctype = cat.get("type").and_then(|v| v.as_str()).unwrap_or_default().to_string();
621
+ if id.is_empty() || ctype.is_empty() {
622
+ continue;
623
+ }
624
+ let name = cat
625
+ .get("name")
626
+ .and_then(|v| v.as_str())
627
+ .map(|s| s.to_string())
628
+ .unwrap_or_else(|| format!("{} ({})", addon.manifest.name, ctype));
629
+
630
+ catalogs.push(PurgeCatalogEntry {
631
+ account_label: account.label.clone(),
632
+ addon_name: addon.manifest.name.clone(),
633
+ transport_url: addon.transport_url.clone(),
634
+ catalog_id: id,
635
+ catalog_type: ctype,
636
+ catalog_name: name,
637
+ });
638
+ }
639
+ }
640
+ }
641
+
642
+ Ok(Json(PurgeSourcesResponse { catalogs, library_accounts }))
643
+ }
644
+
645
+ #[derive(Deserialize)]
646
+ #[serde(tag = "scope", rename_all = "snake_case")]
647
+ pub enum PurgeRequest {
648
+ Catalog {
649
+ transport_url: String,
650
+ catalog_id: String,
651
+ catalog_type: String,
652
+ },
653
+ Library {
654
+ account_label: String,
655
+ },
656
+ }
657
+
658
+ #[derive(Serialize)]
659
+ pub struct PurgeResponse {
660
+ pub purged: u64,
661
+ }
662
+
663
+ pub async fn purge(
664
+ State(state): State<Arc<AppState>>,
665
+ Json(req): Json<PurgeRequest>,
666
+ ) -> Result<Json<PurgeResponse>, AppError> {
667
+ let prefixes: Vec<String> = match req {
668
+ PurgeRequest::Catalog { transport_url, catalog_id, catalog_type } => {
669
+ let ids = crate::services::stremio_account::fetch_catalog_ids(
670
+ &state.http,
671
+ &transport_url,
672
+ &catalog_type,
673
+ &catalog_id,
674
+ )
675
+ .await?;
676
+ ids.iter()
677
+ .flat_map(|id| crate::services::stremio_account::id_to_cache_prefixes(id, &catalog_type))
678
+ .collect()
679
+ }
680
+ PurgeRequest::Library { account_label } => {
681
+ let account = state
682
+ .config
683
+ .stremio_accounts
684
+ .iter()
685
+ .find(|a| a.label == account_label)
686
+ .ok_or_else(|| AppError::BadRequest(format!("unknown stremio account: {account_label}")))?;
687
+ let items = crate::services::stremio_account::get_library_items(&state.http, &account.auth_key).await?;
688
+ items.iter().map(|i| format!("imdb/{}", i.id)).collect()
689
+ }
690
+ };
691
+
692
+ let purged = cache::purge_by_id_prefixes(&state.db, &prefixes).await?;
693
+ Ok(Json(PurgeResponse { purged }))
694
+ }
api/src/lib.rs CHANGED
@@ -1,4 +1,4 @@
1
- pub mod cache;
2
  pub mod config;
3
  pub mod entity;
4
  pub mod error;
@@ -31,6 +31,7 @@ pub use routes::build_app;
31
  #[derive(Clone)]
32
  pub struct AppState {
33
  pub config: Config,
 
34
  pub tmdb: TmdbClient,
35
  pub omdb: Option<OmdbClient>,
36
  pub mdblist: Option<MdblistClient>,
 
1
+ pub mod cache;
2
  pub mod config;
3
  pub mod entity;
4
  pub mod error;
 
31
  #[derive(Clone)]
32
  pub struct AppState {
33
  pub config: Config,
34
+ pub http: reqwest::Client,
35
  pub tmdb: TmdbClient,
36
  pub omdb: Option<OmdbClient>,
37
  pub mdblist: Option<MdblistClient>,
api/src/main.rs CHANGED
@@ -285,6 +285,7 @@ async fn main() {
285
  let pending_last_used: Arc<DashMap<i32, ()>> = Arc::new(DashMap::new());
286
 
287
  let state = Arc::new(AppState {
 
288
  tmdb: TmdbClient::new(config.tmdb_api_key.clone(), http),
289
  omdb,
290
  mdblist,
 
285
  let pending_last_used: Arc<DashMap<i32, ()>> = Arc::new(DashMap::new());
286
 
287
  let state = Arc::new(AppState {
288
+ http: http.clone(),
289
  tmdb: TmdbClient::new(config.tmdb_api_key.clone(), http),
290
  omdb,
291
  mdblist,
api/src/routes/admin.rs CHANGED
@@ -29,4 +29,6 @@ pub fn admin_routes() -> Router<Arc<AppState>> {
29
  "/api/admin/settings",
30
  get(handlers::admin::get_settings).put(handlers::admin::update_settings),
31
  )
 
 
32
  }
 
29
  "/api/admin/settings",
30
  get(handlers::admin::get_settings).put(handlers::admin::update_settings),
31
  )
32
+ .route("/api/admin/purge/sources", get(handlers::admin::purge_sources))
33
+ .route("/api/admin/purge", post(handlers::admin::purge))
34
  }
api/src/services/mod.rs CHANGED
@@ -5,6 +5,7 @@ pub mod mdblist;
5
  pub mod omdb;
6
  pub mod ratings;
7
  pub mod retry;
 
8
  pub mod tmdb;
9
  pub mod trakt;
10
  pub mod validation;
 
5
  pub mod omdb;
6
  pub mod ratings;
7
  pub mod retry;
8
+ pub mod stremio_account;
9
  pub mod tmdb;
10
  pub mod trakt;
11
  pub mod validation;
api/src/services/stremio_account.rs ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use serde::Deserialize;
2
+ use crate::error::AppError;
3
+
4
+ #[derive(Debug, Clone, Deserialize)]
5
+ pub struct AddonManifest {
6
+ pub name: String,
7
+ #[serde(default)]
8
+ pub catalogs: Vec<serde_json::Value>,
9
+ }
10
+
11
+ #[derive(Debug, Clone, Deserialize)]
12
+ pub struct AddonEntry {
13
+ pub manifest: AddonManifest,
14
+ #[serde(rename = "transportUrl")]
15
+ pub transport_url: String,
16
+ }
17
+
18
+ #[derive(Debug, Deserialize)]
19
+ struct AddonCollectionResult {
20
+ addons: Vec<AddonEntry>,
21
+ }
22
+
23
+ #[derive(Debug, Deserialize)]
24
+ struct StremioApiError {
25
+ message: String,
26
+ #[serde(default)]
27
+ code: i64,
28
+ }
29
+
30
+ #[derive(Debug, Deserialize)]
31
+ struct AddonCollectionResponse {
32
+ result: Option<AddonCollectionResult>,
33
+ error: Option<StremioApiError>,
34
+ }
35
+
36
+ /// Fetches the full installed-addon collection for a Stremio account.
37
+ pub async fn get_addon_collection(
38
+ client: &reqwest::Client,
39
+ auth_key: &str,
40
+ ) -> Result<Vec<AddonEntry>, AppError> {
41
+ let body = serde_json::json!({ "authKey": auth_key, "update": false });
42
+ let resp: AddonCollectionResponse = client
43
+ .post("https://api.strem.io/api/addonCollectionGet")
44
+ .json(&body)
45
+ .send()
46
+ .await
47
+ .map_err(|e| AppError::Other(format!("stremio addonCollectionGet request failed: {e}")))?
48
+ .json()
49
+ .await
50
+ .map_err(|e| AppError::Other(format!("stremio addonCollectionGet parse failed: {e}")))?;
51
+
52
+ if let Some(err) = resp.error {
53
+ return Err(AppError::Other(format!(
54
+ "stremio API error {}: {}",
55
+ err.code, err.message
56
+ )));
57
+ }
58
+
59
+ Ok(resp.result.map(|r| r.addons).unwrap_or_default())
60
+ }
61
+
62
+ /// Keeps only addons that expose at least one catalog, excluding any whose
63
+ /// manifest name matches (case-insensitively) an entry in `exclude_names`.
64
+ pub fn filter_catalog_addons(addons: Vec<AddonEntry>, exclude_names: &[String]) -> Vec<AddonEntry> {
65
+ addons
66
+ .into_iter()
67
+ .filter(|a| !a.manifest.catalogs.is_empty())
68
+ .filter(|a| {
69
+ !exclude_names
70
+ .iter()
71
+ .any(|ex| ex.eq_ignore_ascii_case(&a.manifest.name))
72
+ })
73
+ .collect()
74
+ }
75
+
76
+ #[derive(Debug, Clone, Deserialize)]
77
+ pub struct LibraryItem {
78
+ #[serde(rename = "_id")]
79
+ pub id: String,
80
+ #[serde(default)]
81
+ pub removed: bool,
82
+ #[serde(default)]
83
+ pub name: String,
84
+ #[serde(rename = "type", default)]
85
+ pub item_type: String,
86
+ }
87
+
88
+ #[derive(Debug, Deserialize)]
89
+ struct DatastoreGetResponse {
90
+ result: Option<Vec<LibraryItem>>,
91
+ error: Option<StremioApiError>,
92
+ }
93
+
94
+ /// Fetches the account's library items, pre-filtered to non-removed entries
95
+ /// with a real IMDb id (`tt...`) — the only ones that can map to an
96
+ /// `image_meta` cache entry.
97
+ pub async fn get_library_items(
98
+ client: &reqwest::Client,
99
+ auth_key: &str,
100
+ ) -> Result<Vec<LibraryItem>, AppError> {
101
+ let body = serde_json::json!({
102
+ "authKey": auth_key,
103
+ "collection": "libraryItem",
104
+ "ids": [],
105
+ "all": true
106
+ });
107
+ let resp: DatastoreGetResponse = client
108
+ .post("https://api.strem.io/api/datastoreGet")
109
+ .json(&body)
110
+ .send()
111
+ .await
112
+ .map_err(|e| AppError::Other(format!("stremio datastoreGet request failed: {e}")))?
113
+ .json()
114
+ .await
115
+ .map_err(|e| AppError::Other(format!("stremio datastoreGet parse failed: {e}")))?;
116
+
117
+ if let Some(err) = resp.error {
118
+ return Err(AppError::Other(format!(
119
+ "stremio API error {}: {}",
120
+ err.code, err.message
121
+ )));
122
+ }
123
+
124
+ let items = resp.result.unwrap_or_default();
125
+ Ok(items
126
+ .into_iter()
127
+ .filter(|i| !i.removed)
128
+ .filter(|i| i.id.starts_with("tt"))
129
+ .collect())
130
+ }
131
+ #[derive(Debug, Deserialize)]
132
+ pub struct CatalogMeta {
133
+ pub id: String,
134
+ #[serde(rename = "type", default)]
135
+ pub meta_type: String,
136
+ }
137
+
138
+ #[derive(Debug, Deserialize)]
139
+ struct CatalogResponse {
140
+ #[serde(default)]
141
+ metas: Vec<CatalogMeta>,
142
+ }
143
+
144
+ /// Fetches every meta ID currently in a catalog, paginating via Stremio's
145
+ /// `skip=` addon protocol until a short/empty page is returned.
146
+ pub async fn fetch_catalog_ids(
147
+ client: &reqwest::Client,
148
+ transport_url: &str,
149
+ catalog_type: &str,
150
+ catalog_id: &str,
151
+ ) -> Result<Vec<String>, AppError> {
152
+ let base = transport_url
153
+ .trim_end_matches("manifest.json")
154
+ .trim_end_matches('/');
155
+ let mut all_ids = Vec::new();
156
+ let mut skip = 0usize;
157
+ loop {
158
+ let url = if skip == 0 {
159
+ format!("{base}/catalog/{catalog_type}/{catalog_id}.json")
160
+ } else {
161
+ format!("{base}/catalog/{catalog_type}/{catalog_id}/skip={skip}.json")
162
+ };
163
+ let resp: CatalogResponse = client
164
+ .get(&url)
165
+ .send()
166
+ .await
167
+ .map_err(|e| AppError::Other(format!("catalog fetch failed ({url}): {e}")))?
168
+ .json()
169
+ .await
170
+ .map_err(|e| AppError::Other(format!("catalog parse failed ({url}): {e}")))?;
171
+ let count = resp.metas.len();
172
+ if count == 0 {
173
+ break;
174
+ }
175
+ all_ids.extend(resp.metas.into_iter().map(|m| m.id));
176
+ if count < 100 {
177
+ break;
178
+ }
179
+ skip += count;
180
+ if skip > 5000 {
181
+ break;
182
+ }
183
+ }
184
+ Ok(all_ids)
185
+ }
186
+
187
+ /// Maps a raw Stremio catalog meta ID to the `image_meta.cache_key` prefix(es)
188
+ /// that correspond to it. Real IMDb IDs (`tt...`) map to `imdb/tt...`.
189
+ /// TMDB-native IDs (`tmdb:12345`) map to `tmdb/movie-12345` or
190
+ /// `tmdb/series-12345` depending on catalog type. Unknown ID namespaces
191
+ /// (e.g. `kitsu:`) return no prefixes -- nothing safe to purge for those.
192
+ pub fn id_to_cache_prefixes(raw_id: &str, catalog_type: &str) -> Vec<String> {
193
+ if raw_id.starts_with("tt") {
194
+ return vec![format!("imdb/{raw_id}")];
195
+ }
196
+ if let Some(num) = raw_id.strip_prefix("tmdb:") {
197
+ let kind = if catalog_type == "series" { "series" } else { "movie" };
198
+ return vec![format!("tmdb/{kind}-{num}")];
199
+ }
200
+ vec![]
201
+ }
supabase/.temp/gotrue-version ADDED
@@ -0,0 +1 @@
 
 
1
+ v2.193.1
supabase/.temp/linked-project.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"ref":"gnznbigjczikqhdwcctk","name":"FTA7700's Project","organization_id":"gscvtksfqynugvcakfuj","organization_slug":"gscvtksfqynugvcakfuj"}
supabase/.temp/pooler-url ADDED
@@ -0,0 +1 @@
 
 
1
+ postgresql://postgres.gnznbigjczikqhdwcctk@aws-0-eu-central-1.pooler.supabase.com:5432/postgres
supabase/.temp/postgres-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 17.6.1.141
supabase/.temp/project-ref ADDED
@@ -0,0 +1 @@
 
 
1
+ gnznbigjczikqhdwcctk
supabase/.temp/rest-version ADDED
@@ -0,0 +1 @@
 
 
1
+ v14.5
supabase/.temp/storage-migration ADDED
@@ -0,0 +1 @@
 
 
1
+ optimize-existing-functions-again
supabase/.temp/storage-version ADDED
@@ -0,0 +1 @@
 
 
1
+ v1.67.8
web/src/components/AppSidebar.vue CHANGED
@@ -2,7 +2,7 @@
2
  import { version } from '../../package.json'
3
  import { useRoute, useRouter } from 'vue-router'
4
  import { useAuthStore } from '@/stores/auth'
5
- import { LayoutDashboard, Image, Stamp, Wallpaper, Clapperboard, KeyRound, Settings, LogOut } from 'lucide-vue-next'
6
  import {
7
  Sidebar,
8
  SidebarContent,
@@ -28,6 +28,7 @@ const items = [
28
  { title: 'Logos', icon: Stamp, to: '/admin/logos' },
29
  { title: 'Backdrops', icon: Wallpaper, to: '/admin/backdrops' },
30
  { title: 'Episodes', icon: Clapperboard, to: '/admin/episodes' },
 
31
  { title: 'API Keys', icon: KeyRound, to: '/admin/keys' },
32
  { title: 'Settings', icon: Settings, to: '/admin/settings' },
33
  ]
 
2
  import { version } from '../../package.json'
3
  import { useRoute, useRouter } from 'vue-router'
4
  import { useAuthStore } from '@/stores/auth'
5
+ import { LayoutDashboard, Image, Stamp, Wallpaper, Clapperboard, KeyRound, Settings, LogOut, Trash2 } from 'lucide-vue-next'
6
  import {
7
  Sidebar,
8
  SidebarContent,
 
28
  { title: 'Logos', icon: Stamp, to: '/admin/logos' },
29
  { title: 'Backdrops', icon: Wallpaper, to: '/admin/backdrops' },
30
  { title: 'Episodes', icon: Clapperboard, to: '/admin/episodes' },
31
+ { title: 'Purge', icon: Trash2, to: '/admin/purge' },
32
  { title: 'API Keys', icon: KeyRound, to: '/admin/keys' },
33
  { title: 'Settings', icon: Settings, to: '/admin/settings' },
34
  ]
web/src/lib/api.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { useAuthStore } from '@/stores/auth'
2
 
3
  const BASE_URL = import.meta.env.VITE_API_URL || ''
4
 
@@ -157,6 +157,11 @@ export const adminApi = {
157
  get(buildUrl('/api/admin/preview/backdrop', { ratings_limit: ratingsLimit, ratings_order: ratingsOrder, ratings_exclude: ratingsExclude, badge_style: badgeStyle, label_style: labelStyle, badge_size: badgeSize, position, badge_direction: badgeDirection, badge_shape: badgeShape, badge_background: badgeBackground, edge_inset_x: edgeInsetX, edge_inset_y: edgeInsetY, id_type: idType, id_value: idValue })),
158
  previewEpisode: (ratingsLimit: number, ratingsOrder: string, badgeStyle?: string, labelStyle?: string, badgeSize?: string, position?: string, badgeDirection?: string, blur?: boolean, ratingsExclude?: string, badgeShape?: string, badgeBackground?: string, idType?: string, idValue?: string): Promise<Response> =>
159
  get(buildUrl('/api/admin/preview/episode', { ratings_limit: ratingsLimit, ratings_order: ratingsOrder, ratings_exclude: ratingsExclude, badge_style: badgeStyle, label_style: labelStyle, badge_size: badgeSize, position, badge_direction: badgeDirection, blur: blur ? 'true' : undefined, badge_shape: badgeShape, badge_background: badgeBackground, id_type: idType, id_value: idValue })),
 
 
 
 
 
160
  }
161
 
162
  // --- Self-service API (API key session JWT auth) ---
 
1
+ import { useAuthStore } from '@/stores/auth'
2
 
3
  const BASE_URL = import.meta.env.VITE_API_URL || ''
4
 
 
157
  get(buildUrl('/api/admin/preview/backdrop', { ratings_limit: ratingsLimit, ratings_order: ratingsOrder, ratings_exclude: ratingsExclude, badge_style: badgeStyle, label_style: labelStyle, badge_size: badgeSize, position, badge_direction: badgeDirection, badge_shape: badgeShape, badge_background: badgeBackground, edge_inset_x: edgeInsetX, edge_inset_y: edgeInsetY, id_type: idType, id_value: idValue })),
158
  previewEpisode: (ratingsLimit: number, ratingsOrder: string, badgeStyle?: string, labelStyle?: string, badgeSize?: string, position?: string, badgeDirection?: string, blur?: boolean, ratingsExclude?: string, badgeShape?: string, badgeBackground?: string, idType?: string, idValue?: string): Promise<Response> =>
159
  get(buildUrl('/api/admin/preview/episode', { ratings_limit: ratingsLimit, ratings_order: ratingsOrder, ratings_exclude: ratingsExclude, badge_style: badgeStyle, label_style: labelStyle, badge_size: badgeSize, position, badge_direction: badgeDirection, blur: blur ? 'true' : undefined, badge_shape: badgeShape, badge_background: badgeBackground, id_type: idType, id_value: idValue })),
160
+ getPurgeSources: (): Promise<Response> => get('/api/admin/purge/sources'),
161
+ runPurgeCatalog: (transportUrl: string, catalogId: string, catalogType: string): Promise<Response> =>
162
+ post('/api/admin/purge', { scope: 'catalog', transport_url: transportUrl, catalog_id: catalogId, catalog_type: catalogType }),
163
+ runPurgeLibrary: (accountLabel: string): Promise<Response> =>
164
+ post('/api/admin/purge', { scope: 'library', account_label: accountLabel }),
165
  }
166
 
167
  // --- Self-service API (API key session JWT auth) ---
web/src/router/index.ts CHANGED
@@ -109,6 +109,12 @@ const router = createRouter({
109
  component: () => import('@/views/EpisodesView.vue'),
110
  meta: { title: 'Episodes' },
111
  },
 
 
 
 
 
 
112
  {
113
  path: 'keys',
114
  name: 'keys',
 
109
  component: () => import('@/views/EpisodesView.vue'),
110
  meta: { title: 'Episodes' },
111
  },
112
+ {
113
+ path: 'purge',
114
+ name: 'purge',
115
+ component: () => import('@/views/PurgeView.vue'),
116
+ meta: { title: 'Purge' },
117
+ },
118
  {
119
  path: 'keys',
120
  name: 'keys',
web/src/views/PurgeView.vue ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import { ref, computed } from 'vue'
3
+ import { useQuery } from '@tanstack/vue-query'
4
+ import { Loader2, Trash2 } from 'lucide-vue-next'
5
+ import { adminApi } from '@/lib/api'
6
+ import { Button } from '@/components/ui/button'
7
+ import { Skeleton } from '@/components/ui/skeleton'
8
+ import {
9
+ Card,
10
+ CardContent,
11
+ CardHeader,
12
+ CardTitle,
13
+ CardDescription,
14
+ } from '@/components/ui/card'
15
+ import {
16
+ Dialog,
17
+ DialogContent,
18
+ DialogHeader,
19
+ DialogTitle,
20
+ DialogFooter,
21
+ } from '@/components/ui/dialog'
22
+
23
+ interface CatalogEntry {
24
+ account_label: string
25
+ addon_name: string
26
+ transport_url: string
27
+ catalog_id: string
28
+ catalog_type: string
29
+ catalog_name: string
30
+ }
31
+
32
+ interface PurgeSourcesResponse {
33
+ catalogs: CatalogEntry[]
34
+ library_accounts: string[]
35
+ }
36
+
37
+ const { data, isPending, isFetching, refetch } = useQuery<PurgeSourcesResponse>({
38
+ queryKey: ['admin', 'purge-sources'],
39
+ queryFn: async () => {
40
+ const res = await adminApi.getPurgeSources()
41
+ if (!res.ok) throw new Error('Failed to fetch purge sources')
42
+ return res.json()
43
+ },
44
+ })
45
+
46
+ const confirmOpen = ref(false)
47
+ const confirmLabel = ref('')
48
+ const confirmAction = ref<null | (() => Promise<void>)>(null)
49
+ const purging = ref(false)
50
+ const resultMessage = ref('')
51
+
52
+ function askConfirm(label: string, action: () => Promise<void>) {
53
+ confirmLabel.value = label
54
+ confirmAction.value = action
55
+ resultMessage.value = ''
56
+ confirmOpen.value = true
57
+ }
58
+
59
+ async function runConfirmed() {
60
+ if (!confirmAction.value) return
61
+ purging.value = true
62
+ try {
63
+ await confirmAction.value()
64
+ } finally {
65
+ purging.value = false
66
+ }
67
+ }
68
+
69
+ function purgeCatalog(entry: CatalogEntry) {
70
+ askConfirm(`${entry.addon_name} — ${entry.catalog_name}`, async () => {
71
+ const res = await adminApi.runPurgeCatalog(entry.transport_url, entry.catalog_id, entry.catalog_type)
72
+ const body = await res.json()
73
+ resultMessage.value = res.ok
74
+ ? `Purged ${body.purged} cache ${body.purged === 1 ? 'entry' : 'entries'}.`
75
+ : `Error: ${body.error || 'purge failed'}`
76
+ if (res.ok) confirmOpen.value = false
77
+ })
78
+ }
79
+
80
+ function purgeLibrary(accountLabel: string) {
81
+ askConfirm(`Library — ${accountLabel}`, async () => {
82
+ const res = await adminApi.runPurgeLibrary(accountLabel)
83
+ const body = await res.json()
84
+ resultMessage.value = res.ok
85
+ ? `Purged ${body.purged} cache ${body.purged === 1 ? 'entry' : 'entries'}.`
86
+ : `Error: ${body.error || 'purge failed'}`
87
+ if (res.ok) confirmOpen.value = false
88
+ })
89
+ }
90
+
91
+ const groupedCatalogs = computed(() => {
92
+ if (!data.value) return []
93
+ const groups = new Map<string, CatalogEntry[]>()
94
+ for (const c of data.value.catalogs) {
95
+ const key = `${c.account_label} — ${c.addon_name}`
96
+ if (!groups.has(key)) groups.set(key, [])
97
+ groups.get(key)!.push(c)
98
+ }
99
+ return Array.from(groups.entries()).map(([groupName, catalogs]) => ({ groupName, catalogs }))
100
+ })
101
+ </script>
102
+
103
+ <template>
104
+ <div class="space-y-6">
105
+ <div class="flex justify-between items-center">
106
+ <p class="text-sm text-muted-foreground">
107
+ Purge buttons are generated live from each connected Stremio account's installed addons.
108
+ </p>
109
+ <Button variant="outline" size="sm" :disabled="isFetching" @click="refetch()">
110
+ <Loader2 v-if="isFetching" class="size-4 animate-spin mr-1" />
111
+ Refresh
112
+ </Button>
113
+ </div>
114
+
115
+ <div v-if="isPending" class="space-y-3">
116
+ <Skeleton v-for="i in 3" :key="i" class="h-24 w-full" />
117
+ </div>
118
+
119
+ <template v-else-if="data">
120
+ <Card v-if="data.library_accounts.length > 0">
121
+ <CardHeader>
122
+ <CardTitle>Library</CardTitle>
123
+ <CardDescription>Purge cache for titles saved in a Stremio account's Library.</CardDescription>
124
+ </CardHeader>
125
+ <CardContent class="flex flex-wrap gap-2">
126
+ <Button
127
+ v-for="label in data.library_accounts"
128
+ :key="label"
129
+ variant="outline"
130
+ @click="purgeLibrary(label)"
131
+ >
132
+ <Trash2 class="size-4 mr-1" />
133
+ Library — {{ label }}
134
+ </Button>
135
+ </CardContent>
136
+ </Card>
137
+
138
+ <Card v-for="group in groupedCatalogs" :key="group.groupName">
139
+ <CardHeader>
140
+ <CardTitle>{{ group.groupName }}</CardTitle>
141
+ </CardHeader>
142
+ <CardContent class="flex flex-wrap gap-2">
143
+ <Button
144
+ v-for="cat in group.catalogs"
145
+ :key="`${cat.catalog_type}-${cat.catalog_id}`"
146
+ variant="outline"
147
+ @click="purgeCatalog(cat)"
148
+ >
149
+ <Trash2 class="size-4 mr-1" />
150
+ {{ cat.catalog_name }}
151
+ </Button>
152
+ </CardContent>
153
+ </Card>
154
+
155
+ <p v-if="groupedCatalogs.length === 0 && data.library_accounts.length === 0" class="text-sm text-muted-foreground">
156
+ No catalog sources found. Configure at least one Stremio account (STREMIO_ACCOUNT_USER_1 / STREMIO_ACCOUNT_AUTHKEY_1).
157
+ </p>
158
+ </template>
159
+
160
+ <Dialog :open="confirmOpen" @update:open="(v: boolean) => { if (!v) confirmOpen = false }">
161
+ <DialogContent class="max-w-sm">
162
+ <DialogHeader>
163
+ <DialogTitle>Purge cache?</DialogTitle>
164
+ </DialogHeader>
165
+ <p class="text-sm">
166
+ This will delete cached images for every title currently in
167
+ <strong>{{ confirmLabel }}</strong>. They will be freshly rendered on next request.
168
+ </p>
169
+ <p v-if="resultMessage" class="text-sm font-medium">{{ resultMessage }}</p>
170
+ <DialogFooter>
171
+ <Button variant="outline" @click="confirmOpen = false" :disabled="purging">Cancel</Button>
172
+ <Button variant="destructive" @click="runConfirmed" :disabled="purging">
173
+ <Loader2 v-if="purging" class="size-4 animate-spin mr-1" />
174
+ Purge
175
+ </Button>
176
+ </DialogFooter>
177
+ </DialogContent>
178
+ </Dialog>
179
+ </div>
180
+ </template>