main.py 22 KB

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