commit
9c5fef1a4d
412 files changed
+94582
No files matched your search
@@ -0,0 +1,461 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from sakura_cloud.api.deps import CurrentUser, DbSession
|
||||
from sakura_cloud.core.config import settings
|
||||
from sakura_cloud.models.file import FileBlob, UserFile
|
||||
from sakura_cloud.models.mixins import utc_now
|
||||
from sakura_cloud.models.novel import Novel
|
||||
from sakura_cloud.schemas.common import ApiResponse, PageResponse, Pagination
|
||||
from sakura_cloud.schemas.novel import (
|
||||
BookmarkUpdate,
|
||||
NovelOut,
|
||||
NovelSeriesGroup,
|
||||
NovelViewUpdate,
|
||||
ReadingProgressUpdate,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class NovelBatchDeleteRequest(BaseModel):
|
||||
ids: list[str] = Field(default_factory=list, max_length=200)
|
||||
series_ids: list[str] = Field(default_factory=list, max_length=50)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def normalize_targets(self) -> "NovelBatchDeleteRequest":
|
||||
self.ids = [item.strip() for item in self.ids if item and item.strip()]
|
||||
self.series_ids = [item.strip() for item in self.series_ids if item and item.strip()]
|
||||
return self
|
||||
|
||||
|
||||
class OnlineNovelImportRequest(BaseModel):
|
||||
source_platform: str = Field(max_length=20)
|
||||
title: str = Field(min_length=1, max_length=500)
|
||||
author: str | None = Field(default=None, max_length=200)
|
||||
detail_url: str = Field(min_length=1, max_length=2048)
|
||||
cover_url: str | None = Field(default=None, max_length=2048)
|
||||
content: str = Field(min_length=1, max_length=2_000_000)
|
||||
tags: list[str] = Field(default_factory=list, max_length=50)
|
||||
|
||||
|
||||
def _latest_non_null(values: list[datetime | None]) -> datetime | None:
|
||||
normalized = [value for value in values if value is not None]
|
||||
return max(normalized) if normalized else None
|
||||
|
||||
|
||||
def _series_group_from_items(series_id: str, items: list[Novel], *, include_chapters: bool = True) -> NovelSeriesGroup:
|
||||
sorted_items = sorted(items, key=lambda item: (item.chapter_order, item.updated_at))
|
||||
first = sorted_items[0]
|
||||
return NovelSeriesGroup(
|
||||
series_id=series_id,
|
||||
series_title=first.series_title or first.title,
|
||||
author=first.author,
|
||||
chapter_count=len(sorted_items),
|
||||
cover_path=first.cover_path,
|
||||
last_read_at=_latest_non_null([item.last_read_at for item in sorted_items]),
|
||||
last_viewed_at=_latest_non_null([item.last_viewed_at for item in sorted_items]),
|
||||
chapters=[NovelOut.model_validate(item) for item in sorted_items] if include_chapters else [],
|
||||
)
|
||||
|
||||
|
||||
def _resolve_novel_storage_path(novel: Novel, db: DbSession) -> Path:
|
||||
path = Path(novel.file_path or "")
|
||||
if path.is_file():
|
||||
return path
|
||||
|
||||
if novel.file_id:
|
||||
user_file = db.get(UserFile, novel.file_id)
|
||||
if user_file is not None:
|
||||
blob = db.get(FileBlob, user_file.file_sha256)
|
||||
if blob is not None:
|
||||
blob_path = Path(blob.storage_path)
|
||||
if blob_path.is_file():
|
||||
novel.file_path = blob.storage_path
|
||||
novel.file_size = blob.file_size
|
||||
if not novel.cover_path:
|
||||
novel.cover_path = blob.thumbnail_path
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return blob_path
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel file missing from storage")
|
||||
|
||||
|
||||
def _online_source_id(detail_url: str) -> str:
|
||||
return hashlib.sha256(detail_url.encode("utf-8")).hexdigest()[:32]
|
||||
|
||||
|
||||
def _write_online_novel_file(user_id: str, source_id: str, content: str) -> tuple[str, str, int]:
|
||||
data = content.encode("utf-8")
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
path = Path(settings.storage_root) / "online_imports" / "novels" / user_id
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
target = path / f"{source_id}-{sha256[:12]}.txt"
|
||||
if not target.exists():
|
||||
target.write_bytes(data)
|
||||
return str(target), sha256, len(data)
|
||||
|
||||
|
||||
def _ensure_storage_quota(current_user: CurrentUser, incoming_size: int) -> None:
|
||||
size = max(0, incoming_size)
|
||||
if size and current_user.storage_used + size > current_user.storage_limit:
|
||||
raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail="Storage quota exceeded")
|
||||
|
||||
|
||||
@router.get("", response_model=ApiResponse[PageResponse[NovelOut]])
|
||||
def list_novels(
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
page: int = Query(default=1, ge=1),
|
||||
limit: int = Query(default=30, ge=1, le=100),
|
||||
search: str | None = None,
|
||||
is_favorite: bool | None = None,
|
||||
) -> ApiResponse[PageResponse[NovelOut]]:
|
||||
query = select(Novel).where(Novel.user_id == current_user.id)
|
||||
count_query = select(func.count()).select_from(Novel).where(Novel.user_id == current_user.id)
|
||||
if search:
|
||||
if db.bind is not None and db.bind.dialect.name == "postgresql":
|
||||
vector = func.to_tsvector("simple", func.concat_ws(" ", Novel.title, Novel.author, Novel.description))
|
||||
condition = vector.op("@@")(func.plainto_tsquery("simple", search))
|
||||
else:
|
||||
condition = Novel.title.ilike(f"%{search}%") | Novel.author.ilike(f"%{search}%")
|
||||
query = query.where(condition)
|
||||
count_query = count_query.where(condition)
|
||||
if is_favorite is not None:
|
||||
query = query.where(Novel.is_favorite == is_favorite)
|
||||
count_query = count_query.where(Novel.is_favorite == is_favorite)
|
||||
total = int(db.scalar(count_query) or 0)
|
||||
rows = db.scalars(
|
||||
query.order_by(Novel.last_viewed_at.desc().nullslast(), Novel.updated_at.desc())
|
||||
.offset((page - 1) * limit)
|
||||
.limit(limit)
|
||||
).all()
|
||||
data = PageResponse(
|
||||
items=[NovelOut.model_validate(row) for row in rows],
|
||||
pagination=Pagination(page=page, limit=limit, total=total, pages=math.ceil(total / limit) if total else 0),
|
||||
)
|
||||
return ApiResponse(data=data)
|
||||
|
||||
|
||||
@router.get("/continue-reading", response_model=ApiResponse[list[NovelOut]])
|
||||
def continue_reading(current_user: CurrentUser, db: DbSession) -> ApiResponse[list[NovelOut]]:
|
||||
rows = db.scalars(
|
||||
select(Novel)
|
||||
.where(Novel.user_id == current_user.id, Novel.last_read_at.is_not(None))
|
||||
.order_by(Novel.last_read_at.desc())
|
||||
.limit(20)
|
||||
).all()
|
||||
return ApiResponse(data=[NovelOut.model_validate(row) for row in rows])
|
||||
|
||||
|
||||
@router.get("/recent", response_model=ApiResponse[list[NovelOut]])
|
||||
def recent_novels(
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
limit: int = Query(default=20, ge=1, le=100),
|
||||
) -> ApiResponse[list[NovelOut]]:
|
||||
rows = db.scalars(
|
||||
select(Novel)
|
||||
.where(Novel.user_id == current_user.id, Novel.last_viewed_at.is_not(None))
|
||||
.order_by(Novel.last_viewed_at.desc())
|
||||
.limit(limit)
|
||||
).all()
|
||||
return ApiResponse(data=[NovelOut.model_validate(row) for row in rows])
|
||||
|
||||
|
||||
@router.get("/series", response_model=ApiResponse[list[NovelSeriesGroup]])
|
||||
def list_novel_series(
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
include_chapters: bool = Query(default=True),
|
||||
) -> ApiResponse[list[NovelSeriesGroup]]:
|
||||
# Mobile shelf uses include_chapters=false to avoid loading every chapter for every series.
|
||||
# The exact series catalog is fetched later by /series/{series_id}.
|
||||
if not include_chapters:
|
||||
rows = db.execute(
|
||||
select(
|
||||
Novel.series_id,
|
||||
func.min(Novel.series_title),
|
||||
func.min(Novel.author),
|
||||
func.count(Novel.id),
|
||||
func.min(Novel.cover_path),
|
||||
func.max(Novel.last_read_at),
|
||||
func.max(Novel.last_viewed_at),
|
||||
func.max(Novel.updated_at),
|
||||
)
|
||||
.where(Novel.user_id == current_user.id, Novel.series_id.is_not(None))
|
||||
.group_by(Novel.series_id)
|
||||
.order_by(func.max(Novel.last_viewed_at).desc().nullslast(), func.max(Novel.updated_at).desc())
|
||||
).all()
|
||||
return ApiResponse(
|
||||
data=[
|
||||
NovelSeriesGroup(
|
||||
series_id=str(row[0]),
|
||||
series_title=str(row[1] or "Untitled series"),
|
||||
author=row[2],
|
||||
chapter_count=int(row[3] or 0),
|
||||
cover_path=row[4],
|
||||
last_read_at=row[5],
|
||||
last_viewed_at=row[6],
|
||||
chapters=[],
|
||||
)
|
||||
for row in rows
|
||||
if row[0]
|
||||
]
|
||||
)
|
||||
|
||||
rows = db.scalars(
|
||||
select(Novel)
|
||||
.where(Novel.user_id == current_user.id, Novel.series_id.is_not(None))
|
||||
.order_by(Novel.series_title.asc(), Novel.chapter_order.asc(), Novel.updated_at.desc())
|
||||
).all()
|
||||
groups: dict[str, list[Novel]] = {}
|
||||
for row in rows:
|
||||
if not row.series_id:
|
||||
continue
|
||||
groups.setdefault(row.series_id, []).append(row)
|
||||
data = []
|
||||
for series_id, items in groups.items():
|
||||
data.append(_series_group_from_items(series_id, items, include_chapters=include_chapters))
|
||||
data.sort(key=lambda item: item.last_viewed_at or item.last_read_at or datetime.min.replace(tzinfo=timezone.utc), reverse=True)
|
||||
return ApiResponse(data=data)
|
||||
|
||||
|
||||
@router.get("/series/{series_id}", response_model=ApiResponse[NovelSeriesGroup])
|
||||
def get_novel_series(series_id: str, current_user: CurrentUser, db: DbSession) -> ApiResponse[NovelSeriesGroup]:
|
||||
rows = db.scalars(
|
||||
select(Novel)
|
||||
.where(
|
||||
Novel.user_id == current_user.id,
|
||||
Novel.series_id == series_id,
|
||||
)
|
||||
.order_by(Novel.chapter_order.asc(), Novel.updated_at.desc())
|
||||
).all()
|
||||
if not rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel series not found")
|
||||
return ApiResponse(data=_series_group_from_items(series_id, rows, include_chapters=True))
|
||||
|
||||
|
||||
@router.post("/import-online", response_model=ApiResponse[NovelOut], status_code=status.HTTP_201_CREATED)
|
||||
def import_online_novel(
|
||||
payload: OnlineNovelImportRequest,
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
) -> ApiResponse[NovelOut]:
|
||||
source_id = _online_source_id(payload.detail_url)
|
||||
existing = db.scalar(
|
||||
select(Novel).where(
|
||||
Novel.user_id == current_user.id,
|
||||
Novel.source_platform == payload.source_platform,
|
||||
Novel.source_id == source_id,
|
||||
)
|
||||
)
|
||||
if existing is not None:
|
||||
return ApiResponse(data=NovelOut.model_validate(existing))
|
||||
|
||||
storage_path, sha256, file_size = _write_online_novel_file(current_user.id, source_id, payload.content)
|
||||
blob = db.get(FileBlob, sha256)
|
||||
if blob is None:
|
||||
blob = FileBlob(
|
||||
sha256=sha256,
|
||||
storage_path=storage_path,
|
||||
thumbnail_path=payload.cover_url,
|
||||
file_size=file_size,
|
||||
mime_type="text/plain",
|
||||
)
|
||||
db.add(blob)
|
||||
|
||||
user_file = db.scalar(select(UserFile).where(UserFile.user_id == current_user.id, UserFile.file_sha256 == sha256))
|
||||
if user_file is None:
|
||||
_ensure_storage_quota(current_user, file_size)
|
||||
user_file = UserFile(
|
||||
user_id=current_user.id,
|
||||
file_sha256=sha256,
|
||||
original_name=f"{payload.title[:80]}.txt",
|
||||
)
|
||||
db.add(user_file)
|
||||
current_user.storage_used += file_size
|
||||
db.flush()
|
||||
|
||||
novel = Novel(
|
||||
user_id=current_user.id,
|
||||
file_id=user_file.id,
|
||||
source_id=source_id,
|
||||
source_platform=payload.source_platform,
|
||||
title=payload.title.strip(),
|
||||
author=payload.author,
|
||||
file_path=storage_path,
|
||||
file_size=file_size,
|
||||
cover_path=payload.cover_url,
|
||||
word_count=len(payload.content),
|
||||
tags=payload.tags,
|
||||
description=payload.detail_url,
|
||||
)
|
||||
db.add(novel)
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return ApiResponse(code=201, message="created", data=NovelOut.model_validate(novel))
|
||||
|
||||
|
||||
@router.get("/{novel_id}/content")
|
||||
def get_novel_content(novel_id: str, current_user: CurrentUser, db: DbSession) -> FileResponse:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
path = _resolve_novel_storage_path(novel, db)
|
||||
novel.last_viewed_at = utc_now()
|
||||
db.commit()
|
||||
return FileResponse(path, media_type="text/plain", filename=path.name)
|
||||
|
||||
|
||||
@router.get("/{novel_id}", response_model=ApiResponse[NovelOut])
|
||||
def get_novel(novel_id: str, current_user: CurrentUser, db: DbSession) -> ApiResponse[NovelOut]:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
novel.last_viewed_at = utc_now()
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return ApiResponse(data=NovelOut.model_validate(novel))
|
||||
|
||||
|
||||
@router.delete("/{novel_id}", response_model=ApiResponse[dict[str, bool]])
|
||||
def delete_novel(novel_id: str, current_user: CurrentUser, db: DbSession) -> ApiResponse[dict[str, bool]]:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
current_user.storage_used = max(0, current_user.storage_used - max(0, novel.file_size))
|
||||
db.delete(novel)
|
||||
db.commit()
|
||||
return ApiResponse(data={"ok": True})
|
||||
|
||||
|
||||
@router.post("/batch-delete", response_model=ApiResponse[dict[str, int]])
|
||||
def batch_delete_novels(
|
||||
payload: NovelBatchDeleteRequest,
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
) -> ApiResponse[dict[str, int]]:
|
||||
ids = sorted({item.strip() for item in payload.ids if item.strip()})
|
||||
series_ids = sorted({item.strip() for item in payload.series_ids if item.strip()})
|
||||
if not ids and not series_ids:
|
||||
return ApiResponse(data={"deleted": 0})
|
||||
|
||||
rows: list[Novel] = []
|
||||
if ids:
|
||||
rows.extend(
|
||||
db.scalars(
|
||||
select(Novel).where(
|
||||
Novel.user_id == current_user.id,
|
||||
Novel.id.in_(ids),
|
||||
)
|
||||
).all()
|
||||
)
|
||||
if series_ids:
|
||||
rows.extend(
|
||||
db.scalars(
|
||||
select(Novel).where(
|
||||
Novel.user_id == current_user.id,
|
||||
Novel.series_id.in_(series_ids),
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
deleted = 0
|
||||
released = 0
|
||||
seen: set[str] = set()
|
||||
for novel in rows:
|
||||
if novel.id in seen:
|
||||
continue
|
||||
seen.add(novel.id)
|
||||
released += max(0, novel.file_size)
|
||||
db.delete(novel)
|
||||
deleted += 1
|
||||
if deleted:
|
||||
current_user.storage_used = max(0, current_user.storage_used - released)
|
||||
db.commit()
|
||||
return ApiResponse(data={"deleted": deleted})
|
||||
|
||||
|
||||
@router.post("/{novel_id}/favorite", response_model=ApiResponse[NovelOut])
|
||||
def favorite_novel(novel_id: str, current_user: CurrentUser, db: DbSession) -> ApiResponse[NovelOut]:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
novel.is_favorite = True
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return ApiResponse(data=NovelOut.model_validate(novel))
|
||||
|
||||
|
||||
@router.delete("/{novel_id}/favorite", response_model=ApiResponse[NovelOut])
|
||||
def unfavorite_novel(novel_id: str, current_user: CurrentUser, db: DbSession) -> ApiResponse[NovelOut]:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
novel.is_favorite = False
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return ApiResponse(data=NovelOut.model_validate(novel))
|
||||
|
||||
|
||||
@router.post("/{novel_id}/progress", response_model=ApiResponse[NovelOut])
|
||||
def update_progress(
|
||||
novel_id: str,
|
||||
payload: ReadingProgressUpdate,
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
) -> ApiResponse[NovelOut]:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
novel.current_page = payload.current_page
|
||||
novel.last_read_at = utc_now()
|
||||
novel.last_viewed_at = novel.last_read_at
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return ApiResponse(data=NovelOut.model_validate(novel))
|
||||
|
||||
|
||||
@router.post("/{novel_id}/bookmark", response_model=ApiResponse[NovelOut])
|
||||
def update_bookmark(
|
||||
novel_id: str,
|
||||
payload: BookmarkUpdate,
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
) -> ApiResponse[NovelOut]:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
novel.bookmark = payload.bookmark
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return ApiResponse(data=NovelOut.model_validate(novel))
|
||||
|
||||
|
||||
@router.post("/{novel_id}/view", response_model=ApiResponse[NovelOut])
|
||||
def mark_novel_viewed(
|
||||
novel_id: str,
|
||||
payload: NovelViewUpdate,
|
||||
current_user: CurrentUser,
|
||||
db: DbSession,
|
||||
) -> ApiResponse[NovelOut]:
|
||||
novel = db.get(Novel, novel_id)
|
||||
if novel is None or novel.user_id != current_user.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Novel not found")
|
||||
if payload.viewed:
|
||||
novel.last_viewed_at = utc_now()
|
||||
db.commit()
|
||||
db.refresh(novel)
|
||||
return ApiResponse(data=NovelOut.model_validate(novel))
|
||||
Reference in new issue
Block a user