-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler_patch.go
98 lines (87 loc) · 2.39 KB
/
handler_patch.go
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
package app
import (
"errors"
"log/slog"
"net/http"
"strconv"
"strings"
"github.com/Dash-Industry-Forum/livesim2/pkg/patch"
)
type rec struct {
body []byte
status int
}
func (r *rec) Write(b []byte) (int, error) {
r.body = append(r.body, b...)
return len(b), nil
}
func (r *rec) WriteHeader(status int) {
r.status = status
}
func (r *rec) Header() http.Header {
return http.Header{}
}
// patchHandlerFunc returns an MPD patch
func (s *Server) patchHandlerFunc(w http.ResponseWriter, r *http.Request) {
origQuery := r.URL.RawQuery
q := r.URL.Query()
publishTime := q.Get("publishTime")
if publishTime == "" {
slog.Warn("publishTime query is required, but not provided in patch request")
http.Error(w, "publishTime query is required", http.StatusBadRequest)
}
old := &rec{}
oldQuery := removeQuery(origQuery, "nowMS")
oldQuery = removeQuery(oldQuery, "nowDate")
mpdPath := mpdPathFromPatchPath(r.URL.Path)
r.URL.Path = mpdPath
r.URL.RawQuery = oldQuery
s.livesimHandlerFunc(old, r)
new := &rec{}
newQuery := removeQuery(origQuery, "publishTime")
r.URL.RawQuery = newQuery
s.livesimHandlerFunc(new, r)
doc, expiration, err := patch.MPDDiff(old.body, new.body)
switch {
case errors.Is(err, patch.ErrPatchSamePublishTime):
http.Error(w, err.Error(), http.StatusTooEarly)
return
case errors.Is(err, patch.ErrPatchTooLate):
http.Error(w, err.Error(), http.StatusGone)
return
case err != nil:
slog.Error("MPDDiff", "err", err)
http.Error(w, "MPDDiff", http.StatusInternalServerError)
return
}
doc.Indent(2)
b, err := doc.WriteToBytes()
if err != nil {
slog.Error("WriteToBytes", "err", err)
http.Error(w, "WriteToBytes", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/dash-patch+xml")
w.Header().Set("Expires", expiration.Format(http.TimeFormat))
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
_, err = w.Write(b)
if err != nil {
slog.Error("Write", "err", err)
}
w.WriteHeader(http.StatusOK)
}
func mpdPathFromPatchPath(patchPath string) string {
mpdPath := strings.Replace(patchPath, ".mpp", ".mpd", 1)
//TODO. Handle a possible set prefix before patch
return strings.TrimPrefix(mpdPath, "/patch")
}
func removeQuery(query, key string) string {
q := strings.Split(query, "&")
for i, kv := range q {
if strings.HasPrefix(kv, key+"=") {
q = append(q[:i], q[i+1:]...)
break
}
}
return strings.Join(q, "&")
}