package subsonic import ( "context" "errors" "net/http" "github.com/jackc/pgx/v5" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" ) // StartScan starts a library scan in the background, the same scan as the // admin's Rescan in the web app. started is false when one is already // running. type StartScan func(ctx context.Context) (started bool, err error) // ScanStatus is the body of getScanStatus and startScan. Count is the songs // whose files are present; LastScan, from OpenSubsonic, is when the latest // scan finished. type ScanStatus struct { Scanning bool `json:"scanning" xml:"scanning,attr"` Count int64 `json:"count" xml:"count,attr"` LastScan string `json:"lastScan,omitempty" xml:"lastScan,attr,omitempty"` } type ScanStatusResponse struct { Envelope ScanStatus ScanStatus `json:"scanStatus" xml:"scanStatus"` } type scanHandlers struct { pool dbq.DBTX start StartScan } // status reads whether a scan is running from the latest scan run. func (s *scanHandlers) status(ctx context.Context) (ScanStatus, error) { q := dbq.New(s.pool) count, err := q.CountPlayableTracks(ctx) if err != nil { return ScanStatus{}, err } st := ScanStatus{Count: count} run, err := q.GetLatestScanRun(ctx) if errors.Is(err, pgx.ErrNoRows) { return st, nil } if err != nil { return ScanStatus{}, err } st.Scanning = !run.FinishedAt.Valid st.LastScan = timestamptzToRFC3339(run.FinishedAt) return st, nil } func (s *scanHandlers) getScanStatus(w http.ResponseWriter, r *http.Request) { st, err := s.status(r.Context()) if err != nil { WriteFail(w, r, ErrGeneric, "Failed to read the scan status") return } Write(w, r, ScanStatusResponse{Envelope: NewEnvelope("ok"), ScanStatus: st}) } // startScan starts a library scan; only an admin may. It answers scanning // at once: the scan records itself a moment after it starts, so the latest // scan run alone would still read as finished. func (s *scanHandlers) startScan(w http.ResponseWriter, r *http.Request) { user, ok := UserFromContext(r.Context()) if !ok { WriteFail(w, r, ErrNotAuthorized, "Not authenticated") return } if !user.IsAdmin { WriteFail(w, r, ErrNotAuthorized, "Only an admin can start a scan") return } if s.start == nil { WriteFail(w, r, ErrGeneric, "Scanning is not available on this server") return } if _, err := s.start(r.Context()); err != nil { WriteFail(w, r, ErrGeneric, "Failed to start a scan") return } st, err := s.status(r.Context()) if err != nil { WriteFail(w, r, ErrGeneric, "Failed to read the scan status") return } st.Scanning = true Write(w, r, ScanStatusResponse{Envelope: NewEnvelope("ok"), ScanStatus: st}) }