Archived
feat: monorepo structure with Django backend, React frontend, and Expo mobile app
- Backend: Django 5 + DRF with accounts, documents, collections, and reading apps - Custom User model with email-based auth, JWT via SimpleJWT - Full CRUD viewsets with ModelSerializer + DRF routers - pytest, Ruff, drf-spectacular (OpenAPI), whitenoise - Dockerfile for production deployment - Frontend: React 18 + TypeScript + Vite - Lazy-loaded routes with ProtectedRoute/PublicRoute guards - Auth context with useReducer, token refresh interceptor - Pages: Login, Register, Library, Document Detail, Reader, Collections, Settings - Dark theme, responsive grid layout, Vite proxy to Django backend - Mobile: Expo SDK 51 + React Native + Expo Router - File-based routing with login, register, and library screens - AsyncStorage for token persistence, token refresh interceptor - Shared API types via @cloud-reader/shared workspace package - Shared: TypeScript types (API responses, auth, documents, etc.) - CI/CD: 3 independent GitHub Actions pipelines (backend, frontend, mobile)
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import User
|
||||
|
||||
|
||||
@admin.register(User)
|
||||
class UserAdmin(admin.ModelAdmin):
|
||||
list_display = ["email", "display_name", "is_verified", "is_active", "date_joined"]
|
||||
search_fields = ["email", "display_name"]
|
||||
list_filter = ["is_verified", "is_active"]
|
||||
@@ -0,0 +1,29 @@
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
from django.db import models
|
||||
|
||||
|
||||
class User(AbstractUser):
|
||||
"""Custom user model for Cloud Reader."""
|
||||
|
||||
email = models.EmailField(unique=True)
|
||||
display_name = models.CharField(max_length=150, blank=True)
|
||||
avatar = models.ImageField(upload_to="avatars/", blank=True, null=True)
|
||||
is_verified = models.BooleanField(default=False)
|
||||
reading_preferences = models.JSONField(default=dict, blank=True)
|
||||
|
||||
USERNAME_FIELD = "email"
|
||||
REQUIRED_FIELDS = ["username"]
|
||||
|
||||
class Meta:
|
||||
db_table = "accounts_user"
|
||||
verbose_name = "User"
|
||||
verbose_name_plural = "Users"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.email
|
||||
|
||||
@property
|
||||
def avatar_url(self) -> str | None:
|
||||
if self.avatar:
|
||||
return self.avatar.url
|
||||
return None
|
||||
@@ -0,0 +1,53 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import User
|
||||
|
||||
UserModel = get_user_model()
|
||||
|
||||
|
||||
class RegisterSerializer(serializers.ModelSerializer[User]):
|
||||
password = serializers.CharField(write_only=True, min_length=8)
|
||||
password_confirm = serializers.CharField(write_only=True, min_length=8)
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ["email", "username", "display_name", "password", "password_confirm"]
|
||||
|
||||
def validate(self, attrs):
|
||||
if attrs["password"] != attrs.pop("password_confirm"):
|
||||
raise serializers.ValidationError({"password_confirm": "Passwords do not match."})
|
||||
return attrs
|
||||
|
||||
def create(self, validated_data):
|
||||
password = validated_data.pop("password")
|
||||
user = UserModel(**validated_data)
|
||||
user.set_password(password)
|
||||
user.save()
|
||||
return user
|
||||
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer[User]):
|
||||
avatar_url = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = [
|
||||
"id", "email", "username", "display_name", "avatar_url",
|
||||
"date_joined", "is_verified", "reading_preferences",
|
||||
]
|
||||
read_only_fields = ["id", "email", "date_joined", "is_verified"]
|
||||
|
||||
def get_avatar_url(self, obj: User) -> str | None:
|
||||
return obj.avatar_url
|
||||
|
||||
|
||||
class ChangePasswordSerializer(serializers.Serializer):
|
||||
old_password = serializers.CharField(required=True)
|
||||
new_password = serializers.CharField(required=True, min_length=8)
|
||||
|
||||
def validate_old_password(self, value: str) -> str:
|
||||
user = self.context["request"].user
|
||||
if not user.check_password(value):
|
||||
raise serializers.ValidationError("Current password is incorrect.")
|
||||
return value
|
||||
@@ -0,0 +1,14 @@
|
||||
from django.urls import path
|
||||
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
|
||||
|
||||
from . import views
|
||||
|
||||
app_name = "accounts"
|
||||
|
||||
urlpatterns = [
|
||||
path("register/", views.RegisterView.as_view(), name="register"),
|
||||
path("me/", views.UserDetailView.as_view(), name="user-detail"),
|
||||
path("change-password/", views.ChangePasswordView.as_view(), name="change-password"),
|
||||
path("token/", TokenObtainPairView.as_view(), name="token-obtain"),
|
||||
path("token/refresh/", TokenRefreshView.as_view(), name="token-refresh"),
|
||||
]
|
||||
@@ -0,0 +1,36 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from rest_framework import generics, permissions, status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from .serializers import ChangePasswordSerializer, RegisterSerializer, UserSerializer
|
||||
|
||||
UserModel = get_user_model()
|
||||
|
||||
|
||||
class RegisterView(generics.CreateAPIView):
|
||||
"""Create a new user account."""
|
||||
queryset = UserModel.objects.all()
|
||||
serializer_class = RegisterSerializer
|
||||
permission_classes = [permissions.AllowAny]
|
||||
|
||||
|
||||
class UserDetailView(generics.RetrieveUpdateAPIView):
|
||||
"""Get or update the authenticated user's profile."""
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def get_object(self):
|
||||
return self.request.user
|
||||
|
||||
|
||||
class ChangePasswordView(APIView):
|
||||
"""Change the authenticated user's password."""
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def post(self, request):
|
||||
serializer = ChangePasswordSerializer(data=request.data, context={"request": request})
|
||||
serializer.is_valid(raise_exception=True)
|
||||
request.user.set_password(serializer.validated_data["new_password"])
|
||||
request.user.save()
|
||||
return Response({"detail": "Password changed successfully."}, status=status.HTTP_200_OK)
|
||||
@@ -0,0 +1,10 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import Collection
|
||||
|
||||
|
||||
@admin.register(Collection)
|
||||
class CollectionAdmin(admin.ModelAdmin):
|
||||
list_display = ["name", "owner", "document_count", "is_public", "created_at"]
|
||||
list_filter = ["is_public"]
|
||||
search_fields = ["name", "description"]
|
||||
@@ -0,0 +1,39 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class Collection(models.Model):
|
||||
"""A user-created collection of documents."""
|
||||
name = models.CharField(max_length=300)
|
||||
description = models.TextField(blank=True, default="")
|
||||
cover = models.ImageField(upload_to="collection_covers/", blank=True, null=True)
|
||||
documents = models.ManyToManyField(
|
||||
"documents.Document",
|
||||
related_name="collections",
|
||||
blank=True,
|
||||
)
|
||||
is_public = models.BooleanField(default=False)
|
||||
owner = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="collections",
|
||||
)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "collections_collection"
|
||||
ordering = ["-updated_at"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
@property
|
||||
def document_count(self) -> int:
|
||||
return self.documents.count()
|
||||
|
||||
@property
|
||||
def cover_url(self) -> str | None:
|
||||
if self.cover:
|
||||
return self.cover.url
|
||||
return None
|
||||
@@ -0,0 +1,33 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import Collection
|
||||
|
||||
|
||||
class CollectionSerializer(serializers.ModelSerializer[Collection]):
|
||||
cover_url = serializers.SerializerMethodField()
|
||||
document_count = serializers.IntegerField(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Collection
|
||||
fields = [
|
||||
"id", "name", "description", "cover_url", "document_count",
|
||||
"is_public", "created_at", "updated_at",
|
||||
]
|
||||
read_only_fields = ["id", "document_count", "created_at", "updated_at"]
|
||||
|
||||
def get_cover_url(self, obj: Collection) -> str | None:
|
||||
return obj.cover_url
|
||||
|
||||
|
||||
class CollectionDetailSerializer(CollectionSerializer):
|
||||
documents = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
|
||||
|
||||
class Meta(CollectionSerializer.Meta):
|
||||
fields = CollectionSerializer.Meta.fields + ["documents", "owner"]
|
||||
|
||||
|
||||
class CollectionDocumentActionSerializer(serializers.Serializer):
|
||||
document_ids = serializers.ListField(
|
||||
child=serializers.IntegerField(),
|
||||
allow_empty=False,
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from django.urls import include, path
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from . import views
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register("", views.CollectionViewSet, basename="collection")
|
||||
|
||||
app_name = "collections"
|
||||
|
||||
urlpatterns = [
|
||||
path("", include(router.urls)),
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
from rest_framework import permissions, status, viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
|
||||
from apps.documents.models import Document
|
||||
|
||||
from .models import Collection
|
||||
from .serializers import (
|
||||
CollectionDetailSerializer,
|
||||
CollectionDocumentActionSerializer,
|
||||
CollectionSerializer,
|
||||
)
|
||||
|
||||
|
||||
class CollectionViewSet(viewsets.ModelViewSet):
|
||||
"""CRUD for user collections."""
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.action in ("retrieve", "update", "partial_update"):
|
||||
return CollectionDetailSerializer
|
||||
return CollectionSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
return Collection.objects.filter(owner=self.request.user).prefetch_related("documents")
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
@action(detail=True, methods=["post"])
|
||||
def add_documents(self, request, pk=None):
|
||||
"""Add documents to a collection."""
|
||||
collection = self.get_object()
|
||||
serializer = CollectionDocumentActionSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
docs = Document.objects.filter(
|
||||
id__in=serializer.validated_data["document_ids"],
|
||||
owner=request.user,
|
||||
)
|
||||
collection.documents.add(*docs)
|
||||
return Response({"detail": f"Added {docs.count()} document(s)."}, status=status.HTTP_200_OK)
|
||||
|
||||
@action(detail=True, methods=["post"])
|
||||
def remove_documents(self, request, pk=None):
|
||||
"""Remove documents from a collection."""
|
||||
collection = self.get_object()
|
||||
serializer = CollectionDocumentActionSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
collection.documents.remove(*serializer.validated_data["document_ids"])
|
||||
return Response({"detail": "Documents removed."}, status=status.HTTP_200_OK)
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import Document
|
||||
|
||||
|
||||
@admin.register(Document)
|
||||
class DocumentAdmin(admin.ModelAdmin):
|
||||
list_display = ["title", "author", "file_type", "file_size", "is_public", "owner", "uploaded_at"]
|
||||
list_filter = ["file_type", "is_public"]
|
||||
search_fields = ["title", "author", "description"]
|
||||
date_hierarchy = "uploaded_at"
|
||||
@@ -0,0 +1,48 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class Document(models.Model):
|
||||
"""A digital document (ebook, PDF, etc.) uploaded by a user."""
|
||||
|
||||
class FileType(models.TextChoices):
|
||||
PDF = "pdf", "PDF"
|
||||
EPUB = "epub", "EPUB"
|
||||
MOBI = "mobi", "MOBI"
|
||||
TXT = "txt", "Plain Text"
|
||||
DOCX = "docx", "Word Document"
|
||||
|
||||
title = models.CharField(max_length=500)
|
||||
author = models.CharField(max_length=300, blank=True, null=True)
|
||||
description = models.TextField(blank=True, default="")
|
||||
cover = models.ImageField(upload_to="covers/", blank=True, null=True)
|
||||
file = models.FileField(upload_to="documents/")
|
||||
file_type = models.CharField(max_length=10, choices=FileType.choices)
|
||||
file_size = models.PositiveIntegerField(help_text="File size in bytes")
|
||||
page_count = models.PositiveIntegerField(blank=True, null=True)
|
||||
tags = models.JSONField(default=list, blank=True)
|
||||
is_public = models.BooleanField(default=False)
|
||||
owner = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="documents",
|
||||
)
|
||||
uploaded_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "documents_document"
|
||||
ordering = ["-uploaded_at"]
|
||||
indexes = [
|
||||
models.Index(fields=["owner", "-uploaded_at"]),
|
||||
models.Index(fields=["file_type"]),
|
||||
]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.title
|
||||
|
||||
@property
|
||||
def cover_url(self) -> str | None:
|
||||
if self.cover:
|
||||
return self.cover.url
|
||||
return None
|
||||
@@ -0,0 +1,41 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import Document
|
||||
|
||||
|
||||
class DocumentListSerializer(serializers.ModelSerializer[Document]):
|
||||
cover_url = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = Document
|
||||
fields = [
|
||||
"id", "title", "author", "cover_url", "description",
|
||||
"file_type", "file_size", "page_count", "tags",
|
||||
"is_public", "uploaded_at", "updated_at",
|
||||
]
|
||||
read_only_fields = ["id", "uploaded_at", "updated_at"]
|
||||
|
||||
def get_cover_url(self, obj: Document) -> str | None:
|
||||
return obj.cover_url
|
||||
|
||||
|
||||
class DocumentDetailSerializer(DocumentListSerializer):
|
||||
owner = serializers.PrimaryKeyRelatedField(read_only=True)
|
||||
|
||||
class Meta(DocumentListSerializer.Meta):
|
||||
fields = DocumentListSerializer.Meta.fields + ["owner", "file"]
|
||||
|
||||
|
||||
class DocumentUploadSerializer(serializers.ModelSerializer[Document]):
|
||||
class Meta:
|
||||
model = Document
|
||||
fields = [
|
||||
"title", "author", "description", "cover", "file",
|
||||
"file_type", "file_size", "page_count", "tags", "is_public",
|
||||
]
|
||||
|
||||
def validate_file_size(self, value: int) -> int:
|
||||
max_size = 100 * 1024 * 1024 # 100 MB
|
||||
if value > max_size:
|
||||
raise serializers.ValidationError("File size must not exceed 100 MB.")
|
||||
return value
|
||||
@@ -0,0 +1,13 @@
|
||||
from django.urls import include, path
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from . import views
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register("", views.DocumentViewSet, basename="document")
|
||||
|
||||
app_name = "documents"
|
||||
|
||||
urlpatterns = [
|
||||
path("", include(router.urls)),
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
from rest_framework import permissions, viewsets
|
||||
|
||||
from .models import Document
|
||||
from .serializers import DocumentDetailSerializer, DocumentListSerializer, DocumentUploadSerializer
|
||||
|
||||
|
||||
class IsOwnerOrPublic(permissions.BasePermission):
|
||||
"""Allow access if user is owner or the document is public."""
|
||||
|
||||
def has_object_permission(self, request, view, obj: Document) -> bool:
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
return obj.is_public or obj.owner == request.user
|
||||
return obj.owner == request.user
|
||||
|
||||
|
||||
class DocumentViewSet(viewsets.ModelViewSet):
|
||||
"""CRUD for documents with owner-scoping."""
|
||||
permission_classes = [permissions.IsAuthenticated, IsOwnerOrPublic]
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.action == "create":
|
||||
return DocumentUploadSerializer
|
||||
if self.action in ("retrieve", "update", "partial_update"):
|
||||
return DocumentDetailSerializer
|
||||
return DocumentListSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
user = self.request.user
|
||||
qs = Document.objects.select_related("owner")
|
||||
if self.action == "list":
|
||||
return qs.filter(owner=user) | qs.filter(is_public=True)
|
||||
return qs
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(owner=self.request.user)
|
||||
@@ -0,0 +1,21 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import Bookmark, Highlight, ReadingProgress
|
||||
|
||||
|
||||
@admin.register(Bookmark)
|
||||
class BookmarkAdmin(admin.ModelAdmin):
|
||||
list_display = ["document", "user", "page", "label", "created_at"]
|
||||
list_filter = ["created_at"]
|
||||
|
||||
|
||||
@admin.register(Highlight)
|
||||
class HighlightAdmin(admin.ModelAdmin):
|
||||
list_display = ["document", "user", "page", "color", "created_at"]
|
||||
list_filter = ["color", "created_at"]
|
||||
|
||||
|
||||
@admin.register(ReadingProgress)
|
||||
class ReadingProgressAdmin(admin.ModelAdmin):
|
||||
list_display = ["document", "user", "percentage", "last_read_at"]
|
||||
date_hierarchy = "last_read_at"
|
||||
@@ -0,0 +1,84 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class Bookmark(models.Model):
|
||||
"""A user bookmark at a specific page in a document."""
|
||||
document = models.ForeignKey(
|
||||
"documents.Document",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="bookmarks",
|
||||
)
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="bookmarks",
|
||||
)
|
||||
page = models.PositiveIntegerField()
|
||||
label = models.CharField(max_length=300, blank=True, default="")
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "reading_bookmark"
|
||||
ordering = ["page"]
|
||||
unique_together = [["document", "user", "page"]]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.document.title} p.{self.page}"
|
||||
|
||||
|
||||
class Highlight(models.Model):
|
||||
"""A highlighted passage in a document."""
|
||||
document = models.ForeignKey(
|
||||
"documents.Document",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="highlights",
|
||||
)
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="highlights",
|
||||
)
|
||||
page = models.PositiveIntegerField()
|
||||
color = models.CharField(max_length=20, default="yellow")
|
||||
text = models.TextField()
|
||||
note = models.TextField(blank=True, null=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "reading_highlight"
|
||||
ordering = ["-created_at"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"Highlight on {self.document.title} p.{self.page}"
|
||||
|
||||
|
||||
class ReadingProgress(models.Model):
|
||||
"""Tracks the user's reading progress through a document."""
|
||||
document = models.ForeignKey(
|
||||
"documents.Document",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="reading_progress",
|
||||
)
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="reading_progress",
|
||||
)
|
||||
current_page = models.PositiveIntegerField(default=1)
|
||||
total_pages = models.PositiveIntegerField(default=0)
|
||||
percentage = models.FloatField(default=0.0)
|
||||
last_read_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "reading_progress"
|
||||
unique_together = [["document", "user"]]
|
||||
verbose_name_plural = "Reading progress"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.document.title} — {self.percentage:.0f}%"
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if self.total_pages > 0:
|
||||
self.percentage = round((self.current_page / self.total_pages) * 100, 1)
|
||||
super().save(*args, **kwargs)
|
||||
@@ -0,0 +1,35 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import Bookmark, Highlight, ReadingProgress
|
||||
|
||||
|
||||
class BookmarkSerializer(serializers.ModelSerializer[Bookmark]):
|
||||
class Meta:
|
||||
model = Bookmark
|
||||
fields = ["id", "document", "page", "label", "created_at"]
|
||||
read_only_fields = ["id", "created_at"]
|
||||
|
||||
|
||||
class HighlightSerializer(serializers.ModelSerializer[Highlight]):
|
||||
class Meta:
|
||||
model = Highlight
|
||||
fields = ["id", "document", "page", "color", "text", "note", "created_at"]
|
||||
read_only_fields = ["id", "created_at"]
|
||||
|
||||
|
||||
class ReadingProgressSerializer(serializers.ModelSerializer[ReadingProgress]):
|
||||
class Meta:
|
||||
model = ReadingProgress
|
||||
fields = ["id", "document", "current_page", "total_pages", "percentage", "last_read_at"]
|
||||
read_only_fields = ["id", "percentage", "last_read_at"]
|
||||
|
||||
|
||||
class ReadingProgressUpdateSerializer(serializers.ModelSerializer[ReadingProgress]):
|
||||
class Meta:
|
||||
model = ReadingProgress
|
||||
fields = ["current_page", "total_pages"]
|
||||
|
||||
def validate_current_page(self, value: int) -> int:
|
||||
if value < 1:
|
||||
raise serializers.ValidationError("Page must be at least 1.")
|
||||
return value
|
||||
@@ -0,0 +1,15 @@
|
||||
from django.urls import include, path
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from . import views
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register("bookmarks", views.BookmarkViewSet, basename="bookmark")
|
||||
router.register("highlights", views.HighlightViewSet, basename="highlight")
|
||||
router.register("progress", views.ReadingProgressViewSet, basename="reading-progress")
|
||||
|
||||
app_name = "reading"
|
||||
|
||||
urlpatterns = [
|
||||
path("", include(router.urls)),
|
||||
]
|
||||
@@ -0,0 +1,49 @@
|
||||
from rest_framework import permissions, viewsets
|
||||
|
||||
from .models import Bookmark, Highlight, ReadingProgress
|
||||
from .serializers import (
|
||||
BookmarkSerializer,
|
||||
HighlightSerializer,
|
||||
ReadingProgressSerializer,
|
||||
ReadingProgressUpdateSerializer,
|
||||
)
|
||||
|
||||
|
||||
class BookmarkViewSet(viewsets.ModelViewSet):
|
||||
"""User bookmarks for documents."""
|
||||
serializer_class = BookmarkSerializer
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def get_queryset(self):
|
||||
return Bookmark.objects.filter(user=self.request.user).select_related("document")
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(user=self.request.user)
|
||||
|
||||
|
||||
class HighlightViewSet(viewsets.ModelViewSet):
|
||||
"""User highlights for documents."""
|
||||
serializer_class = HighlightSerializer
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def get_queryset(self):
|
||||
return Highlight.objects.filter(user=self.request.user).select_related("document")
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(user=self.request.user)
|
||||
|
||||
|
||||
class ReadingProgressViewSet(viewsets.ModelViewSet):
|
||||
"""Reading progress tracker."""
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.action in ("create", "update", "partial_update"):
|
||||
return ReadingProgressUpdateSerializer
|
||||
return ReadingProgressSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
return ReadingProgress.objects.filter(user=self.request.user).select_related("document")
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(user=self.request.user)
|
||||
Reference in New Issue
Block a user