Skip to content

Commit

Permalink
feat: refresh token in middleware, no polling
Browse files Browse the repository at this point in the history
this should make fly suspend + resume work
  • Loading branch information
pikdum committed Oct 12, 2024
1 parent b9b0106 commit 6643ea9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
14 changes: 12 additions & 2 deletions mona/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
import random
import re
from contextlib import asynccontextmanager
from datetime import datetime

import anitopy
import httpx
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend
Expand All @@ -20,7 +21,6 @@
@asynccontextmanager
async def lifespan(app: FastAPI):
FastAPICache.init(InMemoryBackend())
await tvdb.login()
yield


Expand All @@ -29,6 +29,16 @@ async def lifespan(app: FastAPI):
tvdb = TVDB(os.environ["TVDB_API_KEY"])


@app.middleware("http")
async def tvdb_login(request: Request, call_next):
if tvdb.token is None:
await tvdb.login()
elif datetime.now().timestamp() > tvdb.token_expires:

Check failure on line 36 in mona/app.py

View workflow job for this annotation

GitHub Actions / pyright

Operator ">" not supported for types "float" and "int | None"   Operator ">" not supported for types "float" and "None" (reportOperatorIssue)
await tvdb.login()
response = await call_next(request)
return response


def slugify(text: str) -> str:
# lowercase
text = text.lower()
Expand Down
8 changes: 4 additions & 4 deletions mona/tvdb.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import asyncio
import os
from datetime import datetime

import httpx
from loguru import logger
Expand All @@ -9,22 +10,21 @@
class TVDB:
def __init__(self, apikey: str, pin: str = "hello world"):
self.token: str | None = None
self.token_expires: int | None = None
self.apikey: str = apikey
self.pin: str = pin
self.api_base: str = "https://api4.thetvdb.com/v4"

async def login(self) -> str | None:
# refresh token every hour
asyncio.get_event_loop().call_later(
3600, lambda: asyncio.create_task(self.login())
)
async with httpx.AsyncClient(http2=True) as client:
response = await client.post(
f"{self.api_base}/login",
json={"apikey": self.apikey, "pin": self.pin},
)
if response.status_code == 200:
self.token = response.json().get("data", {}).get("token")
# set token to expire in an hour
self.token_expires = datetime.now().timestamp() + 3600

Check failure on line 27 in mona/tvdb.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot assign to attribute "token_expires" for class "TVDB*"   Type "float" is not assignable to type "int | None"     "float" is not assignable to "int"     "float" is not assignable to "None" (reportAttributeAccessIssue)
logger.info("TVDB token refreshed!")
else:
logger.error("TVDB token refresh failed!")
Expand Down

0 comments on commit 6643ea9

Please sign in to comment.