-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
522 lines (446 loc) · 11.6 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package main
import (
"bufio"
"embed"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/fs"
"log"
"mime"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"github.com/comame/router-go"
)
//go:embed front/dist
var distFs embed.FS
func main() {
router.Get("/api/tracks", func(w http.ResponseWriter, r *http.Request) {
tracks, _, err := getLibrary()
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
js, err := json.Marshal(tracks)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(js)
})
router.Get("/api/playlists", func(w http.ResponseWriter, r *http.Request) {
_, playlists, err := getLibrary()
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
js, err := json.Marshal(playlists)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(js)
})
router.Get("/api/track/:persistent_id", func(w http.ResponseWriter, r *http.Request) {
p := router.Params(r)
persistentID := p["persistent_id"]
tracks, _, err := getLibrary()
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var track *track
for _, tr := range tracks {
if tr.PersistentID == persistentID {
track = &tr
break
}
}
if track == nil {
w.WriteHeader(http.StatusNotFound)
return
}
loc, err := convLocation(track.Locaton)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
f, err := openSMB(loc)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer f.Close()
st, err := f.Stat()
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
typ := mime.TypeByExtension(path.Ext(loc))
w.Header().Set("Content-Type", typ)
w.Header().Set("Accept-Ranges", "bytes")
rh := r.Header.Get("Range")
rb, re, err := parseRangeHeader(rh)
if err != nil {
w.Header().Set("Content-Length", fmt.Sprint(st.Size()))
io.Copy(w, f)
return
}
if rb < 0 {
log.Println("不正な Range")
w.Header().Set("Content-Length", fmt.Sprint(st.Size()))
io.Copy(w, f)
return
}
if re < 0 {
w.Header().Set("Content-Length", fmt.Sprint(st.Size()-int64(rb)))
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", rb, st.Size()-1, st.Size()))
w.WriteHeader(http.StatusPartialContent)
f.Seek(int64(rb), io.SeekStart)
io.Copy(w, f)
return
}
w.Header().Set("Content-Length", fmt.Sprint(re-rb))
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", rb, re-1, st.Size()))
w.WriteHeader(http.StatusPartialContent)
f.Seek(int64(rb), io.SeekStart)
io.Copy(w, f)
})
var cachedTracks []track
router.Get("/api/artwork/:persistent_id", func(w http.ResponseWriter, r *http.Request) {
p := router.Params(r)
persistentID := p["persistent_id"]
// ライブラリにアクセスしたとき、大量に同時アクセスが飛んでくるため、メモリ上にトラック情報をキャッシュする
if cachedTracks == nil {
t, _, err := getLibrary()
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
cachedTracks = t
}
var track *track
for _, tr := range cachedTracks {
if tr.PersistentID == persistentID {
track = &tr
break
}
}
if track == nil {
w.WriteHeader(http.StatusNotFound)
return
}
pf, err := extractArtworks(*track)
if err != nil {
log.Println("ext: " + err.Error())
w.WriteHeader(http.StatusNotFound)
return
}
defer pf.Close()
w.WriteHeader(http.StatusOK)
io.Copy(w, pf)
})
router.Get("/*", func(w http.ResponseWriter, r *http.Request) {
sub, err := fs.Sub(distFs, "front/dist")
if err != nil {
panic(err)
}
srv := http.FileServer(http.FS(sub))
srv.ServeHTTP(w, r)
})
log.Println("Start http://localhost:8080/")
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, ok := os.LookupEnv("DEV")
if ok {
// log.Println(r.URL.Path)
allowCORSForDev(w)
}
router.Handler().ServeHTTP(w, r)
}))
}
// SMB から iTunes Music Library.xml を取得し、パースして返す
func getLibrary() ([]track, []playlist, error) {
f, err := openSMB("./iTunes Music Library.xml")
if err != nil {
return nil, nil, err
}
defer f.Close()
tracks, playlists, err := parseLibraryXML(f)
if err != nil {
return nil, nil, err
}
return tracks, playlists, nil
}
// TODO: なんか新しくライブラリに生えた曲のアートワークが404になる
// track のアートワーク画像を返す。
// 一度取得されたアートワークはファイルシステムにキャッシュされる。キャッシュがなければ SMB から音声ファイルを取得して、ffmpeg でアートワークを抽出する。
func extractArtworks(track track) (io.ReadCloser, error) {
loc, err := convLocation(track.Locaton)
if err != nil {
return nil, err
}
afpath := track.PersistentID + path.Ext(loc)
// とりあえず初回キャッシュを見てみて、存在すればそのまま返す。
fpf, _ := os.Open(".ar/" + afpath + ".jpg")
if fpf != nil {
return fpf, nil
}
// SMB から音声ファイルを取ってきて、
f, err := openSMB(loc)
if err != nil {
return nil, err
}
defer f.Close()
// ... 作業フォルダを作り、
os.MkdirAll(".ar", 0777)
// ... オーディオファイルをダウンロードし、
log.Printf("download track %s to extract artwork", track.PersistentID)
af, err := os.Create(".ar/" + afpath)
if err != nil {
return nil, err
}
if _, err := io.Copy(af, f); err != nil {
return nil, err
}
if err := af.Sync(); err != nil {
return nil, err
}
defer af.Close()
// ... ffmpeg でアートワークを抽出し、
exec.Command("ffmpeg", "-i", ".ar/"+afpath, "-an", "-c:v", "copy", ".ar/"+afpath+".jpg").Run()
// エラーは握りつぶす。もしここで失敗していたら、次の os.Open でコケるはず
// ... 抽出されたアートワークを開く。
pf, err := os.Open(".ar/" + afpath + ".jpg")
if err != nil {
return nil, errors.Join(fmt.Errorf("failed to extract artwork of track id %s due to ffmpeg error", track.PersistentID), err)
}
return pf, nil
}
// 開発環境では CORS ヘッダを返す
func allowCORSForDev(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:5173")
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
func parseRangeHeader(v string) (int, int, error) {
rp := regexp.MustCompile(`^bytes=(\d+)-(\d+)?$`)
fo := rp.FindAllStringSubmatch(v, 2)
if fo == nil {
return -1, -1, errors.New("unsupported or invalid format of range header")
}
sstr := fo[0][1]
estr := "-1"
if len(fo[0]) == 3 && fo[0][2] != "" {
estr = fo[0][2]
}
sint, err := strconv.ParseInt(sstr, 10, 64)
if err != nil {
return -1, -1, err
}
eint, err := strconv.ParseInt(estr, 10, 64)
if err != nil {
return -1, -1, err
}
return int(sint), int(eint), nil
}
// iTunes Music Library.xml の Location を SMB のパスに変換する
func convLocation(p string) (string, error) {
prefix := os.Getenv("ITUNES_LOCATION_PREFIX")
p = "." + p[len(prefix):]
p = strings.ReplaceAll(p, "+", "%2B")
p, err := url.QueryUnescape(p)
if err != nil {
return "", err
}
return p, nil
}
type track struct {
ID int
TotalTime int
DiscNumber int
DiscCount int
TrackNumber int
TrackCount int
Year int
PersistentID string
Name string
Artist string
AlbumArtist string
Album string
Genre string
Locaton string
Kind string
}
type playlist struct {
ID int
PersistentID string
Name string
ItemTrackIDs []int
}
// iTunes Music Library.xml をパースする。気合の塊
func parseLibraryXML(r io.Reader) ([]track, []playlist, error) {
rb := bufio.NewReader(r)
d := xml.NewDecoder(rb)
isReadingKey := false
isReadingTracks := false
isReadingPlaylists := false
key := ""
valueType := "integer" // or "string"
dictDepth := 0
var tracks []track
currentTrack := track{}
var playlists []playlist
currentPlaylist := playlist{}
for {
rt, err := d.Token()
if err != nil && errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, nil, err
}
switch token := rt.(type) {
case xml.StartElement:
name := token.Name.Local
if name == "key" {
isReadingKey = true
}
if name == "dict" || name == "array" {
dictDepth += 1
}
if name == "string" {
valueType = "string"
}
if name == "integer" {
valueType = "integer"
}
case xml.EndElement:
name := token.Name.Local
if name == "key" {
isReadingKey = false
}
if name == "dict" || name == "array" {
dictDepth -= 1
if isReadingTracks && dictDepth == 2 {
tracks = append(tracks, currentTrack)
currentTrack = track{}
}
if isReadingPlaylists && dictDepth == 2 {
playlists = append(playlists, currentPlaylist)
currentPlaylist = playlist{}
}
}
if name == "integer" || name == "string" {
valueType = ""
}
case xml.CharData:
strToken := string(token)
if isReadingKey {
if !isReadingTracks && !isReadingPlaylists && strToken == "Tracks" {
isReadingTracks = true
}
if isReadingTracks && !isReadingPlaylists && strToken == "Playlists" {
isReadingTracks = false
isReadingPlaylists = true
}
}
if isReadingTracks && dictDepth == 3 {
if isReadingKey {
key = strToken
}
if valueType != "integer" && valueType != "string" {
continue
}
intValue := 0
if valueType == "integer" {
v, err := strconv.ParseInt(strToken, 10, 64)
if err != nil {
return nil, nil, err
}
intValue = int(v)
}
switch key {
case "Track ID":
currentTrack.ID = intValue
case "Total Time":
currentTrack.TotalTime = intValue
case "Disc Number":
currentTrack.DiscNumber = intValue
case "Disc Count":
currentTrack.DiscCount = intValue
case "Track Number":
currentTrack.TrackNumber = intValue
case "Track Count":
currentTrack.TrackCount = intValue
case "Persistent ID":
currentTrack.PersistentID = strToken
case "Year":
currentTrack.Year = intValue
case "Name":
currentTrack.Name = strToken
case "Artist":
currentTrack.Artist = strToken
case "Album Artist":
currentTrack.AlbumArtist = strToken
case "Album":
currentTrack.Album = strToken
case "Genre":
currentTrack.Genre = strToken
case "Location":
currentTrack.Locaton = strToken
case "Kind":
currentTrack.Kind = strToken
}
}
if isReadingPlaylists && dictDepth == 3 {
if isReadingKey {
key = strToken
}
if valueType != "integer" && valueType != "string" {
continue
}
intValue := 0
if valueType == "integer" {
v, err := strconv.ParseInt(strToken, 10, 64)
if err != nil {
return nil, nil, err
}
intValue = int(v)
}
switch key {
case "Playlist ID":
currentPlaylist.ID = intValue
case "Playlist Persistent ID":
currentPlaylist.PersistentID = strToken
case "Name":
currentPlaylist.Name = strToken
}
}
if isReadingPlaylists && dictDepth == 5 {
if valueType != "integer" {
continue
}
v, err := strconv.ParseInt(strToken, 10, 64)
if err != nil {
return nil, nil, err
}
currentPlaylist.ItemTrackIDs = append(currentPlaylist.ItemTrackIDs, int(v))
}
}
}
return tracks, playlists, nil
}