8e4fa6448e
Closes #136. Spec #136 end to end: `finished` becomes a fact about the Series, written only by the owner, and the reader-facing Lifecycle bucket is gone. ## What landed - **#157** — `series.finished_at bigint NOT NULL DEFAULT 0` plus the migration whose statement order is load-bearing (seed from the buckets, then flip them); both Lane queries lose the `HAVING COUNT(*) FILTER (WHERE b.status <> 'finished')` clause and gate on `finished_at = 0` instead, with the due-query/eligible-count force asymmetry kept deliberate and commented; `StatusFinished`, its API special-case 400, the web tab and the templates' Finished bucket deleted. - **#158** — owner Finish control on the Series detail page: confirm-gated finish, instant un-finish, admin accent (never ember, nothing is destroyed), `Store.SetSeriesFinished`, the two routes behind the owner gate, and the state displayed on the list row without offering the control there. - **#160** — reader side: derived `finished` bool on the flat Bookmark (`s.finished_at > 0`), rendered as a text-only label in both userscripts and on the web card; read-only inbound by omission from `Upsert`'s explicit `series` column list, same mechanism that already protects `cover`. - **#161** — glossary and the stale Reader-count divergence note catch up. - **#159** — `finished` joins the admin filter vocabulary (predicate `finished_at > 0`, label `Finished`, own aggregate count, figure last in the stats block as informational); the four clock-driven hygiene predicates (stale, never-checked, no-cover, no-chapter) exclude finished Series while unpollable, orphan and sighting-raised deliberately do not. ## Verification `go vet ./...` and `go test ./...` green on the merged branch (Docker-backed, throwaway `postgres:17-alpine` per package). Each ticket also passed a two-axis review (spec + standards) on its own branch before merge. Reviewed-on: #163 Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com> Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
175 lines
5.8 KiB
Go
175 lines
5.8 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"bookmarkmanager/backend/internal/httpmw"
|
|
"bookmarkmanager/backend/internal/store"
|
|
)
|
|
|
|
// Handler serves the userscript-facing JSON bookmark API.
|
|
type Handler struct {
|
|
Store *store.Store
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
if v != nil {
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
log.Printf("encode response: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// List returns all bookmarks of the acting Reader. GET /bookmarks
|
|
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
|
items, err := h.Store.List(httpmw.ReaderID(r))
|
|
if err != nil {
|
|
log.Printf("list: %v", err)
|
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, items)
|
|
}
|
|
|
|
// Put upserts one bookmark. PUT /bookmarks/{key}
|
|
func (h *Handler) Put(w http.ResponseWriter, r *http.Request) {
|
|
key := r.PathValue("key")
|
|
if key == "" {
|
|
http.Error(w, "missing key", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var b store.Bookmark
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16)).Decode(&b); err != nil {
|
|
http.Error(w, "invalid JSON body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
// A body may carry a cover, and it is discarded here rather than
|
|
// rejected: an older installed userscript may still send one, and
|
|
// ADR-0004's compatibility argument depends on those scripts continuing
|
|
// to work. The Cover is acquired server-side (ADR-0007), so the field is
|
|
// permanently inert - not pending removal, and not a value any later code
|
|
// should start reading.
|
|
b.Cover = ""
|
|
|
|
// Path key is authoritative; derive site/series_id from it when the body
|
|
// omits them so the stored row is always self-consistent.
|
|
b.Key = key
|
|
if b.Site == "" || b.SeriesID == "" {
|
|
if site, series, ok := strings.Cut(key, ":"); ok {
|
|
if b.Site == "" {
|
|
b.Site = site
|
|
}
|
|
if b.SeriesID == "" {
|
|
b.SeriesID = series
|
|
}
|
|
}
|
|
}
|
|
|
|
// An empty status is "no opinion" and Upsert keeps the stored bucket.
|
|
// Anything else outside the two lifecycle buckets is a client bug, not
|
|
// something to silently coerce — finished included, which is no longer a
|
|
// bucket at all (issue #157).
|
|
switch b.Status {
|
|
case "", store.StatusReading, store.StatusArchived:
|
|
default:
|
|
http.Error(w, "invalid status", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Same rule as status: empty means "keep the stored value". An unknown
|
|
// value is a client bug, not something to silently coerce to manga.
|
|
switch b.Kind {
|
|
case "", store.KindManga, store.KindNovel:
|
|
default:
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid kind"})
|
|
return
|
|
}
|
|
|
|
// Candidate timestamp, not a decision: Upsert keeps the stored one unless
|
|
// reading progress actually moved. Any client value is ignored.
|
|
b.UpdatedAt = time.Now().UnixMilli()
|
|
|
|
// A userscript PUT is a Sighting: the Reader's browser was on the Series
|
|
// page and read its Latest Chapter (issue #103). Recorded before the
|
|
// Upsert, which is what makes the raise comparison possible, and never
|
|
// from the web UI's own read-modify-write — a Reader toggling a favourite
|
|
// has not looked at the Site and must not postpone a Poll. A failure here
|
|
// costs a deferral, not the write, so it is logged and dropped.
|
|
readerID := httpmw.ReaderID(r)
|
|
if err := h.Store.RecordSighting(readerID, b.Site, b.SeriesID, b.LatestChapterNum, b.UpdatedAt); err != nil {
|
|
log.Printf("record sighting: %v", err)
|
|
}
|
|
|
|
stored, err := h.Store.Upsert(readerID, b)
|
|
if err != nil {
|
|
log.Printf("upsert: %v", err)
|
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
// Echo the stored row: clients adopt this as their cached copy, so it must
|
|
// carry the authoritative updated_at rather than the candidate above.
|
|
writeJSON(w, http.StatusOK, stored)
|
|
}
|
|
|
|
// Delete removes one bookmark. DELETE /bookmarks/{key}
|
|
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
|
key := r.PathValue("key")
|
|
if key == "" {
|
|
http.Error(w, "missing key", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := h.Store.Delete(httpmw.ReaderID(r), key); err != nil {
|
|
log.Printf("delete: %v", err)
|
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// Healthz answers the unauthenticated liveness check. GET /healthz
|
|
func Healthz(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/plain")
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte("ok"))
|
|
}
|
|
|
|
// Cover serves stored cover bytes. GET /covers/{address}
|
|
//
|
|
// Public on purpose: the userscript renders these on Sites the deployment
|
|
// does not control, where no credential of ours may be sent, and the address
|
|
// is the SHA-256 of a URL the Site already publishes (ADR-0007). An unknown
|
|
// address is a 404 rather than an error - "no Cover yet" is a normal state,
|
|
// and the clients fall back to their placeholder.
|
|
func (h *Handler) Cover(w http.ResponseWriter, r *http.Request) {
|
|
body, contentType, ok, err := h.Store.CoverByAddress(r.PathValue("address"))
|
|
if err != nil {
|
|
log.Printf("cover: %v", err)
|
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if !ok {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
// Refuse anything the write gate would not have recorded: a poisoned row
|
|
// (migrated data, a writer that skips the gate) must never be echoed back
|
|
// as bytes of a type no Cover may have.
|
|
if _, ok := store.CoverContentType(contentType); !ok {
|
|
log.Printf("cover %s: refusing non-image content type %q", r.PathValue("address"), contentType)
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", contentType)
|
|
// Content-addressed, so the bytes at this URL can never change. Public
|
|
// rather than private: no credential gates the route.
|
|
w.Header().Set("Cache-Control", "public, max-age=604800, immutable")
|
|
_, _ = w.Write(body)
|
|
}
|