-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathapi.go
More file actions
306 lines (249 loc) · 7.51 KB
/
Copy pathapi.go
File metadata and controls
306 lines (249 loc) · 7.51 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
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
package main
import (
"encoding/json"
"io/fs"
"net/http"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"github.com/Darep/Beatstream/logger"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"golang.org/x/crypto/bcrypt"
)
var songsRefreshing atomic.Bool
var songsMutex = &sync.RWMutex{}
// Define valid audio file extensions
var validExtensions = map[string]bool{
".mp3": true,
".ogg": true,
".flac": true,
".m4a": true,
".wav": true,
".aac": true,
}
func startApi() {
r := registerRoutes()
host := os.Getenv("HOST")
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
listenUrl := host + ":" + port
logger.Log.Printf("Starting server on %s", listenUrl)
err := http.ListenAndServe(listenUrl, r)
if err != nil {
logger.Log.Fatalf("Failed to start server: %v", err)
}
}
func registerRoutes() *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.With(middleware.NoCache).Post("/api/session", loginHandler)
r.Route("/api", func(r chi.Router) {
r.Use(middleware.NoCache)
r.Use(AuthMiddleware)
r.Get("/session", sessionHandler)
r.Delete("/session", logoutHandler)
r.Put("/password", passwordHandler)
r.Get("/songs", songsHandler)
r.Get("/songs/play", playHandler)
r.Get("/songs/refresh", refreshStatusHandler)
r.Post("/songs/refresh", refreshHandler)
r.Get("/lastfm", lastFMStatusHandler)
r.Post("/lastfm/connect", lastFMConnectHandler)
r.Post("/lastfm/complete", lastFMCompleteHandler)
r.Delete("/lastfm", lastFMDisconnectHandler)
r.Post("/lastfm/scrobble", lastFMScrobbleHandler)
r.Post("/lastfm/now-playing", lastFMNowPlayingHandler)
// r.Get("/playlists", playlistsHandler)
// r.Post("/playlists", createPlaylistHandler)
// r.Put("/playlists/{id}", updatePlaylistHandler)
// r.Delete("/playlists/{id}", deletePlaylistHandler)
})
r.Handle("/*", http.HandlerFunc(frontendHandler))
return r
}
// PUT /api/password
func passwordHandler(w http.ResponseWriter, r *http.Request) {
var passwords struct {
Current string `json:"currentPassword"`
New string `json:"newPassword"`
}
if err := json.NewDecoder(r.Body).Decode(&passwords); err != nil || passwords.New == "" {
http.Error(w, "Invalid password", http.StatusBadRequest)
return
}
username := r.Context().Value("username").(string)
updated := slices.Clone(users)
for i := range updated {
if user := &updated[i]; user.Username == username && bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(passwords.Current)) == nil {
password, err := bcrypt.GenerateFromPassword([]byte(passwords.New), bcrypt.DefaultCost)
if err != nil {
http.Error(w, "Invalid password", http.StatusBadRequest)
return
}
user.Password = string(password)
if err := saveUsers(updated); err != nil {
logger.Log.Printf("Failed to save user configuration: %v", err)
http.Error(w, "Failed to save password", http.StatusInternalServerError)
return
}
users = updated
cookie, _ := r.Cookie(sessionCookieName)
deleteOtherSessions(username, cookie.Value)
respondJSON(w, map[string]string{})
return
}
}
http.Error(w, "Current password is incorrect", http.StatusUnauthorized)
}
// GET /api/session
func sessionHandler(w http.ResponseWriter, r *http.Request) {
username := r.Context().Value("username").(string)
if username == "" && os.Getenv("DISABLE_LOGIN") == "true" {
token := createSession(User{Username: "Anonymous", Password: ""}).Token
http.SetCookie(w, createSessionCookie(token))
}
respondJSON(w, map[string]string{
"username": username,
})
}
// POST /api/session
func loginHandler(w http.ResponseWriter, r *http.Request) {
// reload users just in case
err := loadUsers()
if err != nil {
logger.Log.Printf("Failed to load user configuration: %v", err)
}
username, password, ok := r.BasicAuth()
if !ok {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
for _, user := range users {
if user.Username == username && bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) == nil {
token := createSession(user).Token
// Create & set a new cookie
http.SetCookie(w, createSessionCookie(token))
// Respond with session data (currently username only)
respondJSON(w, map[string]string{
"username": username,
})
return
}
}
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
}
// DELETE /api/session
func logoutHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
http.Error(w, "Session cookie not found", http.StatusUnauthorized)
return
}
// Delete the session
deleteSession(cookie.Value)
// Delete the session cookie
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
MaxAge: -1, // Set MaxAge to -1 to delete the cookie
})
respondJSON(w, map[string]string{})
}
// GET /api/songs
func songsHandler(w http.ResponseWriter, r *http.Request) {
songsMutex.RLock()
defer songsMutex.RUnlock()
fileInfo, err := os.Stat(songsFilePath)
if err != nil || fileInfo.Size() <= 2 {
respondJSON(w, []Song{})
return
}
w.Header().Set("Content-Type", "application/json")
http.ServeFile(w, r, songsFilePath)
}
// GET /api/songs/play?file=relative/path/to/song.mp3
func playHandler(w http.ResponseWriter, r *http.Request) {
relativePath := r.URL.Query().Get("file")
// FIXME: check if the file is in the music directory, or clean the path somehow
songPath := filepath.Join(MusicPath, relativePath)
_, err := os.Stat(songPath)
if os.IsNotExist(err) {
http.Error(w, "Song not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "audio/mpeg")
http.ServeFile(w, r, songPath)
}
// POST /api/songs/refresh
func refreshHandler(w http.ResponseWriter, r *http.Request) {
if !songsRefreshing.CompareAndSwap(false, true) {
http.Error(w, "Another refresh operation is already in progress", http.StatusConflict)
return
}
defer songsRefreshing.Store(false)
err := refreshSongs()
if err != nil {
logger.Log.Println("Failed to refresh songs:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
w.Header().Set("Content-Type", "application/json")
http.ServeFile(w, r, songsFilePath)
}
}
// GET /api/songs/refresh
func refreshStatusHandler(w http.ResponseWriter, _ *http.Request) {
respondJSON(w, map[string]bool{"refreshing": songsRefreshing.Load()})
}
func refreshSongs() error {
logger.Log.Println("Refreshing songs…")
defer logger.Log.Println("Songs refresh done")
songs := make([]Song, 0)
err := filepath.WalkDir(MusicPath, func(path string, e fs.DirEntry, err error) error {
if err != nil || e.IsDir() {
return err
}
extension := strings.ToLower(filepath.Ext(e.Name()))
isValidExtension := validExtensions[extension]
if isValidExtension {
song, err := newSongFromFile(path)
if err != nil {
logger.Log.Println("Failed to read song:", err)
} else if song != nil {
songs = append(songs, *song)
}
}
return nil
})
if err != nil {
return err
}
logger.Log.Println("Found", len(songs), "songs")
// Sort songs
sort.Slice(songs, func(i, j int) bool {
return songs[i].ToNaturalSortString() < songs[j].ToNaturalSortString()
})
// lock "songs.json" so that it's not read while being written
songsMutex.Lock()
defer songsMutex.Unlock()
// Write songs to file
file, err := os.Create(songsFilePath)
if err != nil {
return err
}
defer file.Close()
logger.Log.Println("Writing songs to file…")
err = json.NewEncoder(file).Encode(songs)
if err != nil {
return err
}
return nil
}