加入「拾味」:影评 / 读书随感
- 新增 reflections 应用:Work / WorkImage / Reflection 及迁移 - 条目分类(电影/书籍/其他),图片墙与随感时间线 - 浏览公开;新建、上传、写随感复用拾匣密码解锁 - 抽出 cabinet/access.py 共享解锁状态 - 首页新增「拾味」入口
This commit is contained in:
@@ -0,0 +1,230 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
from django import forms
|
||||
from django.db.models import Count, Prefetch
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import get_object_or_404, render
|
||||
from django.views.decorators.http import require_GET, require_POST
|
||||
|
||||
from cabinet.access import is_unlocked, minutes_left, unlock_minutes
|
||||
|
||||
from .models import Reflection, Work, WorkImage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_IMAGES = 10
|
||||
MAX_IMAGE_MB = 15
|
||||
KIND_KEYS = {key for key, _ in Work.KIND_CHOICES}
|
||||
|
||||
|
||||
class ImageUploadForm(forms.Form):
|
||||
image = forms.ImageField()
|
||||
|
||||
|
||||
def _locked():
|
||||
return JsonResponse({"error": "需要密码", "code": "locked"}, status=403)
|
||||
|
||||
|
||||
def _json_payload(request):
|
||||
try:
|
||||
data = json.loads(request.body or b"{}")
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def _base_context(request):
|
||||
return {
|
||||
"unlocked": is_unlocked(request),
|
||||
"minutes_left": minutes_left(request),
|
||||
"unlock_minutes": unlock_minutes(),
|
||||
}
|
||||
|
||||
|
||||
@require_GET
|
||||
def index(request):
|
||||
kind = request.GET.get("kind", "all")
|
||||
if kind != "all" and kind not in KIND_KEYS:
|
||||
kind = "all"
|
||||
|
||||
works = (
|
||||
Work.objects.annotate(
|
||||
image_count=Count("images", distinct=True),
|
||||
reflection_count=Count("reflections", distinct=True),
|
||||
)
|
||||
.prefetch_related(
|
||||
Prefetch("images", queryset=WorkImage.objects.order_by("created_at"))
|
||||
)
|
||||
.order_by("-created_at")
|
||||
)
|
||||
if kind != "all":
|
||||
works = works.filter(kind=kind)
|
||||
|
||||
counts = {"all": Work.objects.count()}
|
||||
for key in KIND_KEYS:
|
||||
counts[key] = Work.objects.filter(kind=key).count()
|
||||
|
||||
context = _base_context(request)
|
||||
context.update({
|
||||
"works": works,
|
||||
"kind": kind,
|
||||
"counts": counts,
|
||||
"kinds": Work.KIND_CHOICES,
|
||||
"kind_tabs": [
|
||||
{"key": key, "label": label, "count": counts[key]}
|
||||
for key, label in Work.KIND_CHOICES
|
||||
],
|
||||
})
|
||||
return render(request, "reflections/index.html", context)
|
||||
|
||||
|
||||
@require_GET
|
||||
def detail(request, work_id):
|
||||
work = get_object_or_404(
|
||||
Work.objects.prefetch_related("images", "reflections"), pk=work_id
|
||||
)
|
||||
context = _base_context(request)
|
||||
context["work"] = work
|
||||
return render(request, "reflections/detail.html", context)
|
||||
|
||||
|
||||
@require_POST
|
||||
def create_work(request):
|
||||
if not is_unlocked(request):
|
||||
return _locked()
|
||||
|
||||
data = _json_payload(request)
|
||||
if data is None:
|
||||
return JsonResponse({"error": "请求格式不对", "code": "bad_payload"}, status=400)
|
||||
|
||||
kind = str(data.get("kind") or "").strip()
|
||||
if kind not in KIND_KEYS:
|
||||
return JsonResponse({"error": "类型不对", "code": "bad_kind"}, status=400)
|
||||
|
||||
title = str(data.get("title") or "").strip()
|
||||
if not title or len(title) > 200:
|
||||
return JsonResponse({"error": "标题要 1-200 个字符", "code": "bad_title"}, status=400)
|
||||
|
||||
creator = str(data.get("creator") or "").strip()
|
||||
if len(creator) > 120:
|
||||
return JsonResponse({"error": "导演/作者最多 120 个字符", "code": "bad_creator"}, status=400)
|
||||
|
||||
year = None
|
||||
year_raw = data.get("year")
|
||||
if year_raw not in (None, ""):
|
||||
try:
|
||||
year = int(year_raw)
|
||||
except (TypeError, ValueError):
|
||||
return JsonResponse({"error": "年份不对", "code": "bad_year"}, status=400)
|
||||
if not 0 <= year <= 2100:
|
||||
return JsonResponse({"error": "年份超出范围", "code": "bad_year"}, status=400)
|
||||
|
||||
try:
|
||||
rating = int(data.get("rating") or 0)
|
||||
except (TypeError, ValueError):
|
||||
rating = 0
|
||||
if not 0 <= rating <= 5:
|
||||
return JsonResponse({"error": "评分要在 0-5 之间", "code": "bad_rating"}, status=400)
|
||||
|
||||
summary = str(data.get("summary") or "").strip()
|
||||
if len(summary) > 2000:
|
||||
return JsonResponse({"error": "简介最多 2000 个字符", "code": "bad_summary"}, status=400)
|
||||
|
||||
work = Work.objects.create(
|
||||
kind=kind,
|
||||
title=title,
|
||||
creator=creator,
|
||||
year=year,
|
||||
rating=rating,
|
||||
summary=summary,
|
||||
)
|
||||
logger.info("reflection work created: %s %r", work.id, work.title)
|
||||
return JsonResponse({"id": work.id}, status=201)
|
||||
|
||||
|
||||
@require_POST
|
||||
def create_reflection(request, work_id):
|
||||
if not is_unlocked(request):
|
||||
return _locked()
|
||||
|
||||
work = get_object_or_404(Work, pk=work_id)
|
||||
data = _json_payload(request)
|
||||
if data is None:
|
||||
return JsonResponse({"error": "请求格式不对", "code": "bad_payload"}, status=400)
|
||||
|
||||
content = str(data.get("content") or "").strip()
|
||||
if not content:
|
||||
return JsonResponse({"error": "写点什么再记下", "code": "empty"}, status=400)
|
||||
if len(content) > 5000:
|
||||
return JsonResponse({"error": "单条随感最多 5000 字", "code": "too_long"}, status=400)
|
||||
|
||||
note = Reflection.objects.create(work=work, content=content)
|
||||
return JsonResponse({
|
||||
"id": note.id,
|
||||
"content": note.content,
|
||||
"created_at": note.created_at.isoformat(),
|
||||
}, status=201)
|
||||
|
||||
|
||||
@require_POST
|
||||
def upload_images(request, work_id):
|
||||
if not is_unlocked(request):
|
||||
return _locked()
|
||||
|
||||
work = get_object_or_404(Work, pk=work_id)
|
||||
uploads = request.FILES.getlist("images")
|
||||
if not uploads:
|
||||
return JsonResponse({"error": "没有选中图片", "code": "empty"}, status=400)
|
||||
if len(uploads) > MAX_IMAGES:
|
||||
return JsonResponse(
|
||||
{"error": "一次最多上传 {} 张图片".format(MAX_IMAGES), "code": "too_many"},
|
||||
status=400,
|
||||
)
|
||||
|
||||
caption = str(request.POST.get("caption") or "").strip()[:200]
|
||||
max_bytes = MAX_IMAGE_MB * 1024 * 1024
|
||||
created, errors = [], []
|
||||
|
||||
for uploaded in uploads:
|
||||
if uploaded.size and uploaded.size > max_bytes:
|
||||
errors.append({"name": uploaded.name, "error": "超过 {} MB".format(MAX_IMAGE_MB)})
|
||||
continue
|
||||
|
||||
form = ImageUploadForm(files={"image": uploaded})
|
||||
if not form.is_valid():
|
||||
errors.append({"name": uploaded.name, "error": "不是有效的图片"})
|
||||
continue
|
||||
|
||||
image = WorkImage.objects.create(
|
||||
work=work,
|
||||
image=form.cleaned_data["image"],
|
||||
caption=caption,
|
||||
)
|
||||
created.append({"id": image.id, "url": image.image.url})
|
||||
|
||||
return JsonResponse(
|
||||
{"images": created, "errors": errors},
|
||||
status=201 if created else 400,
|
||||
)
|
||||
|
||||
|
||||
@require_POST
|
||||
def delete_reflection(request, reflection_id):
|
||||
if not is_unlocked(request):
|
||||
return _locked()
|
||||
|
||||
note = get_object_or_404(Reflection, pk=reflection_id)
|
||||
note.delete()
|
||||
return JsonResponse({"ok": True})
|
||||
|
||||
|
||||
@require_POST
|
||||
def delete_image(request, image_id):
|
||||
if not is_unlocked(request):
|
||||
return _locked()
|
||||
|
||||
image = get_object_or_404(WorkImage, pk=image_id)
|
||||
image.image.delete(save=False)
|
||||
image.delete()
|
||||
return JsonResponse({"ok": True})
|
||||
Reference in New Issue
Block a user