package server import ( "encoding/json" "fmt" "net/http" "os" "path/filepath" "strconv" "time" ) func (s *Server) pdfPageCount(documentHash string) int { result, _ := s.requestMetadataProjection(documentHash, "pdf") return result.PDFPages } func (s *Server) handlePDFPage(w http.ResponseWriter, r *http.Request) { revisionUUID := r.URL.Query().Get("rev") page, _ := strconv.Atoi(r.URL.Query().Get("page")) metadataOnly := r.URL.Query().Get("metadata") == "1" if revisionUUID == "" || (!metadataOnly && (page < 1 || page > 10000)) { http.Error(w, "invalid PDF page", http.StatusBadRequest) return } revision, err := s.store.GetRevisionMetadata(revisionUUID) if err != nil || revision.DocumentHash == "" { http.NotFound(w, r) return } domainUUID := s.domainUUIDForRequest(r) mode, modeErr := s.store.GetConfigInDomain(domainUUID, "authorization_mode") if modeErr != nil { http.Error(w, "forbidden", http.StatusForbidden) return } if mode != "enforcing" { inScope, scopeErr := s.store.ObjectInDomainAuthorityScope(domainUUID, revision.ObjectUUID) if scopeErr != nil || !inScope { http.NotFound(w, r) return } } if err := s.authorizeObjectForRequest(r, "read", revision.ObjectUUID); err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } if metadataOnly { s.serveMetadataProjection(w, r, revision.DocumentHash, "pdf", "", revision.UUID) return } if s.previewRoot == "" { http.Error(w, "preview storage unavailable", http.StatusServiceUnavailable) return } target := filepath.Join( s.previewRoot, fmt.Sprintf("%s-p%d.jpg", revision.DocumentHash, page), ) if info, statErr := os.Stat(target); statErr != nil || info.Size() == 0 { payload, marshalErr := json.Marshal(previewEventPayload{RevisionUUID: revision.UUID, DocumentHash: revision.DocumentHash, Filename: revision.Filename, Kind: "pdf-page", Page: page}) if marshalErr != nil { http.Error(w, marshalErr.Error(), http.StatusInternalServerError) return } queued, queueErr := s.store.EnqueueEvent("pdf.page.generate", revision.DocumentHash+":"+strconv.Itoa(page), string(payload), time.Now()) if queueErr != nil { http.Error(w, queueErr.Error(), http.StatusServiceUnavailable) return } s.wakeEventScheduler() w.Header().Set("Retry-After", "1") w.Header().Set("Cache-Control", "no-store") if queued { w.WriteHeader(http.StatusAccepted) } else { w.WriteHeader(http.StatusAccepted) } return } w.Header().Set("Content-Type", "image/jpeg") w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") w.Header().Set("Vary", "Authorization, Cookie") http.ServeFile(w, r, target) }