-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
269 lines (233 loc) · 5.89 KB
/
main.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// The player application loads audio blobs and integrates them into a media player
package main
import (
"bytes"
"context"
"embed"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
"perkeep.org/pkg/app"
"perkeep.org/pkg/auth"
"perkeep.org/pkg/buildinfo"
"perkeep.org/pkg/client"
"perkeep.org/pkg/search"
"perkeep.org/pkg/webserver"
)
var (
flagVersion = flag.Bool("version", false, "show version")
)
var (
logger = log.New(os.Stderr, "PLAYER: ", log.LstdFlags)
)
type config struct {
masterQueryURL string
}
func appConfig() (*config, error) {
configURL := os.Getenv("CAMLI_APP_CONFIG_URL")
if configURL == "" {
return nil, fmt.Errorf("Player application needs a CAMLI_APP_CONFIG_URL env var")
}
conf := &config{}
masterQueryURL := os.Getenv("CAMLI_APP_MASTERQUERY_URL")
if masterQueryURL == "" {
logger.Fatalf("Player application needs a CAMLI_APP_MASTERQUERY_URL env var")
}
conf.masterQueryURL = masterQueryURL
cl, err := app.Client()
if err != nil {
return nil, fmt.Errorf("could not get a client to fetch extra config: %v", err)
}
pause := time.Second
giveupTime := time.Now().Add(time.Hour)
for {
err := cl.GetJSON(context.TODO(), configURL, conf)
if err == nil {
break
}
if time.Now().After(giveupTime) {
logger.Fatalf("Giving up on starting: could not get app config at %v: %v", configURL, err)
}
logger.Printf("could not get app config at %v: %v. Will retry in a while.", configURL, err)
time.Sleep(pause)
pause *= 2
}
return conf, nil
}
type playerHandler struct {
masterQueryURL string
masterQueryMu sync.Mutex
masterQueryResults []audioData
client *client.Client
auth auth.AuthMode
}
type audioData struct {
BlobRef string
Artist string
Title string
Album string
Genre string
Track int64
}
var masterQuery = &search.SearchQuery{
Limit: -1,
Constraint: &search.Constraint{
File: &search.FileConstraint{
MIMEType: &search.StringConstraint{
HasPrefix: "audio/",
},
},
},
Describe: &search.DescribeRequest{},
}
func newPlayerHandler(conf *config) (*playerHandler, error) {
client, err := app.Client()
if err != nil {
return nil, fmt.Errorf("unable to create app client: %v", err)
}
auth, err := app.Auth()
if err != nil {
return nil, fmt.Errorf("unable to create app auth: %v", err)
}
ph := &playerHandler{
client: client,
auth: auth,
masterQueryURL: conf.masterQueryURL,
}
if err = ph.registerMasterQuery(); err != nil {
return nil, fmt.Errorf("unable to register master query: %v", err)
}
if err = ph.refreshMasterQueryResults(); err != nil {
return nil, fmt.Errorf("unable to fetch initial master query results: %v", err)
}
go ph.loopRefreshMasterQueryResults()
return ph, nil
}
func (h *playerHandler) registerMasterQuery() error {
h.masterQueryMu.Lock()
defer h.masterQueryMu.Unlock()
data, err := json.Marshal(masterQuery)
if err != nil {
return err
}
req, err := http.NewRequest("POST", h.masterQueryURL, bytes.NewReader(data))
if err != nil {
return err
}
h.auth.AddAuthHeader(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(body) != "OK" {
return fmt.Errorf("error setting master query on app handler: %v", string(body))
}
return nil
}
func (h *playerHandler) refreshMasterQueryResults() error {
h.masterQueryMu.Lock()
defer h.masterQueryMu.Unlock()
search, err := h.client.Query(context.Background(), masterQuery)
if err != nil {
return fmt.Errorf("unable to search audio files: %v", err)
}
audioFiles := make([]audioData, 0)
for _, blob := range search.Blobs {
blobMeta := search.Describe.Meta.Get(blob.Blob)
if !isValidAudioMeta(blobMeta) {
continue
}
// track can be used to sort an album
track, _ := strconv.ParseInt(blobMeta.MediaTags["track"], 10, 64)
audioFiles = append(audioFiles, audioData{
BlobRef: blob.Blob.String(),
Title: blobMeta.MediaTags["title"],
Album: blobMeta.MediaTags["album"],
Artist: blobMeta.MediaTags["artist"],
Genre: blobMeta.MediaTags["genre"],
Track: track,
})
}
h.masterQueryResults = audioFiles
return nil
}
func isValidAudioMeta(blobMeta *search.DescribedBlob) bool {
hasMediaTag := func(k string) bool {
_, ok := blobMeta.MediaTags[k]
return ok
}
return blobMeta.BlobRef.Valid() &&
hasMediaTag("title") &&
hasMediaTag("album") &&
hasMediaTag("artist")
}
func (h *playerHandler) loopRefreshMasterQueryResults() {
for range time.Tick(time.Minute) {
if err := h.refreshMasterQueryResults(); err != nil {
logger.Printf("unable to refresh master query results: %v", err)
continue
}
}
}
func (h *playerHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
h.masterQueryMu.Lock()
defer h.masterQueryMu.Unlock()
rw.Header().Add("Content-Type", "application/json")
json.NewEncoder(rw).Encode(h.masterQueryResults)
}
//go:embed player
var staticFiles embed.FS
func main() {
flag.Parse()
logger.Printf("player version %s; Go %s (%s/%s)",
buildinfo.Summary(),
runtime.Version(),
runtime.GOOS,
runtime.GOARCH,
)
if *flagVersion {
return
}
listenAddr, err := app.ListenAddress()
if err != nil {
logger.Fatalf("listen address: %v", err)
}
conf, err := appConfig()
if err != nil {
logger.Fatalf("no app config: %v", err)
}
ph, err := newPlayerHandler(conf)
if err != nil {
logger.Fatalf("unable to create player handler: %v", err)
}
fh := http.FileServer(http.FS(staticFiles))
// server
ws := webserver.New()
ws.Logger = logger
ws.Handle("/", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
switch strings.TrimPrefix(r.URL.Path, "/player") {
case "/api/meta":
ph.ServeHTTP(rw, r)
default:
fh.ServeHTTP(rw, r)
}
}))
if err := ws.Listen(listenAddr); err != nil {
logger.Fatalf("listen: %v", err)
}
ws.Serve()
}