-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupload.go
More file actions
102 lines (79 loc) · 2.1 KB
/
upload.go
File metadata and controls
102 lines (79 loc) · 2.1 KB
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
package main
import (
"bytes"
"fmt"
"net/http"
"os"
"path"
// "path/filepath"
"io"
"github.com/dhowden/tag"
"muhq.space/go/wrms/llog"
)
type UploadBackend struct {
uploadDir string
}
func NewUploadBackend(uploadDir string) (*UploadBackend, error) {
b := UploadBackend{uploadDir: uploadDir}
dirInfo, err := os.Stat(uploadDir)
if os.IsNotExist(err) {
if err = os.MkdirAll(uploadDir, 0750); err != nil {
return nil, err
}
} else if !dirInfo.IsDir() {
llog.Fatal("upload directory %s exists and is not a directory", uploadDir)
}
b.setupUploadRoute()
return &b, nil
}
func (b *UploadBackend) upload(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
if err != nil {
llog.Warning("Failed to read request body: %s", string(data))
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
return
}
fileName := r.URL.Query().Get("song")
filePath := path.Join(b.uploadDir, fileName)
f, err := os.Create(filePath)
if err != nil {
llog.Fatal("Failed to create uploaded %s song on disk: %s", filePath, err)
}
_, err = f.Write(data)
if err != nil {
llog.Fatal("Failed to write uploaded song on disk: %s", err)
}
f.Close()
var title string
var artist string
dataReader := bytes.NewReader(data)
m, err := tag.ReadFrom(dataReader)
if err != nil {
llog.Warning("error reading tags from %s: %v", fileName, err)
} else {
title = m.Title()
artist = m.Artist()
}
if title == "" {
title = fileName
}
if artist == "" {
artist = "Unknown"
}
wrms.AddSong(NewDetailedSong(title, artist, "upload", fileName, m.Album(), m.Year()))
fmt.Fprintf(w, "Added uploaded song %s", string(fileName))
}
func (b *UploadBackend) setupUploadRoute() {
http.HandleFunc("/upload", b.upload)
}
func (b *UploadBackend) OnSongFinished(song *Song) {
songPath := path.Join(b.uploadDir, song.Uri)
llog.Debug("Removing finished song %s", songPath)
os.Remove(songPath)
}
func (b *UploadBackend) Play(song *Song, player Player) {
player.PlayUri("file://" + path.Join(b.uploadDir, song.Uri))
}
func (b *UploadBackend) Search(map[string]string) []*Song {
return nil
}