Add self-hosted RCS backend, extension, and ops tooling
Ship the Go/SQLite API and Web UI, Chrome/Brave capture addon, Docker Compose, Pangolin reverse-proxy support, and a user-crontab watchdog so the binary stays running without systemd.
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
FROM golang:1.24-bookworm AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 go build -o /out/rcs ./cmd/rcs
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/rcs /app/rcs
|
||||
ENV RCS_ADDR=0.0.0.0:8080
|
||||
ENV RCS_DATA_DIR=/data
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/app/rcs"]
|
||||
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/squid/rcs/backend/internal/api"
|
||||
"github.com/squid/rcs/backend/internal/config"
|
||||
"github.com/squid/rcs/backend/internal/db"
|
||||
"github.com/squid/rcs/backend/internal/imgur"
|
||||
"github.com/squid/rcs/backend/internal/web"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
|
||||
if err := os.MkdirAll(cfg.ScreenshotDir, 0o755); err != nil {
|
||||
log.Fatalf("create screenshot dir: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.DBPath), 0o755); err != nil {
|
||||
log.Fatalf("create db dir: %v", err)
|
||||
}
|
||||
|
||||
store, err := db.Open(cfg.DBPath)
|
||||
if err != nil {
|
||||
log.Fatalf("open db: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
imgurClient := imgur.New(cfg.ImgurClientID)
|
||||
webUI, err := web.New(cfg, store, imgurClient)
|
||||
if err != nil {
|
||||
log.Fatalf("web ui: %v", err)
|
||||
}
|
||||
|
||||
server := api.New(cfg, store, imgurClient, webUI)
|
||||
|
||||
fmt.Printf("RCS backend listening on http://%s\n", cfg.Addr)
|
||||
fmt.Printf(" data dir: %s\n", cfg.DataDir)
|
||||
fmt.Printf(" db: %s\n", cfg.DBPath)
|
||||
if cfg.PublicBaseURL != "" {
|
||||
fmt.Printf(" public: %s\n", cfg.PublicBaseURL)
|
||||
}
|
||||
if cfg.TrustProxy {
|
||||
fmt.Println(" proxy: trusting X-Forwarded-* headers")
|
||||
}
|
||||
if cfg.APIKey != "" {
|
||||
fmt.Println(" api key: enabled")
|
||||
} else {
|
||||
fmt.Println(" api key: disabled (open)")
|
||||
}
|
||||
if imgurClient.Enabled() {
|
||||
fmt.Println(" imgur: enabled")
|
||||
} else {
|
||||
fmt.Println(" imgur: disabled (set IMGUR_CLIENT_ID)")
|
||||
}
|
||||
|
||||
if err := http.ListenAndServe(cfg.Addr, server.Handler()); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
module github.com/squid/rcs/backend
|
||||
|
||||
go 1.24.5
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.3.1
|
||||
github.com/go-chi/cors v1.2.2
|
||||
modernc.org/sqlite v1.34.5
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.22.0 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.8.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
|
||||
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
|
||||
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
||||
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
|
||||
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
|
||||
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
|
||||
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
|
||||
modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
|
||||
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
|
||||
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
|
||||
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
|
||||
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
|
||||
modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
|
||||
modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
|
||||
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
|
||||
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
|
||||
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
|
||||
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
|
||||
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
|
||||
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
|
||||
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
|
||||
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
|
||||
modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g=
|
||||
modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE=
|
||||
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
|
||||
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,521 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
"github.com/squid/rcs/backend/internal/config"
|
||||
"github.com/squid/rcs/backend/internal/db"
|
||||
"github.com/squid/rcs/backend/internal/imgur"
|
||||
"github.com/squid/rcs/backend/internal/web"
|
||||
)
|
||||
|
||||
// Server is the HTTP API and Web UI.
|
||||
type Server struct {
|
||||
cfg config.Config
|
||||
store *db.Store
|
||||
imgur *imgur.Client
|
||||
router chi.Router
|
||||
webUI *web.UI
|
||||
}
|
||||
|
||||
// New builds the HTTP server with routes.
|
||||
func New(cfg config.Config, store *db.Store, imgurClient *imgur.Client, webUI *web.UI) *Server {
|
||||
s := &Server{
|
||||
cfg: cfg,
|
||||
store: store,
|
||||
imgur: imgurClient,
|
||||
webUI: webUI,
|
||||
}
|
||||
s.router = s.routes()
|
||||
return s
|
||||
}
|
||||
|
||||
// Handler returns the root HTTP handler.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.router
|
||||
}
|
||||
|
||||
func (s *Server) routes() chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
if s.cfg.TrustProxy {
|
||||
r.Use(trustForwardedHeaders)
|
||||
}
|
||||
r.Use(privateNetworkAccess)
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-API-Key"},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 300,
|
||||
}))
|
||||
|
||||
r.Get("/api/health", s.handleHealth)
|
||||
|
||||
r.Group(func(protected chi.Router) {
|
||||
protected.Use(s.apiKeyMiddleware)
|
||||
protected.Get("/api/comments/exists", s.handleCommentExists)
|
||||
protected.Get("/api/posts/exists", s.handlePostExists)
|
||||
protected.Post("/api/comments", s.handleSaveComment)
|
||||
protected.Post("/api/comments/{id}/screenshot", s.handleAttachScreenshot)
|
||||
protected.Post("/api/posts", s.handleSavePost)
|
||||
protected.Get("/api/search", s.handleSearchJSON)
|
||||
protected.Post("/api/comments/{id}/imgur", s.handleImgurExport)
|
||||
protected.Get("/api/blocklist", s.handleListBlocklist)
|
||||
protected.Put("/api/blocklist", s.handleReplaceBlocklist)
|
||||
protected.Post("/api/blocklist", s.handleAddBlocked)
|
||||
protected.Delete("/api/blocklist/{username}", s.handleRemoveBlocked)
|
||||
})
|
||||
|
||||
r.Get("/screenshots/{file}", s.handleScreenshot)
|
||||
r.Get("/", s.webUI.HandleIndex)
|
||||
r.Post("/export/{id}", s.webUI.HandleExport)
|
||||
r.Handle("/static/*", s.webUI.StaticHandler())
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (s *Server) apiKeyMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.cfg.APIKey == "" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("X-API-Key")
|
||||
if key == "" {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(strings.ToLower(auth), "bearer ") {
|
||||
key = strings.TrimSpace(auth[7:])
|
||||
}
|
||||
}
|
||||
if key != s.cfg.APIKey {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// privateNetworkAccess allows Chrome pages on public origins (e.g. reddit.com)
|
||||
// to call a localhost/LAN backend (CORS Private Network Access preflight).
|
||||
func privateNetworkAccess(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Private-Network", "true")
|
||||
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Private-Network") == "true" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-API-Key")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// trustForwardedHeaders applies X-Forwarded-Host / X-Forwarded-Proto from a trusted reverse proxy.
|
||||
func trustForwardedHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if host := firstForwardedValue(r.Header.Get("X-Forwarded-Host")); host != "" {
|
||||
r.Host = host
|
||||
}
|
||||
if proto := firstForwardedValue(r.Header.Get("X-Forwarded-Proto")); proto != "" && r.URL != nil {
|
||||
r.URL.Scheme = proto
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func firstForwardedValue(header string) string {
|
||||
if header == "" {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(header, ",")
|
||||
return strings.TrimSpace(parts[0])
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"imgur": s.imgur.Enabled(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleCommentExists(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(r.URL.Query().Get("id"))
|
||||
if id == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id required"})
|
||||
return
|
||||
}
|
||||
status, err := s.store.GetCommentCaptureStatus(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, status)
|
||||
}
|
||||
|
||||
func (s *Server) handleAttachScreenshot(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(chi.URLParam(r, "id"))
|
||||
if id == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id required"})
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
ScreenshotBase64 string `json:"screenshot_base64"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 20<<20)).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.ScreenshotBase64) == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "screenshot_base64 required"})
|
||||
return
|
||||
}
|
||||
|
||||
status, err := s.store.GetCommentCaptureStatus(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !status.Exists {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "comment not found"})
|
||||
return
|
||||
}
|
||||
if status.HasScreenshot {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"updated": false,
|
||||
"has_screenshot": true,
|
||||
"screenshot_path": status.ScreenshotPath,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
path, err := s.saveScreenshot(id, req.ScreenshotBase64)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
updated, err := s.store.SetCommentScreenshot(r.Context(), id, path)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"updated": updated,
|
||||
"has_screenshot": true,
|
||||
"screenshot_path": path,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePostExists(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(r.URL.Query().Get("id"))
|
||||
if id == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id required"})
|
||||
return
|
||||
}
|
||||
exists, err := s.store.PostExists(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"exists": exists})
|
||||
}
|
||||
|
||||
type saveCommentRequest struct {
|
||||
RedditCommentID string `json:"reddit_comment_id"`
|
||||
Body string `json:"body"`
|
||||
AuthorID string `json:"author_id"`
|
||||
AuthorName string `json:"author_name"`
|
||||
RedditPostID string `json:"reddit_post_id"`
|
||||
PostTitle string `json:"post_title"`
|
||||
PostBody string `json:"post_body"`
|
||||
PostAuthorID string `json:"post_author_id"`
|
||||
PostAuthorName string `json:"post_author_name"`
|
||||
PostPermalink string `json:"post_permalink"`
|
||||
Subreddit string `json:"subreddit"`
|
||||
Permalink string `json:"permalink"`
|
||||
ScreenshotBase64 string `json:"screenshot_base64"`
|
||||
}
|
||||
|
||||
func (s *Server) handleSaveComment(w http.ResponseWriter, r *http.Request) {
|
||||
var req saveCommentRequest
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 20<<20)).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
req.RedditCommentID = strings.TrimSpace(req.RedditCommentID)
|
||||
req.RedditPostID = strings.TrimSpace(req.RedditPostID)
|
||||
if req.RedditCommentID == "" || req.RedditPostID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "reddit_comment_id and reddit_post_id required"})
|
||||
return
|
||||
}
|
||||
|
||||
blocked, err := s.store.IsUsernameBlocked(r.Context(), req.AuthorName)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if blocked {
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{
|
||||
"saved": false,
|
||||
"blocked": true,
|
||||
"error": "author is on the blocklist",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := s.store.CommentExists(r.Context(), req.RedditCommentID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"saved": false, "exists": true})
|
||||
return
|
||||
}
|
||||
|
||||
screenshotPath := ""
|
||||
if req.ScreenshotBase64 != "" {
|
||||
path, err := s.saveScreenshot(req.RedditCommentID, req.ScreenshotBase64)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
screenshotPath = path
|
||||
}
|
||||
|
||||
id, err := s.store.SaveComment(r.Context(), db.SaveCommentInput{
|
||||
RedditCommentID: req.RedditCommentID,
|
||||
Body: req.Body,
|
||||
AuthorID: req.AuthorID,
|
||||
AuthorName: req.AuthorName,
|
||||
RedditPostID: req.RedditPostID,
|
||||
PostTitle: req.PostTitle,
|
||||
PostBody: req.PostBody,
|
||||
PostAuthorID: req.PostAuthorID,
|
||||
PostAuthorName: req.PostAuthorName,
|
||||
PostPermalink: req.PostPermalink,
|
||||
Subreddit: req.Subreddit,
|
||||
Permalink: req.Permalink,
|
||||
ScreenshotPath: screenshotPath,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"saved": true, "id": id, "exists": false})
|
||||
}
|
||||
|
||||
type savePostRequest struct {
|
||||
RedditPostID string `json:"reddit_post_id"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
AuthorID string `json:"author_id"`
|
||||
AuthorName string `json:"author_name"`
|
||||
Permalink string `json:"permalink"`
|
||||
Subreddit string `json:"subreddit"`
|
||||
}
|
||||
|
||||
func (s *Server) handleSavePost(w http.ResponseWriter, r *http.Request) {
|
||||
var req savePostRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
req.RedditPostID = strings.TrimSpace(req.RedditPostID)
|
||||
if req.RedditPostID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "reddit_post_id required"})
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := s.store.PostExists(r.Context(), req.RedditPostID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
id, err := s.store.SavePost(r.Context(), db.SavePostInput{
|
||||
RedditPostID: req.RedditPostID,
|
||||
Title: req.Title,
|
||||
Body: req.Body,
|
||||
AuthorID: req.AuthorID,
|
||||
AuthorName: req.AuthorName,
|
||||
Permalink: req.Permalink,
|
||||
Subreddit: req.Subreddit,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
status := http.StatusCreated
|
||||
if exists {
|
||||
status = http.StatusOK
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"saved": true, "id": id, "exists": exists})
|
||||
}
|
||||
|
||||
func (s *Server) handleListBlocklist(w http.ResponseWriter, r *http.Request) {
|
||||
names, err := s.store.ListBlockedUsernames(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"usernames": names})
|
||||
}
|
||||
|
||||
func (s *Server) handleAddBlocked(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
name, err := s.store.AddBlockedUsername(r.Context(), req.Username)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
names, err := s.store.ListBlockedUsernames(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"added": name, "usernames": names})
|
||||
}
|
||||
|
||||
func (s *Server) handleRemoveBlocked(w http.ResponseWriter, r *http.Request) {
|
||||
username := chi.URLParam(r, "username")
|
||||
if err := s.store.RemoveBlockedUsername(r.Context(), username); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
names, err := s.store.ListBlockedUsernames(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"usernames": names})
|
||||
}
|
||||
|
||||
func (s *Server) handleReplaceBlocklist(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Usernames []string `json:"usernames"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
names, err := s.store.ReplaceBlockedUsernames(r.Context(), req.Usernames)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"usernames": names})
|
||||
}
|
||||
|
||||
func (s *Server) handleSearchJSON(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query().Get("q")
|
||||
user := r.URL.Query().Get("user")
|
||||
results, err := s.store.SearchComments(r.Context(), q, user, 100, 0)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"results": results})
|
||||
}
|
||||
|
||||
func (s *Server) handleImgurExport(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
url, err := s.exportToImgur(r, id)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"imgur_url": url})
|
||||
}
|
||||
|
||||
func (s *Server) exportToImgur(r *http.Request, redditCommentID string) (string, error) {
|
||||
comment, err := s.store.GetCommentByRedditID(r.Context(), redditCommentID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if comment == nil {
|
||||
return "", fmt.Errorf("comment not found")
|
||||
}
|
||||
if comment.ImgurURL != "" {
|
||||
return comment.ImgurURL, nil
|
||||
}
|
||||
if comment.ScreenshotPath == "" {
|
||||
return "", fmt.Errorf("no screenshot for this comment")
|
||||
}
|
||||
absPath := comment.ScreenshotPath
|
||||
if !filepath.IsAbs(absPath) {
|
||||
absPath = filepath.Join(s.cfg.DataDir, absPath)
|
||||
}
|
||||
link, err := s.imgur.UploadFile(absPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := s.store.SetImgurURL(r.Context(), redditCommentID, link); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return link, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleScreenshot(w http.ResponseWriter, r *http.Request) {
|
||||
file := filepath.Base(chi.URLParam(r, "file"))
|
||||
if file == "." || file == "/" || strings.Contains(file, "..") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
path := filepath.Join(s.cfg.ScreenshotDir, file)
|
||||
http.ServeFile(w, r, path)
|
||||
}
|
||||
|
||||
func (s *Server) saveScreenshot(redditCommentID, dataURL string) (string, error) {
|
||||
payload := dataURL
|
||||
if idx := strings.Index(dataURL, ","); idx >= 0 {
|
||||
payload = dataURL[idx+1:]
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid screenshot base64: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(s.cfg.ScreenshotDir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
filename := sanitizeID(redditCommentID) + ".png"
|
||||
absPath := filepath.Join(s.cfg.ScreenshotDir, filename)
|
||||
if err := os.WriteFile(absPath, raw, 0o644); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Store path relative to data dir for portability.
|
||||
rel := filepath.Join("screenshots", filename)
|
||||
return rel, nil
|
||||
}
|
||||
|
||||
func sanitizeID(id string) string {
|
||||
replacer := strings.NewReplacer("/", "_", "\\", "_", "..", "_", ":", "_")
|
||||
return replacer.Replace(id)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Config holds runtime settings for the RCS backend.
|
||||
type Config struct {
|
||||
Addr string
|
||||
DataDir string
|
||||
DBPath string
|
||||
ScreenshotDir string
|
||||
APIKey string
|
||||
ImgurClientID string
|
||||
// PublicBaseURL is the canonical public origin (e.g. https://rcs.example.com).
|
||||
PublicBaseURL string
|
||||
// TrustProxy honors X-Forwarded-Proto / X-Forwarded-Host when behind a reverse proxy.
|
||||
TrustProxy bool
|
||||
}
|
||||
|
||||
// Load reads configuration from environment variables with sensible defaults.
|
||||
func Load() Config {
|
||||
dataDir := envOr("RCS_DATA_DIR", "data")
|
||||
dbPath := envOr("RCS_DB_PATH", filepath.Join(dataDir, "rcs.db"))
|
||||
screenshotDir := filepath.Join(dataDir, "screenshots")
|
||||
|
||||
return Config{
|
||||
Addr: envOr("RCS_ADDR", "127.0.0.1:8080"),
|
||||
DataDir: dataDir,
|
||||
DBPath: dbPath,
|
||||
ScreenshotDir: screenshotDir,
|
||||
APIKey: os.Getenv("RCS_API_KEY"),
|
||||
ImgurClientID: os.Getenv("IMGUR_CLIENT_ID"),
|
||||
PublicBaseURL: strings.TrimRight(os.Getenv("RCS_PUBLIC_BASE_URL"), "/"),
|
||||
TrustProxy: envTruthy("RCS_TRUST_PROXY"),
|
||||
}
|
||||
}
|
||||
|
||||
func envOr(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envTruthy(key string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// Store wraps the SQLite connection and domain queries.
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// User is a Reddit account reference.
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
RedditUserID string `json:"reddit_user_id"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// Post is a Reddit submission ("top post").
|
||||
type Post struct {
|
||||
ID int64 `json:"id"`
|
||||
RedditPostID string `json:"reddit_post_id"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
AuthorID int64 `json:"author_id"`
|
||||
AuthorName string `json:"author_name"`
|
||||
Permalink string `json:"permalink"`
|
||||
Subreddit string `json:"subreddit"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Comment is a saved Reddit comment with optional screenshot/Imgur URL.
|
||||
type Comment struct {
|
||||
ID int64 `json:"id"`
|
||||
RedditCommentID string `json:"reddit_comment_id"`
|
||||
Body string `json:"body"`
|
||||
AuthorID int64 `json:"author_id"`
|
||||
AuthorName string `json:"author_name"`
|
||||
PostID int64 `json:"post_id"`
|
||||
RedditPostID string `json:"reddit_post_id"`
|
||||
Permalink string `json:"permalink"`
|
||||
ScreenshotPath string `json:"screenshot_path"`
|
||||
ImgurURL string `json:"imgur_url"`
|
||||
CapturedAt time.Time `json:"captured_at"`
|
||||
PostTitle string `json:"post_title"`
|
||||
}
|
||||
|
||||
// SearchResult is a comment row returned by search.
|
||||
type SearchResult struct {
|
||||
Comment
|
||||
}
|
||||
|
||||
// Open opens (or creates) the SQLite database and runs migrations.
|
||||
func Open(path string) (*Store, error) {
|
||||
database, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open sqlite: %w", err)
|
||||
}
|
||||
database.SetMaxOpenConns(1)
|
||||
|
||||
store := &Store{db: database}
|
||||
if err := store.migrate(); err != nil {
|
||||
_ = database.Close()
|
||||
return nil, err
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// Close closes the database.
|
||||
func (s *Store) Close() error {
|
||||
return s.db.Close()
|
||||
}
|
||||
|
||||
func (s *Store) migrate() error {
|
||||
const schema = `
|
||||
PRAGMA foreign_keys = ON;
|
||||
PRAGMA journal_mode = WAL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
reddit_user_id TEXT NOT NULL UNIQUE,
|
||||
username TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS posts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
reddit_post_id TEXT NOT NULL UNIQUE,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
body TEXT NOT NULL DEFAULT '',
|
||||
author_id INTEGER NOT NULL REFERENCES users(id),
|
||||
permalink TEXT NOT NULL DEFAULT '',
|
||||
subreddit TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS comments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
reddit_comment_id TEXT NOT NULL UNIQUE,
|
||||
body TEXT NOT NULL DEFAULT '',
|
||||
author_id INTEGER NOT NULL REFERENCES users(id),
|
||||
post_id INTEGER NOT NULL REFERENCES posts(id),
|
||||
permalink TEXT NOT NULL DEFAULT '',
|
||||
screenshot_path TEXT NOT NULL DEFAULT '',
|
||||
imgur_url TEXT NOT NULL DEFAULT '',
|
||||
captured_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
|
||||
CREATE INDEX IF NOT EXISTS idx_comments_reddit_id ON comments(reddit_comment_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_posts_reddit_id ON posts(reddit_post_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS blocked_usernames (
|
||||
username TEXT PRIMARY KEY COLLATE NOCASE,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
`
|
||||
_, err := s.db.Exec(schema)
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
return s.seedBlocklistIfEmpty()
|
||||
}
|
||||
|
||||
func (s *Store) seedBlocklistIfEmpty() error {
|
||||
var count int
|
||||
if err := s.db.QueryRow(`SELECT COUNT(1) FROM blocked_usernames`).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := s.db.Exec(`INSERT INTO blocked_usernames (username) VALUES (?)`, NormalizeUsername("AutoModerator"))
|
||||
return err
|
||||
}
|
||||
|
||||
// NormalizeUsername trims, strips u/, and lower-cases a Reddit username.
|
||||
func NormalizeUsername(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
name = strings.TrimPrefix(name, "u/")
|
||||
name = strings.TrimPrefix(name, "U/")
|
||||
name = strings.TrimPrefix(name, "/u/")
|
||||
return strings.ToLower(strings.TrimSpace(name))
|
||||
}
|
||||
|
||||
// ListBlockedUsernames returns all blocked usernames (normalized).
|
||||
func (s *Store) ListBlockedUsernames(ctx context.Context) ([]string, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT username FROM blocked_usernames ORDER BY username COLLATE NOCASE`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, name)
|
||||
}
|
||||
if out == nil {
|
||||
out = []string{}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// IsUsernameBlocked reports whether the author is on the blocklist.
|
||||
func (s *Store) IsUsernameBlocked(ctx context.Context, username string) (bool, error) {
|
||||
normalized := NormalizeUsername(username)
|
||||
if normalized == "" {
|
||||
return false, nil
|
||||
}
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(1) FROM blocked_usernames WHERE username = ?`, normalized).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// AddBlockedUsername inserts one username (idempotent).
|
||||
func (s *Store) AddBlockedUsername(ctx context.Context, username string) (string, error) {
|
||||
normalized := NormalizeUsername(username)
|
||||
if normalized == "" {
|
||||
return "", fmt.Errorf("username required")
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO blocked_usernames (username) VALUES (?)
|
||||
ON CONFLICT(username) DO NOTHING
|
||||
`, normalized)
|
||||
return normalized, err
|
||||
}
|
||||
|
||||
// RemoveBlockedUsername deletes one username.
|
||||
func (s *Store) RemoveBlockedUsername(ctx context.Context, username string) error {
|
||||
normalized := NormalizeUsername(username)
|
||||
if normalized == "" {
|
||||
return fmt.Errorf("username required")
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM blocked_usernames WHERE username = ?`, normalized)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReplaceBlockedUsernames replaces the entire blocklist.
|
||||
func (s *Store) ReplaceBlockedUsernames(ctx context.Context, usernames []string) ([]string, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM blocked_usernames`); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
seen := map[string]struct{}{}
|
||||
var normalized []string
|
||||
for _, name := range usernames {
|
||||
n := NormalizeUsername(name)
|
||||
if n == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[n]; ok {
|
||||
continue
|
||||
}
|
||||
seen[n] = struct{}{}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO blocked_usernames (username) VALUES (?)`, n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalized = append(normalized, n)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if normalized == nil {
|
||||
normalized = []string{}
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
// CommentExists reports whether a comment with the given Reddit id is stored.
|
||||
func (s *Store) CommentExists(ctx context.Context, redditCommentID string) (bool, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(1) FROM comments WHERE reddit_comment_id = ?`, redditCommentID).Scan(&count)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// CommentCaptureStatus reports existence and whether a screenshot is already stored.
|
||||
type CommentCaptureStatus struct {
|
||||
Exists bool `json:"exists"`
|
||||
HasScreenshot bool `json:"has_screenshot"`
|
||||
ScreenshotPath string `json:"screenshot_path,omitempty"`
|
||||
}
|
||||
|
||||
// GetCommentCaptureStatus loads capture status for a Reddit comment id.
|
||||
func (s *Store) GetCommentCaptureStatus(ctx context.Context, redditCommentID string) (CommentCaptureStatus, error) {
|
||||
var path string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT screenshot_path FROM comments WHERE reddit_comment_id = ?`, redditCommentID).Scan(&path)
|
||||
if err == sql.ErrNoRows {
|
||||
return CommentCaptureStatus{Exists: false, HasScreenshot: false}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return CommentCaptureStatus{}, err
|
||||
}
|
||||
return CommentCaptureStatus{
|
||||
Exists: true,
|
||||
HasScreenshot: strings.TrimSpace(path) != "",
|
||||
ScreenshotPath: path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetCommentScreenshot sets screenshot_path only when currently empty.
|
||||
func (s *Store) SetCommentScreenshot(ctx context.Context, redditCommentID, screenshotPath string) (bool, error) {
|
||||
result, err := s.db.ExecContext(ctx, `
|
||||
UPDATE comments
|
||||
SET screenshot_path = ?
|
||||
WHERE reddit_comment_id = ?
|
||||
AND (screenshot_path IS NULL OR screenshot_path = '')
|
||||
`, screenshotPath, redditCommentID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := result.RowsAffected()
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// PostExists reports whether a post with the given Reddit id is stored.
|
||||
func (s *Store) PostExists(ctx context.Context, redditPostID string) (bool, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(1) FROM posts WHERE reddit_post_id = ?`, redditPostID).Scan(&count)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// UpsertUser inserts or updates a user by Reddit user id.
|
||||
func (s *Store) UpsertUser(ctx context.Context, redditUserID, username string) (int64, error) {
|
||||
if redditUserID == "" {
|
||||
redditUserID = "unknown:" + username
|
||||
}
|
||||
if username == "" {
|
||||
username = "[deleted]"
|
||||
}
|
||||
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO users (reddit_user_id, username) VALUES (?, ?)
|
||||
ON CONFLICT(reddit_user_id) DO UPDATE SET username = excluded.username
|
||||
`, redditUserID, username)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var id int64
|
||||
err = s.db.QueryRowContext(ctx, `SELECT id FROM users WHERE reddit_user_id = ?`, redditUserID).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
// SavePostInput is the payload for saving a submission.
|
||||
type SavePostInput struct {
|
||||
RedditPostID string
|
||||
Title string
|
||||
Body string
|
||||
AuthorID string
|
||||
AuthorName string
|
||||
Permalink string
|
||||
Subreddit string
|
||||
}
|
||||
|
||||
// SavePost upserts a post and its author.
|
||||
func (s *Store) SavePost(ctx context.Context, input SavePostInput) (int64, error) {
|
||||
authorID, err := s.UpsertUser(ctx, input.AuthorID, input.AuthorName)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
INSERT INTO posts (reddit_post_id, title, body, author_id, permalink, subreddit, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT(reddit_post_id) DO UPDATE SET
|
||||
title = excluded.title,
|
||||
body = excluded.body,
|
||||
author_id = excluded.author_id,
|
||||
permalink = excluded.permalink,
|
||||
subreddit = excluded.subreddit
|
||||
`, input.RedditPostID, input.Title, input.Body, authorID, input.Permalink, input.Subreddit)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var id int64
|
||||
err = s.db.QueryRowContext(ctx, `SELECT id FROM posts WHERE reddit_post_id = ?`, input.RedditPostID).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
// SaveCommentInput is the payload for saving a comment.
|
||||
type SaveCommentInput struct {
|
||||
RedditCommentID string
|
||||
Body string
|
||||
AuthorID string
|
||||
AuthorName string
|
||||
RedditPostID string
|
||||
PostTitle string
|
||||
PostBody string
|
||||
PostAuthorID string
|
||||
PostAuthorName string
|
||||
PostPermalink string
|
||||
Subreddit string
|
||||
Permalink string
|
||||
ScreenshotPath string
|
||||
}
|
||||
|
||||
// SaveComment ensures the parent post exists, then inserts the comment (no overwrite of existing).
|
||||
func (s *Store) SaveComment(ctx context.Context, input SaveCommentInput) (int64, error) {
|
||||
exists, err := s.CommentExists(ctx, input.RedditCommentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if exists {
|
||||
var id int64
|
||||
err = s.db.QueryRowContext(ctx, `SELECT id FROM comments WHERE reddit_comment_id = ?`, input.RedditCommentID).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
postID, err := s.SavePost(ctx, SavePostInput{
|
||||
RedditPostID: input.RedditPostID,
|
||||
Title: input.PostTitle,
|
||||
Body: input.PostBody,
|
||||
AuthorID: input.PostAuthorID,
|
||||
AuthorName: input.PostAuthorName,
|
||||
Permalink: input.PostPermalink,
|
||||
Subreddit: input.Subreddit,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
authorID, err := s.UpsertUser(ctx, input.AuthorID, input.AuthorName)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
result, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO comments (reddit_comment_id, body, author_id, post_id, permalink, screenshot_path, captured_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
`, input.RedditCommentID, input.Body, authorID, postID, input.Permalink, input.ScreenshotPath)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.LastInsertId()
|
||||
}
|
||||
|
||||
// GetCommentByRedditID loads a comment by Reddit id.
|
||||
func (s *Store) GetCommentByRedditID(ctx context.Context, redditCommentID string) (*Comment, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT c.id, c.reddit_comment_id, c.body, c.author_id, u.username, c.post_id, p.reddit_post_id,
|
||||
c.permalink, c.screenshot_path, c.imgur_url, c.captured_at, p.title
|
||||
FROM comments c
|
||||
JOIN users u ON u.id = c.author_id
|
||||
JOIN posts p ON p.id = c.post_id
|
||||
WHERE c.reddit_comment_id = ?
|
||||
`, redditCommentID)
|
||||
|
||||
var comment Comment
|
||||
var capturedAt string
|
||||
err := row.Scan(
|
||||
&comment.ID, &comment.RedditCommentID, &comment.Body, &comment.AuthorID, &comment.AuthorName,
|
||||
&comment.PostID, &comment.RedditPostID, &comment.Permalink, &comment.ScreenshotPath,
|
||||
&comment.ImgurURL, &capturedAt, &comment.PostTitle,
|
||||
)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
comment.CapturedAt = parseTime(capturedAt)
|
||||
return &comment, nil
|
||||
}
|
||||
|
||||
// SetImgurURL stores the Imgur link for a comment.
|
||||
func (s *Store) SetImgurURL(ctx context.Context, redditCommentID, imgurURL string) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE comments SET imgur_url = ? WHERE reddit_comment_id = ?`, imgurURL, redditCommentID)
|
||||
return err
|
||||
}
|
||||
|
||||
func commentSearchFilter(query, username string) (where string, args []any) {
|
||||
var clauses []string
|
||||
if username != "" {
|
||||
clauses = append(clauses, `u.username LIKE ?`)
|
||||
args = append(args, username+"%")
|
||||
}
|
||||
if query != "" {
|
||||
pattern := normalizeGlob(query)
|
||||
clauses = append(clauses, `(c.body GLOB ? OR p.title GLOB ?)`)
|
||||
args = append(args, pattern, pattern)
|
||||
}
|
||||
if len(clauses) > 0 {
|
||||
where = "WHERE " + strings.Join(clauses, " AND ")
|
||||
}
|
||||
return where, args
|
||||
}
|
||||
|
||||
// CountComments returns how many comments match the optional username / GLOB filters.
|
||||
func (s *Store) CountComments(ctx context.Context, query, username string) (int, error) {
|
||||
where, args := commentSearchFilter(query, username)
|
||||
sqlQuery := fmt.Sprintf(`
|
||||
SELECT COUNT(1)
|
||||
FROM comments c
|
||||
JOIN users u ON u.id = c.author_id
|
||||
JOIN posts p ON p.id = c.post_id
|
||||
%s
|
||||
`, where)
|
||||
var total int
|
||||
err := s.db.QueryRowContext(ctx, sqlQuery, args...).Scan(&total)
|
||||
return total, err
|
||||
}
|
||||
|
||||
// SearchComments finds comments by optional username and GLOB text pattern (newest first).
|
||||
func (s *Store) SearchComments(ctx context.Context, query, username string, limit, offset int) ([]SearchResult, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 100
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
|
||||
where, args := commentSearchFilter(query, username)
|
||||
sqlQuery := fmt.Sprintf(`
|
||||
SELECT c.id, c.reddit_comment_id, c.body, c.author_id, u.username, c.post_id, p.reddit_post_id,
|
||||
c.permalink, c.screenshot_path, c.imgur_url, c.captured_at, p.title
|
||||
FROM comments c
|
||||
JOIN users u ON u.id = c.author_id
|
||||
JOIN posts p ON p.id = c.post_id
|
||||
%s
|
||||
ORDER BY c.captured_at DESC, c.id DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, where)
|
||||
args = append(args, limit, offset)
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, sqlQuery, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var results []SearchResult
|
||||
for rows.Next() {
|
||||
var item SearchResult
|
||||
var capturedAt string
|
||||
if err := rows.Scan(
|
||||
&item.ID, &item.RedditCommentID, &item.Body, &item.AuthorID, &item.AuthorName,
|
||||
&item.PostID, &item.RedditPostID, &item.Permalink, &item.ScreenshotPath,
|
||||
&item.ImgurURL, &capturedAt, &item.PostTitle,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.CapturedAt = parseTime(capturedAt)
|
||||
results = append(results, item)
|
||||
}
|
||||
return results, rows.Err()
|
||||
}
|
||||
|
||||
func normalizeGlob(query string) string {
|
||||
query = strings.TrimSpace(query)
|
||||
if query == "" {
|
||||
return "*"
|
||||
}
|
||||
// If the user did not include wildcards, wrap for substring match.
|
||||
if !strings.ContainsAny(query, "*?") {
|
||||
return "*" + query + "*"
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func parseTime(value string) time.Time {
|
||||
layouts := []string{
|
||||
time.RFC3339,
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02T15:04:05Z",
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if parsed, err := time.Parse(layout, value); err == nil {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package imgur
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
const uploadURL = "https://api.imgur.com/3/image"
|
||||
|
||||
// Client uploads images to Imgur anonymously with a Client-ID.
|
||||
type Client struct {
|
||||
clientID string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
// New creates an Imgur client. clientID may be empty (uploads will fail clearly).
|
||||
func New(clientID string) *Client {
|
||||
return &Client{
|
||||
clientID: clientID,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 60 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Enabled reports whether a Client-ID is configured.
|
||||
func (c *Client) Enabled() bool {
|
||||
return c != nil && c.clientID != ""
|
||||
}
|
||||
|
||||
type uploadResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
Link string `json:"link"`
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
// UploadFile uploads a local image file and returns the public Imgur URL.
|
||||
func (c *Client) UploadFile(path string) (string, error) {
|
||||
if !c.Enabled() {
|
||||
return "", fmt.Errorf("imgur is not configured (set IMGUR_CLIENT_ID)")
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open screenshot: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
part, err := writer.CreateFormFile("image", "screenshot.png")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := io.Copy(part, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
_ = writer.WriteField("type", "file")
|
||||
if err := writer.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, uploadURL, &body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Client-ID "+c.clientID)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("imgur request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var parsed uploadResponse
|
||||
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||
return "", fmt.Errorf("decode imgur response: %w (body=%s)", err, truncate(string(raw), 200))
|
||||
}
|
||||
if !parsed.Success || parsed.Data.Link == "" {
|
||||
return "", fmt.Errorf("imgur upload failed (status=%d): %s", resp.StatusCode, truncate(string(raw), 300))
|
||||
}
|
||||
return parsed.Data.Link, nil
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "..."
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
document.querySelectorAll(".copy-url").forEach((button) => {
|
||||
button.addEventListener("click", async () => {
|
||||
const url = button.getAttribute("data-url");
|
||||
if (!url) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
const hint = button.parentElement.querySelector(".copied-hint");
|
||||
if (hint) {
|
||||
hint.hidden = false;
|
||||
setTimeout(() => {
|
||||
hint.hidden = true;
|
||||
}, 1500);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("copy failed", err);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
(function setupLightbox() {
|
||||
const lightbox = document.getElementById("lightbox");
|
||||
const lightboxImg = document.getElementById("lightbox-img");
|
||||
if (!lightbox || !lightboxImg) {
|
||||
console.warn("[RCS] lightbox elements missing");
|
||||
return;
|
||||
}
|
||||
|
||||
function openLightbox(src) {
|
||||
lightboxImg.src = src;
|
||||
lightbox.hidden = false;
|
||||
lightbox.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("lightbox-open");
|
||||
}
|
||||
|
||||
function closeLightbox() {
|
||||
lightbox.hidden = true;
|
||||
lightbox.setAttribute("aria-hidden", "true");
|
||||
lightboxImg.removeAttribute("src");
|
||||
document.body.classList.remove("lightbox-open");
|
||||
}
|
||||
|
||||
// Event delegation so thumbs work even if markup is re-rendered later.
|
||||
document.addEventListener("click", (event) => {
|
||||
const thumb = event.target.closest(".shot-thumb");
|
||||
if (thumb) {
|
||||
event.preventDefault();
|
||||
const src = thumb.getAttribute("data-full") || (thumb.querySelector("img") && thumb.querySelector("img").src);
|
||||
if (src) openLightbox(src);
|
||||
return;
|
||||
}
|
||||
if (event.target === lightbox || event.target.classList.contains("lightbox-close")) {
|
||||
closeLightbox();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape" && !lightbox.hidden) {
|
||||
closeLightbox();
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,263 @@
|
||||
:root {
|
||||
--bg: #0f1419;
|
||||
--panel: #1a222c;
|
||||
--text: #e7ecf1;
|
||||
--muted: #8b98a5;
|
||||
--accent: #ff4500;
|
||||
--accent-2: #4a9eff;
|
||||
--ok: #1f6f4a;
|
||||
--warn: #7a5b12;
|
||||
--error: #8b2e2e;
|
||||
--border: #2c3640;
|
||||
--font: "IBM Plex Sans", "Segoe UI", sans-serif;
|
||||
--mono: "IBM Plex Mono", ui-monospace, monospace;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: var(--font);
|
||||
background:
|
||||
radial-gradient(1200px 600px at 10% -10%, #243041 0%, transparent 60%),
|
||||
radial-gradient(900px 500px at 100% 0%, #2a1c14 0%, transparent 55%),
|
||||
var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.site-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1.5rem;
|
||||
align-items: end;
|
||||
justify-content: space-between;
|
||||
padding: 1.5rem clamp(1rem, 3vw, 2.5rem);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--panel) 85%, transparent);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.brand h1 {
|
||||
margin: 0;
|
||||
font-size: 2rem;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.brand p {
|
||||
margin: 0.15rem 0 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.search {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
.search label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.search input {
|
||||
min-width: 12rem;
|
||||
padding: 0.55rem 0.7rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button, .btn {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
padding: 0.55rem 0.9rem;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.btn.secondary {
|
||||
background: var(--accent-2);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.banner {
|
||||
margin: 1rem clamp(1rem, 3vw, 2.5rem);
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.banner.error { background: var(--error); }
|
||||
.banner.warn { background: var(--warn); }
|
||||
.banner.ok { background: var(--ok); }
|
||||
|
||||
main {
|
||||
padding: 1rem clamp(1rem, 3vw, 2.5rem) 3rem;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.results {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.result {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem 0.6rem;
|
||||
align-items: baseline;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.muted { color: var(--muted); }
|
||||
.permalink { color: var(--accent-2); }
|
||||
|
||||
.body {
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.45;
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.shot {
|
||||
margin: 0.5rem 0 0.25rem;
|
||||
}
|
||||
|
||||
.shot-thumb {
|
||||
appearance: none;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 0;
|
||||
background: #000;
|
||||
cursor: zoom-in;
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
max-width: min(100%, 420px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.shot-thumb img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.shot-hint {
|
||||
font-size: 0.75rem;
|
||||
color: var(--muted);
|
||||
background: color-mix(in srgb, var(--panel) 90%, #000);
|
||||
padding: 0.35rem 0.55rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.no-shot {
|
||||
margin: 0.35rem 0 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.lightbox {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.82);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.lightbox[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.lightbox img {
|
||||
max-width: min(96vw, 1100px);
|
||||
max-height: 90vh;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
|
||||
background: #111;
|
||||
}
|
||||
|
||||
.lightbox-close {
|
||||
position: absolute;
|
||||
top: 0.75rem;
|
||||
right: 1rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #fff;
|
||||
font-size: 2rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
body.lightbox-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
margin-top: 0.75rem;
|
||||
}
|
||||
|
||||
.pager {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem 1rem;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 1.25rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.pager-meta {
|
||||
color: var(--muted);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.pager-links {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.btn.secondary.disabled,
|
||||
span.btn.secondary.disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
code { font-family: var(--mono); }
|
||||
@@ -0,0 +1,104 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>RCS — Reddit Comment Saver</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="brand">
|
||||
<h1>RCS</h1>
|
||||
<p>Reddit Comment Saver</p>
|
||||
</div>
|
||||
<form class="search" method="get" action="/">
|
||||
<label>
|
||||
Username
|
||||
<input type="text" name="user" value="{{.User}}" placeholder="spez">
|
||||
</label>
|
||||
<label>
|
||||
Free text (GLOB)
|
||||
<input type="text" name="q" value="{{.Query}}" placeholder="*bla*bla*">
|
||||
</label>
|
||||
<button type="submit">Search</button>
|
||||
</form>
|
||||
</header>
|
||||
|
||||
{{if .Error}}
|
||||
<div class="banner error">{{.Error}}</div>
|
||||
{{end}}
|
||||
{{if .Flash}}
|
||||
<div class="banner ok">{{.Flash}}</div>
|
||||
{{end}}
|
||||
|
||||
{{if not .ImgurOn}}
|
||||
<div class="banner warn">Imgur export is disabled until <code>IMGUR_CLIENT_ID</code> is set on the server.</div>
|
||||
{{end}}
|
||||
|
||||
<main>
|
||||
{{if not .Results}}
|
||||
<p class="empty">No comments yet. Browse Reddit with the RCS extension connected to this backend.</p>
|
||||
{{else}}
|
||||
<ul class="results">
|
||||
{{range .Results}}
|
||||
<li class="result" data-comment-id="{{.RedditCommentID}}">
|
||||
<div class="meta">
|
||||
<strong>u/{{.AuthorName}}</strong>
|
||||
<span class="muted">on</span>
|
||||
<span>{{.PostTitle}}</span>
|
||||
<a class="permalink" href="{{.Permalink}}" target="_blank" rel="noopener">Reddit</a>
|
||||
</div>
|
||||
<p class="body">{{snippet .Body}}</p>
|
||||
{{if .ScreenshotPath}}
|
||||
<div class="shot">
|
||||
<button type="button" class="shot-thumb" data-full="{{screenshotURL .ScreenshotPath}}" aria-label="Preview screenshot">
|
||||
<img src="{{screenshotURL .ScreenshotPath}}" alt="Comment screenshot" loading="lazy">
|
||||
<span class="shot-hint">Click to enlarge</span>
|
||||
</button>
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="muted no-shot">No screenshot</p>
|
||||
{{end}}
|
||||
<div class="actions">
|
||||
{{if hasImgur .ImgurURL}}
|
||||
<a class="btn" href="{{.ImgurURL}}" target="_blank" rel="noopener">Open on Imgur</a>
|
||||
<button type="button" class="btn secondary copy-url" data-url="{{.ImgurURL}}">Copy URL</button>
|
||||
<span class="muted copied-hint" hidden>Copied</span>
|
||||
{{else}}
|
||||
<form method="post" action="/export/{{.RedditCommentID}}">
|
||||
<input type="hidden" name="q" value="{{$.Query}}">
|
||||
<input type="hidden" name="user" value="{{$.User}}">
|
||||
<input type="hidden" name="page" value="{{$.Page}}">
|
||||
<button type="submit" class="btn" {{if not $.ImgurOn}}disabled{{end}}>Export to Imgur</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</div>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
<nav class="pager" aria-label="Pagination">
|
||||
<span class="pager-meta">Page {{.Page}} of {{.TotalPages}} ({{.Total}} total)</span>
|
||||
<div class="pager-links">
|
||||
{{if .HasPrev}}
|
||||
<a class="btn secondary" href="{{pageURL . .PrevPage}}">Newer</a>
|
||||
{{else}}
|
||||
<span class="btn secondary disabled">Newer</span>
|
||||
{{end}}
|
||||
{{if .HasNext}}
|
||||
<a class="btn secondary" href="{{pageURL . .NextPage}}">Older</a>
|
||||
{{else}}
|
||||
<span class="btn secondary disabled">Older</span>
|
||||
{{end}}
|
||||
</div>
|
||||
</nav>
|
||||
{{end}}
|
||||
</main>
|
||||
|
||||
<div id="lightbox" class="lightbox" hidden>
|
||||
<button type="button" class="lightbox-close" aria-label="Close preview">×</button>
|
||||
<img id="lightbox-img" alt="Screenshot preview">
|
||||
</div>
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,233 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/squid/rcs/backend/internal/config"
|
||||
"github.com/squid/rcs/backend/internal/db"
|
||||
"github.com/squid/rcs/backend/internal/imgur"
|
||||
)
|
||||
|
||||
const pageSize = 50
|
||||
|
||||
//go:embed templates/* static/*
|
||||
var assets embed.FS
|
||||
|
||||
// UI serves the search Web UI.
|
||||
type UI struct {
|
||||
cfg config.Config
|
||||
store *db.Store
|
||||
imgur *imgur.Client
|
||||
tmpl *template.Template
|
||||
}
|
||||
|
||||
// New creates the Web UI.
|
||||
func New(cfg config.Config, store *db.Store, imgurClient *imgur.Client) (*UI, error) {
|
||||
tmpl, err := template.New("").Funcs(template.FuncMap{
|
||||
"hasImgur": func(url string) bool { return strings.TrimSpace(url) != "" },
|
||||
"snippet": func(body string) string {
|
||||
body = strings.TrimSpace(body)
|
||||
if len(body) > 280 {
|
||||
return body[:280] + "…"
|
||||
}
|
||||
return body
|
||||
},
|
||||
"screenshotURL": func(path string) string {
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
return "/screenshots/" + filepath.Base(path)
|
||||
},
|
||||
"pageURL": func(data pageData, page int) string {
|
||||
values := url.Values{}
|
||||
if data.Query != "" {
|
||||
values.Set("q", data.Query)
|
||||
}
|
||||
if data.User != "" {
|
||||
values.Set("user", data.User)
|
||||
}
|
||||
if page > 1 {
|
||||
values.Set("page", strconv.Itoa(page))
|
||||
}
|
||||
encoded := values.Encode()
|
||||
if encoded == "" {
|
||||
return "/"
|
||||
}
|
||||
return "/?" + encoded
|
||||
},
|
||||
}).ParseFS(assets, "templates/*.html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse templates: %w", err)
|
||||
}
|
||||
return &UI{cfg: cfg, store: store, imgur: imgurClient, tmpl: tmpl}, nil
|
||||
}
|
||||
|
||||
// StaticHandler serves embedded CSS/JS.
|
||||
func (u *UI) StaticHandler() http.Handler {
|
||||
sub, err := fs.Sub(assets, "static")
|
||||
if err != nil {
|
||||
return http.NotFoundHandler()
|
||||
}
|
||||
return http.StripPrefix("/static/", http.FileServer(http.FS(sub)))
|
||||
}
|
||||
|
||||
type pageData struct {
|
||||
Query string
|
||||
User string
|
||||
Results []db.SearchResult
|
||||
Error string
|
||||
Flash string
|
||||
ImgurOn bool
|
||||
Page int
|
||||
TotalPages int
|
||||
Total int
|
||||
HasPrev bool
|
||||
HasNext bool
|
||||
PrevPage int
|
||||
NextPage int
|
||||
}
|
||||
|
||||
func parsePage(raw string) int {
|
||||
page, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil || page < 1 {
|
||||
return 1
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
// HandleIndex renders search results.
|
||||
func (u *UI) HandleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
user := strings.TrimSpace(r.URL.Query().Get("user"))
|
||||
flash := strings.TrimSpace(r.URL.Query().Get("flash"))
|
||||
errMsg := strings.TrimSpace(r.URL.Query().Get("error"))
|
||||
page := parsePage(r.URL.Query().Get("page"))
|
||||
|
||||
data := pageData{
|
||||
Query: q,
|
||||
User: user,
|
||||
Flash: flash,
|
||||
Error: errMsg,
|
||||
ImgurOn: u.imgur.Enabled(),
|
||||
Page: page,
|
||||
}
|
||||
|
||||
total, err := u.store.CountComments(r.Context(), q, user)
|
||||
if err != nil {
|
||||
data.Error = err.Error()
|
||||
} else {
|
||||
data.Total = total
|
||||
data.TotalPages = total / pageSize
|
||||
if total%pageSize != 0 {
|
||||
data.TotalPages++
|
||||
}
|
||||
if data.TotalPages == 0 {
|
||||
data.TotalPages = 1
|
||||
}
|
||||
if page > data.TotalPages {
|
||||
page = data.TotalPages
|
||||
data.Page = page
|
||||
}
|
||||
data.HasPrev = page > 1
|
||||
data.HasNext = page < data.TotalPages
|
||||
data.PrevPage = page - 1
|
||||
data.NextPage = page + 1
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
results, err := u.store.SearchComments(r.Context(), q, user, pageSize, offset)
|
||||
if err != nil {
|
||||
data.Error = err.Error()
|
||||
} else {
|
||||
data.Results = results
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := u.tmpl.ExecuteTemplate(w, "index.html", data); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleExport uploads a comment screenshot to Imgur (or returns existing URL).
|
||||
func (u *UI) HandleExport(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
q := strings.TrimSpace(r.FormValue("q"))
|
||||
if q == "" {
|
||||
q = strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
}
|
||||
user := strings.TrimSpace(r.FormValue("user"))
|
||||
if user == "" {
|
||||
user = strings.TrimSpace(r.URL.Query().Get("user"))
|
||||
}
|
||||
pageRaw := strings.TrimSpace(r.FormValue("page"))
|
||||
if pageRaw == "" {
|
||||
pageRaw = strings.TrimSpace(r.URL.Query().Get("page"))
|
||||
}
|
||||
page := parsePage(pageRaw)
|
||||
|
||||
redirect := func(flash, errMsg string) {
|
||||
values := url.Values{}
|
||||
if q != "" {
|
||||
values.Set("q", q)
|
||||
}
|
||||
if user != "" {
|
||||
values.Set("user", user)
|
||||
}
|
||||
if page > 1 {
|
||||
values.Set("page", strconv.Itoa(page))
|
||||
}
|
||||
if flash != "" {
|
||||
values.Set("flash", flash)
|
||||
}
|
||||
if errMsg != "" {
|
||||
values.Set("error", errMsg)
|
||||
}
|
||||
target := "/"
|
||||
if encoded := values.Encode(); encoded != "" {
|
||||
target += "?" + encoded
|
||||
}
|
||||
http.Redirect(w, r, target, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
comment, err := u.store.GetCommentByRedditID(r.Context(), id)
|
||||
if err != nil {
|
||||
redirect("", err.Error())
|
||||
return
|
||||
}
|
||||
if comment == nil {
|
||||
redirect("", "comment not found")
|
||||
return
|
||||
}
|
||||
if comment.ImgurURL != "" {
|
||||
redirect("Already exported", "")
|
||||
return
|
||||
}
|
||||
if comment.ScreenshotPath == "" {
|
||||
redirect("", "no screenshot for this comment")
|
||||
return
|
||||
}
|
||||
|
||||
absPath := comment.ScreenshotPath
|
||||
if !filepath.IsAbs(absPath) {
|
||||
absPath = filepath.Join(u.cfg.DataDir, absPath)
|
||||
}
|
||||
link, err := u.imgur.UploadFile(absPath)
|
||||
if err != nil {
|
||||
redirect("", err.Error())
|
||||
return
|
||||
}
|
||||
if err := u.store.SetImgurURL(r.Context(), id, link); err != nil {
|
||||
redirect("", err.Error())
|
||||
return
|
||||
}
|
||||
redirect("Exported to Imgur", "")
|
||||
}
|
||||
Reference in New Issue
Block a user