main.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. from fastapi import FastAPI, Request, Depends, Form, Response, HTTPException, status
  2. from fastapi.templating import Jinja2Templates
  3. from fastapi.staticfiles import StaticFiles
  4. from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, StreamingResponse
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from sqlalchemy import select, func
  7. from contextlib import asynccontextmanager
  8. import json
  9. from datetime import datetime
  10. from typing import Optional
  11. import httpx
  12. import os
  13. from pathlib import Path
  14. from app.database import init_db, get_db
  15. from app.models import Book, ListeningSession, Recommendation, User, AppSettings
  16. from app.abs_client import get_abs_client
  17. from app.recommender import BookRecommender
  18. from app.config import get_settings
  19. from app.auth import (
  20. get_current_user,
  21. get_current_user_optional,
  22. get_current_admin,
  23. authenticate_user,
  24. create_user,
  25. set_session_cookie,
  26. clear_session_cookie
  27. )
  28. from app.services.stats import ReadingStatsService
  29. @asynccontextmanager
  30. async def lifespan(app: FastAPI):
  31. """Initialize database on startup."""
  32. await init_db()
  33. yield
  34. # Initialize FastAPI app
  35. app = FastAPI(
  36. title="Audiobookshelf Recommendations",
  37. description="AI-powered book recommendations based on your listening history",
  38. lifespan=lifespan
  39. )
  40. # Setup templates and static files
  41. templates = Jinja2Templates(directory="app/templates")
  42. app.mount("/static", StaticFiles(directory="app/static"), name="static")
  43. # Initialize recommender (shared across users)
  44. recommender = BookRecommender()
  45. @app.get("/", response_class=HTMLResponse)
  46. async def home(
  47. request: Request,
  48. db: AsyncSession = Depends(get_db),
  49. user: Optional[User] = Depends(get_current_user_optional)
  50. ):
  51. """Home page showing dashboard or landing page."""
  52. # If user not logged in, show landing page
  53. if not user:
  54. return templates.TemplateResponse(
  55. "index.html",
  56. {
  57. "request": request,
  58. "user": None,
  59. "books": [],
  60. "recommendations": []
  61. }
  62. )
  63. # Get user's recent books and recommendations
  64. recent_sessions = await db.execute(
  65. select(ListeningSession)
  66. .where(ListeningSession.user_id == user.id)
  67. .order_by(ListeningSession.last_update.desc())
  68. .limit(10)
  69. )
  70. sessions = recent_sessions.scalars().all()
  71. # Get book details for sessions
  72. books = []
  73. for session in sessions:
  74. book_result = await db.execute(
  75. select(Book).where(Book.id == session.book_id)
  76. )
  77. book = book_result.scalar_one_or_none()
  78. if book:
  79. books.append({
  80. "book": book,
  81. "session": session
  82. })
  83. # Get user's recent recommendations
  84. recs_result = await db.execute(
  85. select(Recommendation)
  86. .where(
  87. Recommendation.user_id == user.id,
  88. Recommendation.dismissed == False
  89. )
  90. .order_by(Recommendation.created_at.desc())
  91. .limit(5)
  92. )
  93. recommendations_raw = recs_result.scalars().all()
  94. # Parse JSON fields for template
  95. recommendations = []
  96. for rec in recommendations_raw:
  97. rec_dict = {
  98. "id": rec.id,
  99. "title": rec.title,
  100. "author": rec.author,
  101. "description": rec.description,
  102. "reason": rec.reason,
  103. "genres": json.loads(rec.genres) if rec.genres else []
  104. }
  105. recommendations.append(rec_dict)
  106. return templates.TemplateResponse(
  107. "index.html",
  108. {
  109. "request": request,
  110. "user": user,
  111. "books": books,
  112. "recommendations": recommendations
  113. }
  114. )
  115. # ==================== Authentication Routes ====================
  116. @app.get("/login", response_class=HTMLResponse)
  117. async def login_page(request: Request):
  118. """Login page."""
  119. return templates.TemplateResponse("login.html", {"request": request})
  120. @app.post("/api/auth/login")
  121. async def login(
  122. username: str = Form(...),
  123. password: str = Form(...),
  124. db: AsyncSession = Depends(get_db)
  125. ):
  126. """Authenticate user and create session."""
  127. user = await authenticate_user(db, username, password)
  128. if not user:
  129. raise HTTPException(
  130. status_code=status.HTTP_401_UNAUTHORIZED,
  131. detail="Incorrect username or password"
  132. )
  133. # Create redirect response and set session cookie
  134. redirect = RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
  135. set_session_cookie(redirect, user.id)
  136. return redirect
  137. @app.get("/register", response_class=HTMLResponse)
  138. async def register_page(request: Request):
  139. """Registration page."""
  140. return templates.TemplateResponse("register.html", {"request": request})
  141. @app.post("/api/auth/register")
  142. async def register(
  143. username: str = Form(...),
  144. email: str = Form(...),
  145. password: str = Form(...),
  146. abs_url: str = Form(...),
  147. abs_api_token: str = Form(...),
  148. display_name: Optional[str] = Form(None),
  149. db: AsyncSession = Depends(get_db)
  150. ):
  151. """Register a new user."""
  152. try:
  153. # Check if registration is allowed
  154. result = await db.execute(
  155. select(AppSettings).where(AppSettings.key == "allow_registration")
  156. )
  157. allow_reg_setting = result.scalar_one_or_none()
  158. # Check if there are any existing users (first user is always allowed)
  159. result = await db.execute(select(func.count(User.id)))
  160. user_count = result.scalar()
  161. if user_count > 0 and allow_reg_setting and allow_reg_setting.value.lower() != 'true':
  162. raise HTTPException(
  163. status_code=status.HTTP_403_FORBIDDEN,
  164. detail="Registration is currently disabled"
  165. )
  166. user = await create_user(
  167. db=db,
  168. username=username,
  169. email=email,
  170. password=password,
  171. abs_url=abs_url,
  172. abs_api_token=abs_api_token,
  173. display_name=display_name
  174. )
  175. # Create redirect response and set session cookie
  176. redirect = RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
  177. set_session_cookie(redirect, user.id)
  178. return redirect
  179. except HTTPException as e:
  180. raise e
  181. except Exception as e:
  182. raise HTTPException(
  183. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  184. detail=str(e)
  185. )
  186. @app.post("/api/auth/logout")
  187. async def logout(response: Response):
  188. """Logout user and clear session."""
  189. clear_session_cookie(response)
  190. return JSONResponse({
  191. "status": "success",
  192. "message": "Logged out successfully"
  193. })
  194. # ==================== API Routes ====================
  195. async def download_cover_image(abs_client, book_id: str) -> Optional[str]:
  196. """
  197. Download cover image from Audiobookshelf and save locally.
  198. Args:
  199. abs_client: Audiobookshelf client with authentication
  200. book_id: Library item ID
  201. Returns:
  202. Local path to saved cover (e.g., /static/covers/book_id.jpg) or None
  203. """
  204. if not book_id:
  205. return None
  206. # Create covers directory if it doesn't exist
  207. covers_dir = Path("app/static/covers")
  208. covers_dir.mkdir(parents=True, exist_ok=True)
  209. # Use Audiobookshelf API cover endpoint
  210. cover_url = f"{abs_client.base_url}/api/items/{book_id}/cover"
  211. async with httpx.AsyncClient() as client:
  212. try:
  213. response = await client.get(cover_url, headers=abs_client.headers, follow_redirects=True)
  214. response.raise_for_status()
  215. # Determine extension from content-type
  216. content_type = response.headers.get("content-type", "image/jpeg")
  217. ext = ".webp" if "webp" in content_type else ".jpg"
  218. local_filename = f"{book_id}{ext}"
  219. local_path = covers_dir / local_filename
  220. # Save to local file
  221. with open(local_path, "wb") as f:
  222. f.write(response.content)
  223. # Return path relative to static directory
  224. return f"/static/covers/{local_filename}"
  225. except Exception as e:
  226. print(f"Failed to download cover for {book_id}: {e}")
  227. return None
  228. @app.get("/api/sync")
  229. async def sync_with_audiobookshelf(
  230. db: AsyncSession = Depends(get_db),
  231. user: User = Depends(get_current_user)
  232. ):
  233. """Sync library and progress from Audiobookshelf."""
  234. try:
  235. # Create user-specific ABS client
  236. abs_client = get_abs_client(user)
  237. # Get user info which includes all media progress
  238. user_info = await abs_client.get_user_info()
  239. media_progress = user_info.get("mediaProgress", [])
  240. synced_count = 0
  241. for progress_item in media_progress:
  242. # Skip podcast episodes, only process books
  243. if progress_item.get("mediaItemType") != "book":
  244. continue
  245. library_item_id = progress_item.get("libraryItemId")
  246. if not library_item_id:
  247. continue
  248. # Fetch full library item details
  249. try:
  250. item = await abs_client.get_item_details(library_item_id)
  251. except:
  252. # Skip if item not found
  253. continue
  254. # Extract book info
  255. media = item.get("media", {})
  256. metadata = media.get("metadata", {})
  257. book_id = item.get("id")
  258. if not book_id:
  259. continue
  260. # Check if book exists in DB
  261. result = await db.execute(select(Book).where(Book.id == book_id))
  262. book = result.scalar_one_or_none()
  263. # Download cover image and get local path
  264. local_cover_url = await download_cover_image(abs_client, book_id)
  265. # Create or update book
  266. if not book:
  267. book = Book(
  268. id=book_id,
  269. title=metadata.get("title", "Unknown"),
  270. author=metadata.get("authorName", "Unknown"),
  271. narrator=metadata.get("narratorName"),
  272. description=metadata.get("description"),
  273. genres=json.dumps(metadata.get("genres", [])),
  274. tags=json.dumps(media.get("tags", [])),
  275. duration=media.get("duration", 0),
  276. cover_url=local_cover_url # Store local path
  277. )
  278. db.add(book)
  279. else:
  280. # Update existing book
  281. book.title = metadata.get("title", book.title)
  282. book.author = metadata.get("authorName", book.author)
  283. if local_cover_url: # Only update if download succeeded
  284. book.cover_url = local_cover_url
  285. book.updated_at = datetime.now()
  286. # Update or create listening session
  287. progress_data = progress_item.get("progress", 0)
  288. current_time = progress_item.get("currentTime", 0)
  289. is_finished = progress_item.get("isFinished", False)
  290. started_at_ts = progress_item.get("startedAt")
  291. finished_at_ts = progress_item.get("finishedAt")
  292. session_result = await db.execute(
  293. select(ListeningSession)
  294. .where(
  295. ListeningSession.user_id == user.id,
  296. ListeningSession.book_id == book_id
  297. )
  298. .order_by(ListeningSession.last_update.desc())
  299. .limit(1)
  300. )
  301. session = session_result.scalar_one_or_none()
  302. if not session:
  303. session = ListeningSession(
  304. user_id=user.id,
  305. book_id=book_id,
  306. progress=progress_data,
  307. current_time=current_time,
  308. is_finished=is_finished,
  309. started_at=datetime.fromtimestamp(started_at_ts / 1000) if started_at_ts else datetime.now(),
  310. finished_at=datetime.fromtimestamp(finished_at_ts / 1000) if finished_at_ts else None
  311. )
  312. db.add(session)
  313. else:
  314. # Update existing session
  315. session.progress = progress_data
  316. session.current_time = current_time
  317. session.is_finished = is_finished
  318. if finished_at_ts and not session.finished_at:
  319. session.finished_at = datetime.fromtimestamp(finished_at_ts / 1000)
  320. synced_count += 1
  321. await db.commit()
  322. return JSONResponse({
  323. "status": "success",
  324. "synced": synced_count,
  325. "message": f"Synced {synced_count} books from Audiobookshelf"
  326. })
  327. except Exception as e:
  328. return JSONResponse(
  329. {"status": "error", "message": str(e)},
  330. status_code=500
  331. )
  332. @app.get("/api/recommendations/generate")
  333. async def generate_recommendations(
  334. db: AsyncSession = Depends(get_db),
  335. user: User = Depends(get_current_user)
  336. ):
  337. """Generate new AI recommendations based on reading history."""
  338. try:
  339. # Get finished books for context
  340. finished_result = await db.execute(
  341. select(ListeningSession, Book)
  342. .join(Book, ListeningSession.book_id == Book.id)
  343. .where(
  344. ListeningSession.user_id == user.id,
  345. ListeningSession.is_finished == True
  346. )
  347. .order_by(ListeningSession.finished_at.desc())
  348. .limit(20)
  349. )
  350. finished_items = finished_result.all()
  351. if not finished_items:
  352. return JSONResponse({
  353. "status": "error",
  354. "message": "No reading history found. Please sync with Audiobookshelf first."
  355. })
  356. # Format reading history
  357. reading_history = []
  358. for session, book in finished_items:
  359. reading_history.append({
  360. "title": book.title,
  361. "author": book.author,
  362. "genres": json.loads(book.genres) if book.genres else [],
  363. "progress": session.progress,
  364. "is_finished": session.is_finished
  365. })
  366. # Generate recommendations
  367. new_recs = await recommender.generate_recommendations(
  368. reading_history, num_recommendations=5
  369. )
  370. # Save to database
  371. for rec in new_recs:
  372. recommendation = Recommendation(
  373. user_id=user.id,
  374. title=rec.get("title"),
  375. author=rec.get("author"),
  376. description=rec.get("description"),
  377. reason=rec.get("reason"),
  378. genres=json.dumps(rec.get("genres", []))
  379. )
  380. db.add(recommendation)
  381. await db.commit()
  382. return JSONResponse({
  383. "status": "success",
  384. "recommendations": new_recs,
  385. "count": len(new_recs)
  386. })
  387. except Exception as e:
  388. return JSONResponse(
  389. {"status": "error", "message": str(e)},
  390. status_code=500
  391. )
  392. @app.get("/api/recommendations")
  393. async def get_recommendations(
  394. db: AsyncSession = Depends(get_db),
  395. user: User = Depends(get_current_user)
  396. ):
  397. """Get saved recommendations."""
  398. result = await db.execute(
  399. select(Recommendation)
  400. .where(
  401. Recommendation.user_id == user.id,
  402. Recommendation.dismissed == False
  403. )
  404. .order_by(Recommendation.created_at.desc())
  405. )
  406. recommendations = result.scalars().all()
  407. return JSONResponse({
  408. "recommendations": [
  409. {
  410. "id": rec.id,
  411. "title": rec.title,
  412. "author": rec.author,
  413. "description": rec.description,
  414. "reason": rec.reason,
  415. "genres": json.loads(rec.genres) if rec.genres else [],
  416. "created_at": rec.created_at.isoformat()
  417. }
  418. for rec in recommendations
  419. ]
  420. })
  421. @app.get("/api/history")
  422. async def get_listening_history(
  423. db: AsyncSession = Depends(get_db),
  424. user: User = Depends(get_current_user)
  425. ):
  426. """Get listening history."""
  427. result = await db.execute(
  428. select(ListeningSession, Book)
  429. .join(Book, ListeningSession.book_id == Book.id)
  430. .where(ListeningSession.user_id == user.id)
  431. .order_by(ListeningSession.last_update.desc())
  432. )
  433. items = result.all()
  434. return JSONResponse({
  435. "history": [
  436. {
  437. "book": {
  438. "id": book.id,
  439. "title": book.title,
  440. "author": book.author,
  441. "cover_url": book.cover_url,
  442. },
  443. "session": {
  444. "progress": session.progress,
  445. "is_finished": session.is_finished,
  446. "started_at": session.started_at.isoformat() if session.started_at else None,
  447. "finished_at": session.finished_at.isoformat() if session.finished_at else None,
  448. }
  449. }
  450. for session, book in items
  451. ]
  452. })
  453. # ==================== Reading Log Routes ====================
  454. @app.get("/reading-log", response_class=HTMLResponse)
  455. async def reading_log_page(
  456. request: Request,
  457. user: User = Depends(get_current_user)
  458. ):
  459. """Reading log page with stats and filters."""
  460. return templates.TemplateResponse(
  461. "reading_log.html",
  462. {
  463. "request": request,
  464. "user": user
  465. }
  466. )
  467. @app.get("/api/reading-log/stats")
  468. async def get_reading_stats(
  469. db: AsyncSession = Depends(get_db),
  470. user: User = Depends(get_current_user),
  471. start_date: Optional[str] = None,
  472. end_date: Optional[str] = None
  473. ):
  474. """Get reading statistics for the user."""
  475. try:
  476. # Parse dates if provided
  477. start_dt = datetime.fromisoformat(start_date) if start_date else None
  478. end_dt = datetime.fromisoformat(end_date) if end_date else None
  479. # Calculate stats
  480. stats_service = ReadingStatsService(db, user.id, user.abs_url)
  481. stats = await stats_service.calculate_stats(start_dt, end_dt)
  482. return JSONResponse(stats)
  483. except Exception as e:
  484. return JSONResponse(
  485. {"status": "error", "message": str(e)},
  486. status_code=500
  487. )
  488. @app.put("/api/sessions/{session_id}/rating")
  489. async def update_session_rating(
  490. session_id: int,
  491. rating: int = Form(...),
  492. db: AsyncSession = Depends(get_db),
  493. user: User = Depends(get_current_user)
  494. ):
  495. """Update the rating for a listening session."""
  496. try:
  497. # Validate rating
  498. if rating < 1 or rating > 5:
  499. raise HTTPException(
  500. status_code=status.HTTP_400_BAD_REQUEST,
  501. detail="Rating must be between 1 and 5"
  502. )
  503. # Get session and verify ownership
  504. result = await db.execute(
  505. select(ListeningSession).where(
  506. ListeningSession.id == session_id,
  507. ListeningSession.user_id == user.id
  508. )
  509. )
  510. session = result.scalar_one_or_none()
  511. if not session:
  512. raise HTTPException(
  513. status_code=status.HTTP_404_NOT_FOUND,
  514. detail="Session not found"
  515. )
  516. # Update rating
  517. session.rating = rating
  518. await db.commit()
  519. return JSONResponse({
  520. "status": "success",
  521. "message": "Rating updated successfully",
  522. "rating": rating
  523. })
  524. except HTTPException as e:
  525. raise e
  526. except Exception as e:
  527. return JSONResponse(
  528. {"status": "error", "message": str(e)},
  529. status_code=500
  530. )
  531. # ==================== Admin Routes ====================
  532. @app.get("/admin", response_class=HTMLResponse)
  533. async def admin_page(
  534. request: Request,
  535. user: User = Depends(get_current_admin)
  536. ):
  537. """Admin panel page."""
  538. return templates.TemplateResponse(
  539. "admin.html",
  540. {
  541. "request": request,
  542. "user": user
  543. }
  544. )
  545. @app.get("/api/admin/settings")
  546. async def get_admin_settings(
  547. db: AsyncSession = Depends(get_db),
  548. admin: User = Depends(get_current_admin)
  549. ):
  550. """Get application settings."""
  551. result = await db.execute(select(AppSettings))
  552. settings = result.scalars().all()
  553. settings_dict = {s.key: s.value for s in settings}
  554. return JSONResponse(settings_dict)
  555. @app.put("/api/admin/settings/{key}")
  556. async def update_setting(
  557. key: str,
  558. value: str = Form(...),
  559. db: AsyncSession = Depends(get_db),
  560. admin: User = Depends(get_current_admin)
  561. ):
  562. """Update an application setting."""
  563. result = await db.execute(
  564. select(AppSettings).where(AppSettings.key == key)
  565. )
  566. setting = result.scalar_one_or_none()
  567. if not setting:
  568. # Create new setting
  569. setting = AppSettings(key=key, value=value)
  570. db.add(setting)
  571. else:
  572. # Update existing
  573. setting.value = value
  574. await db.commit()
  575. return JSONResponse({
  576. "status": "success",
  577. "message": f"Setting {key} updated"
  578. })
  579. @app.get("/api/admin/users")
  580. async def get_users(
  581. db: AsyncSession = Depends(get_db),
  582. admin: User = Depends(get_current_admin)
  583. ):
  584. """Get all users."""
  585. result = await db.execute(select(User).order_by(User.created_at.desc()))
  586. users = result.scalars().all()
  587. users_list = [
  588. {
  589. "id": user.id,
  590. "username": user.username,
  591. "email": user.email,
  592. "display_name": user.display_name,
  593. "is_admin": user.is_admin,
  594. "is_active": user.is_active,
  595. "created_at": user.created_at.isoformat() if user.created_at else None,
  596. "last_login": user.last_login.isoformat() if user.last_login else None,
  597. "is_current": user.id == admin.id
  598. }
  599. for user in users
  600. ]
  601. return JSONResponse({"users": users_list})
  602. @app.put("/api/admin/users/{user_id}/admin")
  603. async def toggle_user_admin(
  604. user_id: int,
  605. is_admin: str = Form(...),
  606. db: AsyncSession = Depends(get_db),
  607. admin: User = Depends(get_current_admin)
  608. ):
  609. """Toggle admin status for a user."""
  610. # Prevent admin from removing their own admin status
  611. if user_id == admin.id:
  612. return JSONResponse(
  613. {"status": "error", "message": "Cannot modify your own admin status"},
  614. status_code=400
  615. )
  616. result = await db.execute(select(User).where(User.id == user_id))
  617. user = result.scalar_one_or_none()
  618. if not user:
  619. raise HTTPException(
  620. status_code=status.HTTP_404_NOT_FOUND,
  621. detail="User not found"
  622. )
  623. user.is_admin = is_admin.lower() == 'true'
  624. await db.commit()
  625. return JSONResponse({
  626. "status": "success",
  627. "message": "User admin status updated"
  628. })
  629. @app.delete("/api/admin/users/{user_id}")
  630. async def delete_user(
  631. user_id: int,
  632. db: AsyncSession = Depends(get_db),
  633. admin: User = Depends(get_current_admin)
  634. ):
  635. """Delete a user."""
  636. # Prevent admin from deleting themselves
  637. if user_id == admin.id:
  638. return JSONResponse(
  639. {"status": "error", "message": "Cannot delete your own account"},
  640. status_code=400
  641. )
  642. result = await db.execute(select(User).where(User.id == user_id))
  643. user = result.scalar_one_or_none()
  644. if not user:
  645. raise HTTPException(
  646. status_code=status.HTTP_404_NOT_FOUND,
  647. detail="User not found"
  648. )
  649. await db.delete(user)
  650. await db.commit()
  651. return JSONResponse({
  652. "status": "success",
  653. "message": "User deleted successfully"
  654. })
  655. @app.get("/health")
  656. async def health_check():
  657. """Health check endpoint."""
  658. return {"status": "healthy"}