1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
package api
import (
"context"
"errors"
"net/http"
"codeberg.org/snonux/player/internal/service"
)
// ------------------------------------------------------------------
// File serving handlers
// ------------------------------------------------------------------
func (s *Server) fileHandler(fn func(context.Context, int64, int64) (*service.FileResult, error)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := pathID(r, "id")
if err != nil || id == 0 {
http.Error(w, "invalid media id", http.StatusBadRequest)
return
}
res, err := fn(r.Context(), id, userIDFromContext(r))
if err != nil {
if errors.Is(err, service.ErrNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
if errors.Is(err, service.ErrForbidden) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if res == nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
s.serveFileResult(w, r, res, false)
}
}
func (s *Server) handleStream(w http.ResponseWriter, r *http.Request) {
if !requireService(w, s.media.Browse) {
return
}
s.fileHandler(s.media.Browse.StreamMedia)(w, r)
}
func (s *Server) handleDownload(w http.ResponseWriter, r *http.Request) {
if !requireService(w, s.media.Browse) {
return
}
id, err := pathID(r, "id")
if err != nil || id == 0 {
badRequest(w, "invalid media id")
return
}
res, err := s.media.Browse.DownloadMedia(r.Context(), id, userIDFromContext(r))
if err != nil {
if errors.Is(err, service.ErrNotFound) {
notFound(w)
return
}
if errors.Is(err, service.ErrForbidden) {
forbidden(w, "forbidden")
return
}
handleError(w, err)
return
}
if res == nil {
notFound(w)
return
}
s.serveFileResult(w, r, res, true)
}
func (s *Server) handleThumbnail(w http.ResponseWriter, r *http.Request) {
if !requireService(w, s.media.Browse) {
return
}
w.Header().Set("Cache-Control", "no-cache")
s.fileHandler(s.media.Browse.GetThumbnail)(w, r)
}
func (s *Server) handleRegenThumbnail(w http.ResponseWriter, r *http.Request) {
if !requireService(w, s.media.Write) {
return
}
id, err := pathID(r, "id")
if err != nil || id == 0 {
badRequest(w, "invalid media id")
return
}
if err := s.media.Write.RegenerateThumbnail(r.Context(), id, userIDFromContext(r)); err != nil {
if errors.Is(err, service.ErrNotFound) {
notFound(w)
return
}
if errors.Is(err, service.ErrForbidden) {
forbidden(w, "forbidden")
return
}
handleError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
|