Skip to content

Commit 6eb8479

Browse files
Merge branch 'main' of github.com:TimilsinaBimal/Watchly into dev
2 parents 25da74e + 4f0f930 commit 6eb8479

File tree

5 files changed

+34
-9
lines changed

5 files changed

+34
-9
lines changed

app/api/endpoints/tokens.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ async def create_token(payload: TokenRequest, request: Request) -> TokenResponse
142142
)
143143
except Exception as exc: # pragma: no cover - remote dependency
144144
logger.error(f"[{redact_token(token)}] Initial catalog refresh failed: {{}}", exc, exc_info=True)
145-
await token_store.delete_token(token)
145+
await token_store.delete_token(token=token)
146146
raise HTTPException(
147147
status_code=502,
148148
detail="Credentials verified, but Watchly couldn't refresh your catalogs yet. Please try again.",

app/core/app.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ async def lifespan(app: FastAPI):
8787
async def configure_page(token: str | None = None):
8888
index_path = static_dir / "index.html"
8989
if index_path.exists():
90-
html_content = index_path.read_text(encoding="utf-8")
90+
with open(index_path, encoding="utf-8") as file:
91+
html_content = file.read()
9192
dynamic_announcement = os.getenv("ANNOUNCEMENT_HTML")
9293
if dynamic_announcement is None:
9394
dynamic_announcement = settings.ANNOUNCEMENT_HTML

app/services/catalog_updater.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,27 @@
1818

1919

2020
async def refresh_catalogs_for_credentials(
21-
credentials: dict[str, Any], user_settings: UserSettings | None = None, auth_key: str | None = None
21+
credentials: dict[str, Any],
22+
user_settings: UserSettings | None = None,
23+
auth_key: str | None = None,
24+
key: str | None = None,
2225
) -> bool:
2326
"""Regenerate catalogs for the provided credentials and push them to Stremio."""
2427
stremio_service = StremioService(
2528
username=credentials.get("username") or "",
2629
password=credentials.get("password") or "",
2730
auth_key=auth_key or credentials.get("authKey"),
2831
)
32+
# check if user has addon installed or not
33+
try:
34+
addon_installed = await stremio_service.is_addon_installed()
35+
if not addon_installed:
36+
logger.info("User has not installed addon. Removing token from redis")
37+
await token_store.delete_token(key=key)
38+
return True
39+
except Exception as e:
40+
logger.exception(f"Failed to check if addon is installed: {e}")
41+
2942
try:
3043
library_items = await stremio_service.get_library_items()
3144
dynamic_catalog_service = DynamicCatalogService(stremio_service=stremio_service)
@@ -111,7 +124,7 @@ async def _update_safe(key: str, payload: dict[str, Any]) -> None:
111124

112125
async with sem:
113126
try:
114-
updated = await refresh_catalogs_for_credentials(payload)
127+
updated = await refresh_catalogs_for_credentials(payload, key=key)
115128
logger.info(
116129
f"Background refresh for {self._mask_key(key)} completed (updated={updated})",
117130
)

app/services/stremio_service.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,8 @@ async def get_library_items(self) -> dict[str, list[dict]]:
194194
]
195195
logger.info(f"Filtered {len(watched_items)} watched library items")
196196

197-
# Sort watched items by modification time (most recent first)
198-
watched_items.sort(key=lambda x: x.get("_mtime", ""), reverse=True)
197+
# Sort watched items by watched time (most recent first)
198+
watched_items.sort(key=lambda x: x.get("state", {}).get("lastWatched", ""), reverse=True)
199199

200200
# is_loved only until we find 10 movies and 10 series
201201
loved_items = []
@@ -307,3 +307,11 @@ async def update_catalogs(self, catalogs: list[dict], auth_key: str | None = Non
307307
addon["manifest"]["catalogs"] = catalogs
308308
break
309309
return await self.update_addon(addons, auth_key)
310+
311+
async def is_addon_installed(self, auth_key: str | None = None):
312+
auth_key = auth_key or await self.get_auth_key()
313+
addons = await self.get_addons(auth_key)
314+
for addon in addons:
315+
if addon.get("manifest", {}).get("id") == settings.ADDON_ID:
316+
return True
317+
return False

app/services/token_store.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,12 @@ async def get_payload(self, token: str) -> dict[str, Any] | None:
138138
logger.warning("Failed to decrypt or decode cached payload for token. Key might have changed.")
139139
return None
140140

141-
async def delete_token(self, token: str) -> None:
142-
hashed = self._hash_token(token)
143-
key = self._format_key(hashed)
141+
async def delete_token(self, token: str = None, key: str = None) -> None:
142+
if not token and not key:
143+
raise ValueError("Either token or key must be provided")
144+
if token:
145+
hashed = self._hash_token(token)
146+
key = self._format_key(hashed)
144147
client = await self._get_client()
145148
await client.delete(key)
146149

0 commit comments

Comments
 (0)