Restructure backend into services and fix security, crash and sync issues

Security
- Serve character images through os.Root so names like ../ can't escape
  the characters folder
- Sync start and /sync/reset are POST only (legacy and /api/v1)
- /api/v1/token/cleanup requires a token, password compared in constant
  time, tokens no longer logged
- Echo's rate limiter replaces the custom one; TRUSTED_PROXIES enables
  X-Forwarded-For for reverse proxies

Crashes and races
- Sync state lives in SyncService with atomics and a mutex instead of
  unsynchronised globals (fixes concurrent map writes during full sync)
- Only one sync can run; /api/v1 sync and music routes are locked during
  sync like the legacy ones
- No log.Fatal outside startup: errors become 4xx/5xx responses
- Search uses an in-order character match instead of unescaped regexes
- Empty queue / no songs return 404 instead of panicking or looping

Behaviour
- Sync result is computed once and stays the same between polls
- Swagger and /openapi serve the embedded spec
- Shutdown stops HTTP before closing the database
- Expired tokens are deleted with a context that outlives the request
- Files are served with Range support and correct content types; audio
  has no write deadline

Performance
- Migration 000006 adds soundtrack.fingerprint (names, sizes, mtimes) so
  unchanged folders are skipped without reading any files
- Songs are reconciled per soundtrack with one query plus needed writes;
  renames keep play counts
- Moved MUSIC_PATH updates soundtrack and song paths
- .id cleanup only runs for changed soundtracks or a full sync
- Classic random uses one SQL query; Gitea release lookups are cached
  with a timeout

Structure
- internal/config reads all environment variables once
- sqlc emits a Querier interface; backend globals become services
  injected into handlers
- One route registration shared by legacy and /api/v1
- Removed dead code (dbHelper.go, unused middleware, duplicate Gitea
  functions, embedded Swagger UI copy) and lib/pq
- templ and swag pinned as go tools
This commit is contained in:
Sansan committed 2026-10-06 15:20:14 +02:00
1 parent 75b6f0c1cf
commit 090e794460
78 files changed
+2919 -6303

No files matched your search

-40
View File
@@ -1,40 +0,0 @@
package backend
import (
"context"
"music-server/internal/db/repository"
"github.com/jackc/pgx/v5/pgxpool"
)
// Global variables - these are initialized by InitBackend
var (
backendPool *pgxpool.Pool
repo *repository.Queries
backendCtx context.Context = context.Background()
)
// InitBackend initializes the backend package with the database pool.
// This should be called once at application startup.
func InitBackend(pool *pgxpool.Pool) {
backendPool = pool
repo = repository.New(pool)
backendCtx = context.Background()
}
// BackendCtx returns the context used by backend operations.
// This is exposed for use by the backend functions.
func BackendCtx() context.Context {
return backendCtx
}
// BackendRepo returns the repository queries instance.
// This is exposed for use by the backend functions.
func BackendRepo() *repository.Queries {
return repo
}
// BackendPool returns the underlying database pool.
// This is exposed for test utilities that need direct pool access.
func BackendPool() *pgxpool.Pool {
return backendPool
}
+47 -27
View File
@@ -1,43 +1,63 @@
package backend
import (
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"go.uber.org/zap"
"music-server/internal/logging"
)
func GetCharacterList() []string {
charactersPath := os.Getenv("CHARACTERS_PATH")
logging.GetLogger().Debug("Getting character list", zap.String("path", charactersPath))
// Clean the path - remove trailing slashes and then add one for consistency
charactersPath = strings.TrimSuffix(charactersPath, "/")
charactersPath += "/"
files, err := os.ReadDir(charactersPath)
if err != nil {
logging.GetLogger().Fatal("Failed to read characters directory", zap.String("path", charactersPath), zap.String("error", err.Error()))
}
// CharacterService serves character images from a single directory.
type CharacterService struct {
root *os.Root
}
// NewCharacterService opens the characters directory. Files outside it can never be served.
func NewCharacterService(path string) (*CharacterService, error) {
root, err := os.OpenRoot(path)
if err != nil {
return nil, err
}
return &CharacterService{root: root}, nil
}
// List returns the file names of all character images.
func (c *CharacterService) List() ([]string, error) {
entries, err := fs.ReadDir(c.root.FS(), ".")
if err != nil {
return nil, err
}
var characters []string
for _, file := range files {
if isImage(file) {
characters = append(characters, file.Name())
for _, entry := range entries {
if !entry.IsDir() && isImage(entry.Name()) {
characters = append(characters, entry.Name())
}
}
return characters
return characters, nil
}
func GetCharacter(character string) string {
charactersPath := os.Getenv("CHARACTERS_PATH")
// Clean the path - remove trailing slashes and then add one for consistency
charactersPath = strings.TrimSuffix(charactersPath, "/")
charactersPath += "/"
logging.GetLogger().Debug("Getting character", zap.String("character", character), zap.String("path", charactersPath+character))
return charactersPath + character
// Open opens the character image with the given file name.
func (c *CharacterService) Open(name string) (*os.File, error) {
if name == "" || name != filepath.Base(name) || !isImage(name) {
return nil, ErrInvalidName
}
f, err := c.root.Open(name)
if errors.Is(err, fs.ErrNotExist) {
return nil, ErrNotFound
}
return f, err
}
func isImage(entry os.DirEntry) bool {
return !entry.IsDir() && (strings.HasSuffix(entry.Name(), ".jpg") || strings.HasSuffix(entry.Name(), ".jpeg") ||
strings.HasSuffix(entry.Name(), ".png"))
// Close releases the characters directory.
func (c *CharacterService) Close() error {
return c.root.Close()
}
func isImage(name string) bool {
switch strings.ToLower(filepath.Ext(name)) {
case ".jpg", ".jpeg", ".png":
return true
}
return false
}
-90
View File
@@ -1,90 +0,0 @@
package backend
import (
"io/fs"
"os"
"testing"
)
func TestIsImage(t *testing.T) {
tests := []struct {
name string
entry fs.DirEntry
expected bool
}{
{
name: "jpg file",
entry: &mockDirEntry{name: "test.jpg", isDir: false},
expected: true,
},
{
name: "jpeg file",
entry: &mockDirEntry{name: "test.jpeg", isDir: false},
expected: true,
},
{
name: "png file",
entry: &mockDirEntry{name: "test.png", isDir: false},
expected: true,
},
{
name: "directory",
entry: &mockDirEntry{name: "test", isDir: true},
expected: false,
},
{
name: "txt file",
entry: &mockDirEntry{name: "test.txt", isDir: false},
expected: false,
},
{
name: "mp3 file",
entry: &mockDirEntry{name: "test.mp3", isDir: false},
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isImage(tt.entry)
if result != tt.expected {
t.Errorf("isImage() = %v, want %v", result, tt.expected)
}
})
}
}
type mockDirEntry struct {
name string
isDir bool
}
func (m *mockDirEntry) Name() string { return m.name }
func (m *mockDirEntry) IsDir() bool { return m.isDir }
func (m *mockDirEntry) Type() fs.FileMode { return 0 }
func (m *mockDirEntry) Info() (fs.FileInfo, error) { return nil, nil }
func (m *mockDirEntry) Sys() interface{} { return nil }
func TestGetCharacter(t *testing.T) {
os.Setenv("CHARACTERS_PATH", "/test/path")
defer os.Unsetenv("CHARACTERS_PATH")
result := GetCharacter("test.jpg")
expected := "/test/path/test.jpg"
if result != expected {
t.Errorf("GetCharacter() = %v, want %v", result, expected)
}
}
func TestGetCharacterWithTrailingSlash(t *testing.T) {
os.Setenv("CHARACTERS_PATH", "/test/path/")
defer os.Unsetenv("CHARACTERS_PATH")
result := GetCharacter("test.jpg")
expected := "/test/path/test.jpg"
if result != expected {
t.Errorf("GetCharacter() = %v, want %v", result, expected)
}
}
-103
View File
@@ -1,103 +0,0 @@
package backend
import (
"encoding/json"
"net/http"
"strings"
"music-server/internal/logging"
"go.uber.org/zap"
)
type giteaResponse struct {
Id int `json:"id"`
Name string `json:"name"`
Assets []assetResponse `json:"assets"`
}
type assetResponse struct {
Id int `json:"id"`
Name string `json:"name"`
DownloadUrl string `json:"browser_download_url"`
}
func CheckLatest() string {
resp, err := http.Get("https://gitea.sanplex.xyz/api/v1/repos/sansan/MusicPlayer/releases/latest")
if err != nil {
logging.GetLogger().Fatal("Failed to check latest version", zap.String("error", err.Error()))
}
defer resp.Body.Close()
//Create a variable of the same type as our model
var cResp giteaResponse
//Decode the data
if err := json.NewDecoder(resp.Body).Decode(&cResp); err != nil {
logging.GetLogger().Fatal("Failed to decode response", zap.String("error", err.Error()))
}
logging.GetLogger().Debug("Checked latest version", zap.Int("id", cResp.Id), zap.String("name", cResp.Name))
return cResp.Name
}
func ListAssetsOfLatest() []string {
resp, err := http.Get("https://gitea.sanplex.xyz/api/v1/repos/sansan/MusicPlayer/releases/latest")
if err != nil {
logging.GetLogger().Fatal("Failed to list assets", zap.String("error", err.Error()))
}
defer resp.Body.Close()
//Create a variable of the same type as our model
var cResp giteaResponse
//Decode the data
if err := json.NewDecoder(resp.Body).Decode(&cResp); err != nil {
logging.GetLogger().Fatal("Failed to decode response", zap.String("error", err.Error()))
}
logging.GetLogger().Debug("Listing assets", zap.Int("id", cResp.Id), zap.String("name", cResp.Name))
var assets []string
for _, asset := range cResp.Assets {
logging.GetLogger().Debug("Found asset", zap.Int("id", cResp.Id), zap.String("name", cResp.Name), zap.String("asset", asset.Name))
assets = append(assets, asset.Name)
}
return assets
}
func DownloadLatestWindows() string {
resp, err := http.Get("https://gitea.sanplex.xyz/api/v1/repos/sansan/MusicPlayer/releases/latest")
if err != nil {
logging.GetLogger().Fatal("Failed to download latest Windows version", zap.String("error", err.Error()))
}
defer resp.Body.Close()
//Create a variable of the same type as our model
var cResp giteaResponse
//Decode the data
if err := json.NewDecoder(resp.Body).Decode(&cResp); err != nil {
logging.GetLogger().Fatal("Failed to decode response", zap.String("error", err.Error()))
}
logging.GetLogger().Debug("Downloading Windows version", zap.Int("id", cResp.Id), zap.String("name", cResp.Name))
for _, asset := range cResp.Assets {
logging.GetLogger().Debug("Checking asset", zap.Int("id", cResp.Id), zap.String("name", cResp.Name), zap.String("asset", asset.Name))
if strings.HasSuffix(asset.Name, ".exe") {
return asset.DownloadUrl
}
}
return ""
}
func DownloadLatestLinux() string {
resp, err := http.Get("https://gitea.sanplex.xyz/api/v1/repos/sansan/MusicPlayer/releases/latest")
if err != nil {
logging.GetLogger().Fatal("Failed to download latest Linux version", zap.String("error", err.Error()))
}
defer resp.Body.Close()
//Create a variable of the same type as our model
var cResp giteaResponse
//Decode the data
if err := json.NewDecoder(resp.Body).Decode(&cResp); err != nil {
logging.GetLogger().Fatal("Failed to decode response", zap.String("error", err.Error()))
}
logging.GetLogger().Debug("Downloading Linux version", zap.Int("id", cResp.Id), zap.String("name", cResp.Name))
for _, asset := range cResp.Assets {
logging.GetLogger().Debug("Checking asset", zap.Int("id", cResp.Id), zap.String("name", cResp.Name), zap.String("asset", asset.Name))
if strings.HasSuffix(asset.Name, ".x86_64") {
return asset.DownloadUrl
}
}
return ""
}
-61
View File
@@ -1,61 +0,0 @@
package backend
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestCheckLatest(t *testing.T) {
mockResponse := giteaResponse{
Id: 1,
Name: "v1.0.0",
Assets: []assetResponse{
{Id: 1, Name: "app.exe", DownloadUrl: "http://example.com/app.exe"},
},
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(mockResponse)
}))
defer server.Close()
originalURL := "https://gitea.sanplex.xyz/api/v1/repos/sansan/MusicPlayer/releases/latest"
_ = originalURL
// Note: This test would need mocking of http.Get to fully work
// For now, we'll just test the parsing logic
// In a real scenario, you'd use httpmock or similar
}
func TestListAssetsOfLatest(t *testing.T) {
mockResponse := giteaResponse{
Id: 1,
Name: "v1.0.0",
Assets: []assetResponse{
{Id: 1, Name: "app.exe", DownloadUrl: "http://example.com/app.exe"},
{Id: 2, Name: "app.x86_64", DownloadUrl: "http://example.com/app.x86_64"},
{Id: 3, Name: "app.dmg", DownloadUrl: "http://example.com/app.dmg"},
},
}
// Test the parsing of the response
var cResp giteaResponse
data, _ := json.Marshal(mockResponse)
json.Unmarshal(data, &cResp)
var assets []string
for _, asset := range cResp.Assets {
assets = append(assets, asset.Name)
}
if len(assets) != 3 {
t.Errorf("Expected 3 assets, got %d", len(assets))
}
if assets[0] != "app.exe" {
t.Errorf("Expected first asset to be app.exe, got %s", assets[0])
}
}
+16
View File
@@ -0,0 +1,16 @@
package backend
import "errors"
var (
// ErrQueueEmpty is returned when the play queue has no songs.
ErrQueueEmpty = errors.New("song queue is empty")
// ErrNoSongs is returned when no playable song could be found.
ErrNoSongs = errors.New("no playable songs found")
// ErrNotFound is returned when a requested resource does not exist.
ErrNotFound = errors.New("not found")
// ErrInvalidName is returned when a requested file name is not allowed.
ErrInvalidName = errors.New("invalid name")
// ErrUpstream is returned when an external service could not be reached.
ErrUpstream = errors.New("upstream service unavailable")
)
+285 -247
View File
@@ -1,16 +1,25 @@
package backend
import (
"math/rand"
"context"
"errors"
"math/rand/v2"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"music-server/internal/db/repository"
"music-server/internal/logging"
"os"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"go.uber.org/zap"
)
// maxPickAttempts bounds how many broken songs are skipped before giving up.
const maxPickAttempts = 100
type SongInfo struct {
Soundtrack string `json:"Soundtrack"`
SoundtrackPlayed int32 `json:"SoundtrackPlayed"`
@@ -20,303 +29,332 @@ type SongInfo struct {
SongNo int `json:"SongNo"`
}
var currentSong = -1
// MusicService picks songs and keeps track of the shared play queue.
type MusicService struct {
q repository.Querier
soundCheckPath string
var soundtracksNew []repository.Soundtrack
cacheMu sync.Mutex
soundtracks []repository.Soundtrack
var songQueNew []repository.Song
var lastFetchedNew repository.Song
func initRepo() {
// This function is kept for backward compatibility
// but now uses the backend package's initialized repo
// If not initialized, this will panic intentionally
if BackendRepo() == nil {
panic("backend not initialized - call backend.InitBackend() first")
}
// Queue state is shared by all clients and intentionally not locked.
queue []repository.Song
currentSong int
lastFetched repository.Song
}
func getAllSoundtracks() []repository.Soundtrack {
if len(soundtracksNew) == 0 {
initRepo()
soundtracksNew, _ = BackendRepo().FindAllSoundtracks(BackendCtx())
}
return soundtracksNew
// NewMusicService creates a MusicService. soundCheckPath is the directory holding sound check songs.
func NewMusicService(q repository.Querier, soundCheckPath string) *MusicService {
return &MusicService{q: q, soundCheckPath: soundCheckPath, currentSong: -1}
}
func GetSoundCheckSong() string {
files, err := os.ReadDir("songs")
if err != nil {
logging.GetLogger().Fatal("Failed to read songs directory", zap.String("error", err.Error()))
}
fileInfo := files[rand.Intn(len(files))]
return "songs/" + fileInfo.Name()
}
func Reset() {
songQueNew = nil
currentSong = -1
initRepo()
soundtracksNew, _ = BackendRepo().FindAllSoundtracks(BackendCtx())
}
func AddLatestToQue() {
if lastFetchedNew.Path != "" {
currentSong = len(songQueNew)
songQueNew = append(songQueNew, lastFetchedNew)
lastFetchedNew = repository.Song{}
}
}
func AddLatestPlayed() {
if len(songQueNew) == 0 {
return
}
currentSongData := songQueNew[currentSong]
initRepo()
BackendRepo().AddSoundtrackPlayed(BackendCtx(), currentSongData.SoundtrackID)
BackendRepo().AddSongPlayed(BackendCtx(), repository.AddSongPlayedParams{SoundtrackID: currentSongData.SoundtrackID, SongName: currentSongData.SongName})
}
func SetPlayed(songNumber int) {
if len(songQueNew) == 0 || songNumber >= len(songQueNew) {
return
}
songData := songQueNew[songNumber]
initRepo()
BackendRepo().AddSoundtrackPlayed(BackendCtx(), songData.SoundtrackID)
BackendRepo().AddSongPlayed(BackendCtx(), repository.AddSongPlayedParams{SoundtrackID: songData.SoundtrackID, SongName: songData.SongName})
}
func GetRandomSong() string {
getAllSoundtracks()
if len(soundtracksNew) == 0 {
return ""
}
song := getSongFromList(soundtracksNew)
lastFetchedNew = song
return song.Path
}
func GetRandomSongLowChance() string {
getAllSoundtracks()
var listOfSoundtracks []repository.Soundtrack
var averagePlayed = getAveragePlayed()
for _, data := range soundtracksNew {
timesToAdd := averagePlayed - data.TimesPlayed
if timesToAdd <= 0 {
listOfSoundtracks = append(listOfSoundtracks, data)
} else {
for i := int32(0); i < timesToAdd; i++ {
listOfSoundtracks = append(listOfSoundtracks, data)
}
}
}
song := getSongFromList(listOfSoundtracks)
lastFetchedNew = song
return song.Path
}
func GetRandomSongClassic() string {
getAllSoundtracks()
var listOfAllSongs []repository.Song
for _, soundtrack := range soundtracksNew {
songList, _ := BackendRepo().FindSongsFromSoundtrack(BackendCtx(), soundtrack.ID)
listOfAllSongs = append(listOfAllSongs, songList...)
}
songFound := false
var song repository.Song
for !songFound {
song = listOfAllSongs[rand.Intn(len(listOfAllSongs))]
soundtrackData, err := BackendRepo().GetSoundtrackById(BackendCtx(), song.SoundtrackID)
func (m *MusicService) allSoundtracks(ctx context.Context) ([]repository.Soundtrack, error) {
m.cacheMu.Lock()
defer m.cacheMu.Unlock()
if len(m.soundtracks) == 0 {
soundtracks, err := m.q.FindAllSoundtracks(ctx)
if err != nil {
BackendRepo().RemoveBrokenSong(BackendCtx(), repository.RemoveBrokenSongParams{SoundtrackID: song.SoundtrackID, Path: song.Path})
logging.GetLogger().Warn("Song not found, removed from database",
zap.String("song", song.SongName),
zap.String("soundtrack", soundtrackData.SoundtrackName),
zap.String("filename", *song.FileName))
return nil, err
}
m.soundtracks = soundtracks
}
return m.soundtracks, nil
}
// Reset clears the play queue and reloads the soundtrack list.
func (m *MusicService) Reset(ctx context.Context) error {
m.queue = nil
m.currentSong = -1
m.cacheMu.Lock()
m.soundtracks = nil
m.cacheMu.Unlock()
_, err := m.allSoundtracks(ctx)
return err
}
// SoundCheckSong returns the path of a random sound check song.
func (m *MusicService) SoundCheckSong() (string, error) {
files, err := os.ReadDir(m.soundCheckPath)
if err != nil {
return "", err
}
files = slices.DeleteFunc(files, func(f os.DirEntry) bool { return f.IsDir() })
if len(files) == 0 {
return "", ErrNoSongs
}
return filepath.Join(m.soundCheckPath, files[rand.IntN(len(files))].Name()), nil
}
// AddLatestToQueue appends the last fetched random song to the queue.
func (m *MusicService) AddLatestToQueue() {
if m.lastFetched.Path != "" {
m.currentSong = len(m.queue)
m.queue = append(m.queue, m.lastFetched)
m.lastFetched = repository.Song{}
}
}
// AddLatestPlayed increments the play counters of the current song.
func (m *MusicService) AddLatestPlayed(ctx context.Context) error {
if !m.validIndex(m.currentSong) {
return nil
}
return m.markPlayed(ctx, m.queue[m.currentSong])
}
// SetPlayed increments the play counters of the song at the given queue position.
func (m *MusicService) SetPlayed(ctx context.Context, songNumber int) error {
if !m.validIndex(songNumber) {
return nil
}
return m.markPlayed(ctx, m.queue[songNumber])
}
func (m *MusicService) markPlayed(ctx context.Context, song repository.Song) error {
if err := m.q.AddSoundtrackPlayed(ctx, song.SoundtrackID); err != nil {
return err
}
return m.q.AddSongPlayed(ctx, repository.AddSongPlayedParams{SoundtrackID: song.SoundtrackID, SongName: song.SongName})
}
func (m *MusicService) validIndex(i int) bool {
return i >= 0 && i < len(m.queue)
}
// RandomSong picks a random song from a random soundtrack.
func (m *MusicService) RandomSong(ctx context.Context) (string, error) {
soundtracks, err := m.allSoundtracks(ctx)
if err != nil {
return "", err
}
candidates := make([]weightedSoundtrack, len(soundtracks))
for i, s := range soundtracks {
candidates[i] = weightedSoundtrack{soundtrack: s, weight: 1}
}
return m.pickAndRemember(ctx, candidates)
}
// RandomSongLowChance picks a random song, favouring soundtracks played less than average.
func (m *MusicService) RandomSongLowChance(ctx context.Context) (string, error) {
soundtracks, err := m.allSoundtracks(ctx)
if err != nil {
return "", err
}
return m.pickAndRemember(ctx, lowChanceWeights(soundtracks))
}
func (m *MusicService) pickAndRemember(ctx context.Context, candidates []weightedSoundtrack) (string, error) {
song, err := m.pickSong(ctx, candidates)
if err != nil {
return "", err
}
m.lastFetched = song
return song.Path, nil
}
// RandomSongClassic picks a random song where every song has the same chance.
func (m *MusicService) RandomSongClassic(ctx context.Context) (string, error) {
for range maxPickAttempts {
row, err := m.q.GetRandomActiveSong(ctx)
if errors.Is(err, pgx.ErrNoRows) {
return "", ErrNoSongs
}
if err != nil {
return "", err
}
if !songIsPlayable(row.Song, row.SoundtrackPath) {
if err := m.removeBrokenSong(ctx, row.Song); err != nil {
return "", err
}
continue
}
//Check if file exists and open
openFile, err := os.Open(song.Path)
if err != nil || (song.FileName != nil && soundtrackData.Path+*song.FileName != song.Path) {
//File not found
BackendRepo().RemoveBrokenSong(BackendCtx(), repository.RemoveBrokenSongParams{SoundtrackID: song.SoundtrackID, Path: song.Path})
logging.GetLogger().Warn("Song not found, removed from database",
zap.String("song", song.SongName),
zap.String("soundtrack", soundtrackData.SoundtrackName),
zap.String("filename", *song.FileName))
} else {
songFound = true
}
err = openFile.Close()
if err != nil {
logging.GetLogger().Error("Failed to close file", zap.String("error", err.Error()))
}
m.lastFetched = row.Song
return row.Song.Path, nil
}
lastFetchedNew = song
return song.Path
return "", ErrNoSongs
}
func GetSongInfo() SongInfo {
if songQueNew == nil {
// SongInfo returns information about the current song in the queue.
func (m *MusicService) SongInfo(ctx context.Context) SongInfo {
if !m.validIndex(m.currentSong) {
return SongInfo{}
}
var currentSongData = songQueNew[currentSong]
currentSoundtrackData := getCurrentSoundtrack(currentSongData)
song := m.queue[m.currentSong]
soundtrack := m.soundtrackFor(ctx, song)
return SongInfo{
Soundtrack: currentSoundtrackData.SoundtrackName,
SoundtrackPlayed: currentSoundtrackData.TimesPlayed,
Song: currentSongData.SongName,
SongPlayed: currentSongData.TimesPlayed,
Soundtrack: soundtrack.SoundtrackName,
SoundtrackPlayed: soundtrack.TimesPlayed,
Song: song.SongName,
SongPlayed: song.TimesPlayed,
CurrentlyPlaying: true,
SongNo: currentSong,
SongNo: m.currentSong,
}
}
func GetPlayedSongs() []SongInfo {
// PlayedSongs returns all songs in the queue.
func (m *MusicService) PlayedSongs(ctx context.Context) []SongInfo {
var songList []SongInfo
for i, song := range songQueNew {
soundtrackData := getCurrentSoundtrack(song)
for i, song := range m.queue {
soundtrack := m.soundtrackFor(ctx, song)
songList = append(songList, SongInfo{
Soundtrack: soundtrackData.SoundtrackName,
SoundtrackPlayed: soundtrackData.TimesPlayed,
Soundtrack: soundtrack.SoundtrackName,
SoundtrackPlayed: soundtrack.TimesPlayed,
Song: song.SongName,
SongPlayed: song.TimesPlayed,
CurrentlyPlaying: i == currentSong,
CurrentlyPlaying: i == m.currentSong,
SongNo: i,
})
}
return songList
}
func GetSong(song string) string {
currentSong, _ = strconv.Atoi(song)
if currentSong >= len(songQueNew) {
currentSong = len(songQueNew) - 1
} else if currentSong < 0 {
currentSong = 0
// Song jumps to the given queue position (clamped to the queue) and returns its path.
func (m *MusicService) Song(songNumber int) (string, error) {
if len(m.queue) == 0 {
return "", ErrQueueEmpty
}
songData := songQueNew[currentSong]
return songData.Path
m.currentSong = max(0, min(songNumber, len(m.queue)-1))
return m.queue[m.currentSong].Path, nil
}
func GetAllSoundtracks() []string {
getAllSoundtracks()
var jsonArray []string
for _, soundtrack := range soundtracksNew {
jsonArray = append(jsonArray, soundtrack.SoundtrackName)
// NextSong moves to the next song in the queue, staying on the last one at the end.
func (m *MusicService) NextSong() (string, error) {
if len(m.queue) == 0 {
return "", ErrQueueEmpty
}
return jsonArray
return m.Song(m.currentSong + 1)
}
func GetAllSoundtracksRandom() []string {
getAllSoundtracks()
var jsonArray []string
for _, soundtrack := range soundtracksNew {
jsonArray = append(jsonArray, soundtrack.SoundtrackName)
// PreviousSong moves to the previous song in the queue, staying on the first one at the start.
func (m *MusicService) PreviousSong() (string, error) {
if len(m.queue) == 0 {
return "", ErrQueueEmpty
}
rand.Shuffle(len(jsonArray), func(i, j int) { jsonArray[i], jsonArray[j] = jsonArray[j], jsonArray[i] })
return jsonArray
return m.Song(m.currentSong - 1)
}
func GetNextSong() string {
if songQueNew == nil {
return ""
// SoundtrackNames returns all soundtrack names in alphabetical order.
func (m *MusicService) SoundtrackNames(ctx context.Context) ([]string, error) {
soundtracks, err := m.allSoundtracks(ctx)
if err != nil {
return nil, err
}
if currentSong == len(songQueNew)-1 || currentSong == -1 {
songData := songQueNew[currentSong]
return songData.Path
} else {
currentSong = currentSong + 1
songData := songQueNew[currentSong]
return songData.Path
names := make([]string, len(soundtracks))
for i, s := range soundtracks {
names[i] = s.SoundtrackName
}
return names, nil
}
func GetPreviousSong() string {
if songQueNew == nil {
return ""
}
if currentSong == -1 || currentSong == 0 {
songData := songQueNew[0]
return songData.Path
} else {
currentSong = currentSong - 1
songData := songQueNew[currentSong]
return songData.Path
}
// SoundtrackNamesRandom returns all soundtrack names in random order.
func (m *MusicService) SoundtrackNamesRandom(ctx context.Context) ([]string, error) {
names, err := m.SoundtrackNames(ctx)
rand.Shuffle(len(names), func(i, j int) { names[i], names[j] = names[j], names[i] })
return names, err
}
func getSongFromList(soundtracks []repository.Soundtrack) repository.Song {
songFound := false
var song repository.Song
for !songFound {
soundtrack := getRandomSoundtrack(soundtracks)
songs, _ := BackendRepo().FindSongsFromSoundtrack(BackendCtx(), soundtrack.ID)
type weightedSoundtrack struct {
soundtrack repository.Soundtrack
weight int
}
// lowChanceWeights gives each soundtrack a weight of how far it is below the average play count (at least 1).
func lowChanceWeights(soundtracks []repository.Soundtrack) []weightedSoundtrack {
average := averagePlayed(soundtracks)
weighted := make([]weightedSoundtrack, len(soundtracks))
for i, s := range soundtracks {
weighted[i] = weightedSoundtrack{soundtrack: s, weight: max(1, int(average-s.TimesPlayed))}
}
return weighted
}
func averagePlayed(soundtracks []repository.Soundtrack) int32 {
if len(soundtracks) == 0 {
return 0
}
var sum int64
for _, s := range soundtracks {
sum += int64(s.TimesPlayed)
}
return int32(sum / int64(len(soundtracks)))
}
func pickWeighted(candidates []weightedSoundtrack) int {
total := 0
for _, c := range candidates {
total += c.weight
}
n := rand.IntN(total)
for i, c := range candidates {
if n < c.weight {
return i
}
n -= c.weight
}
return len(candidates) - 1
}
// pickSong picks a random playable song. Soundtracks without songs are dropped from the candidates
// and broken songs are removed from the database.
func (m *MusicService) pickSong(ctx context.Context, candidates []weightedSoundtrack) (repository.Song, error) {
candidates = slices.Clone(candidates)
for range maxPickAttempts {
if len(candidates) == 0 {
return repository.Song{}, ErrNoSongs
}
i := pickWeighted(candidates)
soundtrack := candidates[i].soundtrack
songs, err := m.q.FindSongsFromSoundtrack(ctx, soundtrack.ID)
if err != nil {
return repository.Song{}, err
}
if len(songs) == 0 {
candidates = slices.Delete(candidates, i, i+1)
continue
}
song = songs[rand.Intn(len(songs))]
song := songs[rand.IntN(len(songs))]
logging.GetLogger().Debug("Selected song", zap.String("song", song.SongName), zap.String("path", song.Path))
//Check if file exists and open
openFile, err := os.Open(song.Path)
if err != nil || (song.FileName != nil && soundtrack.Path+*song.FileName != song.Path) || (song.FileName != nil && strings.HasSuffix(*song.FileName, ".wav")) {
//File not found
BackendRepo().RemoveBrokenSong(BackendCtx(), repository.RemoveBrokenSongParams{SoundtrackID: song.SoundtrackID, Path: song.Path})
logging.GetLogger().Warn("Song not found, removed from database",
zap.String("song", song.SongName),
zap.String("soundtrack", soundtrack.SoundtrackName),
zap.Any("filename", song.FileName))
} else {
songFound = true
}
err = openFile.Close()
if err != nil {
logging.GetLogger().Error("Failed to close file", zap.String("path", song.Path), zap.String("error", err.Error()))
if !songIsPlayable(song, soundtrack.Path) {
if err := m.removeBrokenSong(ctx, song); err != nil {
return repository.Song{}, err
}
continue
}
return song, nil
}
return song
return repository.Song{}, ErrNoSongs
}
func getCurrentSoundtrack(currentSongData repository.Song) repository.Soundtrack {
for _, soundtrack := range soundtracksNew {
if soundtrack.ID == currentSongData.SoundtrackID {
func (m *MusicService) removeBrokenSong(ctx context.Context, song repository.Song) error {
logging.GetLogger().Warn("Song not found, removing from database",
zap.String("song", song.SongName),
zap.String("path", song.Path))
return m.q.RemoveBrokenSong(ctx, repository.RemoveBrokenSongParams{SoundtrackID: song.SoundtrackID, Path: song.Path})
}
// songIsPlayable reports whether the song file exists and its stored path is consistent.
func songIsPlayable(song repository.Song, soundtrackPath string) bool {
if song.FileName != nil {
if soundtrackPath+*song.FileName != song.Path || strings.HasSuffix(strings.ToLower(*song.FileName), ".wav") {
return false
}
}
info, err := os.Stat(song.Path)
return err == nil && !info.IsDir()
}
func (m *MusicService) soundtrackFor(ctx context.Context, song repository.Song) repository.Soundtrack {
soundtracks, err := m.allSoundtracks(ctx)
if err != nil {
logging.GetLogger().Error("Failed to load soundtracks", zap.Error(err))
return repository.Soundtrack{}
}
for _, soundtrack := range soundtracks {
if soundtrack.ID == song.SoundtrackID {
return soundtrack
}
}
return repository.Soundtrack{}
}
func getAveragePlayed() int32 {
getAllSoundtracks()
var sum int32
for _, data := range soundtracksNew {
sum += data.TimesPlayed
}
return sum / int32(len(soundtracksNew))
}
func getRandomSoundtrack(listOfSoundtracks []repository.Soundtrack) repository.Soundtrack {
return listOfSoundtracks[rand.Intn(len(listOfSoundtracks))]
}
-201
View File
@@ -1,201 +0,0 @@
package backend
import (
"math/rand"
"testing"
"music-server/internal/db/repository"
)
// Test the average calculation logic directly without database access
func TestCalculateAverage(t *testing.T) {
soundtracks := []repository.Soundtrack{
{SoundtrackName: "Soundtrack1", TimesPlayed: 10},
{SoundtrackName: "Soundtrack2", TimesPlayed: 20},
{SoundtrackName: "Soundtrack3", TimesPlayed: 30},
}
var sum int32
for _, data := range soundtracks {
sum += data.TimesPlayed
}
result := sum / int32(len(soundtracks))
expected := int32(20)
if result != expected {
t.Errorf("Average calculation = %v, want %v", result, expected)
}
}
func TestCalculateAverageEmpty(t *testing.T) {
soundtracks := []repository.Soundtrack{}
if len(soundtracks) == 0 {
result := int32(0)
expected := int32(0)
if result != expected {
t.Errorf("Average calculation with empty list = %v, want %v", result, expected)
}
return
}
var sum int32
for _, data := range soundtracks {
sum += data.TimesPlayed
}
result := sum / int32(len(soundtracks))
expected := int32(0)
if result != expected {
t.Errorf("Average calculation with empty list = %v, want %v", result, expected)
}
}
func TestCalculateAverageSingle(t *testing.T) {
soundtracks := []repository.Soundtrack{
{SoundtrackName: "Soundtrack1", TimesPlayed: 42},
}
var sum int32
for _, data := range soundtracks {
sum += data.TimesPlayed
}
result := sum / int32(len(soundtracks))
expected := int32(42)
if result != expected {
t.Errorf("Average calculation with single soundtrack = %v, want %v", result, expected)
}
}
func TestGetRandomSoundtrack(t *testing.T) {
soundtracks := []repository.Soundtrack{
{SoundtrackName: "Soundtrack1", TimesPlayed: 10},
{SoundtrackName: "Soundtrack2", TimesPlayed: 20},
{SoundtrackName: "Soundtrack3", TimesPlayed: 30},
}
// Set seed for reproducible tests
rand.Seed(42)
result := soundtracks[rand.Intn(len(soundtracks))]
if result.SoundtrackName == "" {
t.Error("random soundtrack selection returned empty soundtrack")
}
found := false
for _, s := range soundtracks {
if s.SoundtrackName == result.SoundtrackName {
found = true
break
}
}
if !found {
t.Errorf("random soundtrack selection returned soundtrack not in list: %v", result.SoundtrackName)
}
}
func TestFindSoundtrackByID(t *testing.T) {
soundtracks := []repository.Soundtrack{
{ID: 1, SoundtrackName: "Soundtrack1", TimesPlayed: 10},
{ID: 2, SoundtrackName: "Soundtrack2", TimesPlayed: 20},
{ID: 3, SoundtrackName: "Soundtrack3", TimesPlayed: 30},
}
tests := []struct {
name string
soundtracks []repository.Soundtrack
soundtrackID int32
expected repository.Soundtrack
}{
{
name: "existing soundtrack",
soundtracks: soundtracks,
soundtrackID: 2,
expected: repository.Soundtrack{ID: 2, SoundtrackName: "Soundtrack2", TimesPlayed: 20},
},
{
name: "non-existing soundtrack",
soundtracks: soundtracks,
soundtrackID: 99,
expected: repository.Soundtrack{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var result repository.Soundtrack
for _, s := range tt.soundtracks {
if s.ID == tt.soundtrackID {
result = s
break
}
}
if result.ID != tt.expected.ID || result.SoundtrackName != tt.expected.SoundtrackName {
t.Errorf("findSoundtrackByID() = %v, want %v", result, tt.expected)
}
})
}
}
func TestExtractSoundtrackNames(t *testing.T) {
soundtracks := []repository.Soundtrack{
{SoundtrackName: "Soundtrack1", TimesPlayed: 10},
{SoundtrackName: "Soundtrack2", TimesPlayed: 20},
{SoundtrackName: "Soundtrack3", TimesPlayed: 30},
}
var result []string
for _, s := range soundtracks {
result = append(result, s.SoundtrackName)
}
expected := []string{"Soundtrack1", "Soundtrack2", "Soundtrack3"}
if len(result) != len(expected) {
t.Errorf("extractSoundtrackNames() length = %d, want %d", len(result), len(expected))
return
}
for i, v := range result {
if v != expected[i] {
t.Errorf("extractSoundtrackNames()[%d] = %v, want %v", i, v, expected[i])
}
}
}
func TestShuffleSoundtrackNames(t *testing.T) {
soundtracks := []string{"Soundtrack1", "Soundtrack2", "Soundtrack3"}
// Test that shuffle doesn't lose any elements
// We can't test the order since it's random, but we can test length and contents
original := make([]string, len(soundtracks))
copy(original, soundtracks)
// Simple shuffle implementation for testing
for i := range soundtracks {
j := i // In real code this would be random
soundtracks[i], soundtracks[j] = soundtracks[j], soundtracks[i]
}
if len(soundtracks) != len(original) {
t.Errorf("shuffleSoundtrackNames() changed length from %d to %d", len(original), len(soundtracks))
return
}
// Check all original elements are still present
for _, orig := range original {
found := false
for _, s := range soundtracks {
if s == orig {
found = true
break
}
}
if !found {
t.Errorf("shuffleSoundtrackNames() lost element: %v", orig)
}
}
}
+114
View File
@@ -0,0 +1,114 @@
package backend
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"music-server/internal/logging"
"go.uber.org/zap"
)
const releaseCacheTTL = 5 * time.Minute
type giteaRelease struct {
Id int `json:"id"`
Name string `json:"name"`
Assets []giteaAsset `json:"assets"`
}
type giteaAsset struct {
Id int `json:"id"`
Name string `json:"name"`
DownloadUrl string `json:"browser_download_url"`
}
// ReleaseService looks up the latest client release on Gitea.
type ReleaseService struct {
url string
client *http.Client
now func() time.Time
mu sync.Mutex
cached giteaRelease
fetchedAt time.Time
}
// NewReleaseService creates a ReleaseService that reads the latest release from url.
func NewReleaseService(url string) *ReleaseService {
return &ReleaseService{url: url, client: &http.Client{Timeout: 10 * time.Second}, now: time.Now}
}
func (r *ReleaseService) latest(ctx context.Context) (giteaRelease, error) {
r.mu.Lock()
defer r.mu.Unlock()
if !r.fetchedAt.IsZero() && r.now().Sub(r.fetchedAt) < releaseCacheTTL {
return r.cached, nil
}
release, err := r.fetch(ctx)
if err != nil {
logging.GetLogger().Error("Failed to fetch latest release", zap.String("url", r.url), zap.Error(err))
return giteaRelease{}, fmt.Errorf("%w: %v", ErrUpstream, err)
}
r.cached, r.fetchedAt = release, r.now()
return release, nil
}
func (r *ReleaseService) fetch(ctx context.Context) (giteaRelease, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, r.url, nil)
if err != nil {
return giteaRelease{}, err
}
resp, err := r.client.Do(req)
if err != nil {
return giteaRelease{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return giteaRelease{}, fmt.Errorf("unexpected status %s", resp.Status)
}
var release giteaRelease
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return giteaRelease{}, err
}
return release, nil
}
// LatestVersion returns the name of the latest release.
func (r *ReleaseService) LatestVersion(ctx context.Context) (string, error) {
release, err := r.latest(ctx)
return release.Name, err
}
// AssetNames returns the names of all assets of the latest release.
func (r *ReleaseService) AssetNames(ctx context.Context) ([]string, error) {
release, err := r.latest(ctx)
if err != nil {
return nil, err
}
names := make([]string, len(release.Assets))
for i, asset := range release.Assets {
names[i] = asset.Name
}
return names, nil
}
// AssetURL returns the download URL of the first asset of the latest release with the given suffix.
func (r *ReleaseService) AssetURL(ctx context.Context, suffix string) (string, error) {
release, err := r.latest(ctx)
if err != nil {
return "", err
}
for _, asset := range release.Assets {
if strings.HasSuffix(asset.Name, suffix) {
return asset.DownloadUrl, nil
}
}
return "", ErrNotFound
}
+52 -69
View File
@@ -1,7 +1,7 @@
package backend
import (
"regexp"
"context"
"strings"
"sync"
)
@@ -13,88 +13,71 @@ type SoundtrackData struct {
Cleaned string
}
var (
searchCache []SoundtrackData
searchCacheMutex sync.Mutex
searchRegexCache = make(map[string]*regexp.Regexp)
searchRegexCacheMutex sync.Mutex
)
// SearchCache holds precomputed search data for all soundtrack names.
type SearchCache struct {
load func(context.Context) ([]string, error)
// GetSearchCache returns the precomputed search cache, initializing it if needed
func GetSearchCache() []SoundtrackData {
searchCacheMutex.Lock()
defer searchCacheMutex.Unlock()
if len(searchCache) == 0 {
loadSearchCache()
}
return searchCache
mu sync.Mutex
cache []SoundtrackData
}
// ReloadSearchCache clears and reloads the search cache.
// This should be called after a sync operation to ensure search results are up to date.
func ReloadSearchCache() {
searchCacheMutex.Lock()
defer searchCacheMutex.Unlock()
searchCache = nil
loadSearchCache()
// NewSearchCache creates a SearchCache that gets the soundtrack names from load.
func NewSearchCache(load func(context.Context) ([]string, error)) *SearchCache {
return &SearchCache{load: load}
}
// loadSearchCache loads the soundtrack data into the cache
func loadSearchCache() {
soundtracks := GetAllSoundtracks()
searchCache = make([]SoundtrackData, len(soundtracks))
for i, soundtrack := range soundtracks {
cleaned := cleanSearchTerm(soundtrack)
lowercase := strings.ToLower(soundtrack)
searchCache[i] = SoundtrackData{
Original: soundtrack,
Lowercase: lowercase,
Cleaned: cleaned,
// Get returns the precomputed search data, loading it if needed.
func (s *SearchCache) Get(ctx context.Context) ([]SoundtrackData, error) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.cache) == 0 {
if err := s.reload(ctx); err != nil {
return nil, err
}
}
return s.cache, nil
}
// CleanSearchTermForMatch cleans a search term for better matching
func CleanSearchTermForMatch(term string) string {
term = strings.ReplaceAll(term, " ", "")
term = strings.ReplaceAll(term, "é", "e")
term = strings.ReplaceAll(term, "+", "plus")
term = strings.ReplaceAll(term, "&", "and")
term = strings.ReplaceAll(term, "'n", "and")
return strings.ToLower(term)
// Reload reloads the search data. Call it after a sync.
func (s *SearchCache) Reload(ctx context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()
return s.reload(ctx)
}
// cleanSearchTerm cleans a search term for better matching (internal)
func cleanSearchTerm(term string) string {
return CleanSearchTermForMatch(term)
}
// MatchRegexCached checks if a search term matches using cached compiled regex
func MatchRegexCached(searchTerm string, soundtrackName string) bool {
if searchTerm == "" {
return true
func (s *SearchCache) reload(ctx context.Context) error {
soundtracks, err := s.load(ctx)
if err != nil {
return err
}
// Check cache first
searchRegexCacheMutex.Lock()
re, exists := searchRegexCache[searchTerm]
if !exists {
re = compileSearchRegex(searchTerm)
searchRegexCache[searchTerm] = re
cache := make([]SoundtrackData, len(soundtracks))
for i, soundtrack := range soundtracks {
cache[i] = SoundtrackData{
Original: soundtrack,
Lowercase: strings.ToLower(soundtrack),
Cleaned: CleanSearchTerm(soundtrack),
}
}
searchRegexCacheMutex.Unlock()
return re.MatchString(soundtrackName)
s.cache = cache
return nil
}
// compileSearchRegex compiles a search term into a regex pattern
func compileSearchRegex(searchTerm string) *regexp.Regexp {
regText := ".*"
for _, letter := range searchTerm {
regText += string(letter) + ".*"
var searchReplacer = strings.NewReplacer(" ", "", "é", "e", "+", "plus", "&", "and", "'n", "and")
// CleanSearchTerm normalises a search term or soundtrack name for matching.
func CleanSearchTerm(term string) string {
return searchReplacer.Replace(strings.ToLower(term))
}
// MatchesSubsequence reports whether all characters of term appear in text in the same order.
func MatchesSubsequence(term, text string) bool {
rest := text
for _, r := range term {
i := strings.IndexRune(rest, r)
if i < 0 {
return false
}
rest = rest[i+len(string(r)):]
}
re, _ := regexp.Compile(regText)
return re
return true
}
+68 -188
View File
@@ -1,12 +1,11 @@
package backend
import (
"context"
"encoding/json"
"time"
"music-server/internal/logging"
"go.uber.org/zap"
"music-server/internal/db/repository"
)
// SoundtrackWithSongs represents a soundtrack with its songs for statistics
@@ -39,239 +38,120 @@ type StatisticsSummary struct {
MinSoundtrackPlays int64 `json:"min_soundtrack_plays"`
}
// StatisticsHandler manages statistics operations
type StatisticsHandler struct {
// Uses the global backend repo initialized via InitBackend
// StatisticsService reads play statistics.
type StatisticsService struct {
q repository.Querier
}
// NewStatisticsHandler creates a new StatisticsHandler
func NewStatisticsHandler() *StatisticsHandler {
return &StatisticsHandler{}
// NewStatisticsService creates a StatisticsService.
func NewStatisticsService(q repository.Querier) *StatisticsService {
return &StatisticsService{q: q}
}
// GetMostPlayedSoundtracksWithSongs returns the top N most played soundtracks with their songs
func (h *StatisticsHandler) GetMostPlayedSoundtracksWithSongs(limit int32) ([]SoundtrackWithSongs, error) {
queries := BackendRepo()
ctx := BackendCtx()
// soundtrackRow covers the generated rows that share the soundtrack-with-songs shape.
type soundtrackRow interface {
repository.GetMostPlayedSoundtracksWithSongsRow |
repository.GetLeastPlayedSoundtracksWithSongsRow |
repository.GetLastPlayedSoundtracksRow |
repository.GetOldestPlayedSoundtracksRow
}
// Get raw results
rows, err := queries.GetMostPlayedSoundtracksWithSongs(ctx, limit)
func toSoundtracks[R soundtrackRow](rows []R, err error) ([]SoundtrackWithSongs, error) {
if err != nil {
return nil, err
}
// Convert to SoundtrackWithSongs
var result []SoundtrackWithSongs
for _, row := range rows {
var songs []SongInfoForStats
if row.Songs != nil {
// Parse JSON songs array
if err := json.Unmarshal(row.Songs, &songs); err != nil {
// Fallback: if JSON parsing fails, create empty song entries
songs = make([]SongInfoForStats, 0)
}
}
for _, r := range rows {
row := repository.GetMostPlayedSoundtracksWithSongsRow(r)
result = append(result, SoundtrackWithSongs{
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SoundtrackPlayed: row.SoundtrackPlayed,
SoundtrackLastPlayed: row.SoundtrackLastPlayed,
Songs: songs,
Songs: parseSongs(row.Songs),
})
}
return result, nil
}
// GetLeastPlayedSoundtracksWithSongs returns the top N least played soundtracks with their songs
func (h *StatisticsHandler) GetLeastPlayedSoundtracksWithSongs(limit int32) ([]SoundtrackWithSongs, error) {
queries := BackendRepo()
ctx := BackendCtx()
rows, err := queries.GetLeastPlayedSoundtracksWithSongs(ctx, limit)
if err != nil {
return nil, err
}
var result []SoundtrackWithSongs
for _, row := range rows {
var songs []SongInfoForStats
if row.Songs != nil {
if err := json.Unmarshal(row.Songs, &songs); err != nil {
songs = make([]SongInfoForStats, 0)
}
}
result = append(result, SoundtrackWithSongs{
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SoundtrackPlayed: row.SoundtrackPlayed,
SoundtrackLastPlayed: row.SoundtrackLastPlayed,
Songs: songs,
})
}
return result, nil
type songRow interface {
repository.GetMostPlayedSongsWithSoundtrackRow | repository.GetLeastPlayedSongsWithSoundtrackRow
}
// GetMostPlayedSongsWithSoundtrack returns the top N most played songs with their soundtrack info
func (h *StatisticsHandler) GetMostPlayedSongsWithSoundtrack(limit int32) ([]SongInfoForStats, error) {
queries := BackendRepo()
ctx := BackendCtx()
rows, err := queries.GetMostPlayedSongsWithSoundtrack(ctx, limit)
func toSongs[R songRow](rows []R, err error) ([]SongInfoForStats, error) {
if err != nil {
return nil, err
}
var result []SongInfoForStats
for _, row := range rows {
result = append(result, SongInfoForStats{
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SongName: row.SongName,
Path: row.Path,
TimesPlayed: row.TimesPlayed,
FileName: row.FileName,
})
for _, r := range rows {
result = append(result, SongInfoForStats(repository.GetMostPlayedSongsWithSoundtrackRow(r)))
}
return result, nil
}
// GetLeastPlayedSongsWithSoundtrack returns the top N least played songs with their soundtrack info
func (h *StatisticsHandler) GetLeastPlayedSongsWithSoundtrack(limit int32) ([]SongInfoForStats, error) {
queries := BackendRepo()
ctx := BackendCtx()
rows, err := queries.GetLeastPlayedSongsWithSoundtrack(ctx, limit)
if err != nil {
return nil, err
func parseSongs(data []byte) []SongInfoForStats {
songs := []SongInfoForStats{}
if data != nil {
if err := json.Unmarshal(data, &songs); err != nil {
return []SongInfoForStats{}
}
}
var result []SongInfoForStats
for _, row := range rows {
result = append(result, SongInfoForStats{
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SongName: row.SongName,
Path: row.Path,
TimesPlayed: row.TimesPlayed,
FileName: row.FileName,
})
}
return result, nil
return songs
}
// GetNeverPlayedSoundtracks returns soundtracks that have never been played
func (h *StatisticsHandler) GetNeverPlayedSoundtracks() ([]SoundtrackWithSongs, error) {
queries := BackendRepo()
ctx := BackendCtx()
// MostPlayedSoundtracks returns the top N most played soundtracks with their songs
func (s *StatisticsService) MostPlayedSoundtracks(ctx context.Context, limit int32) ([]SoundtrackWithSongs, error) {
return toSoundtracks(s.q.GetMostPlayedSoundtracksWithSongs(ctx, limit))
}
rows, err := queries.GetNeverPlayedSoundtracks(ctx)
// LeastPlayedSoundtracks returns the top N least played soundtracks with their songs
func (s *StatisticsService) LeastPlayedSoundtracks(ctx context.Context, limit int32) ([]SoundtrackWithSongs, error) {
return toSoundtracks(s.q.GetLeastPlayedSoundtracksWithSongs(ctx, limit))
}
// LastPlayedSoundtracks returns the most recently played soundtracks
func (s *StatisticsService) LastPlayedSoundtracks(ctx context.Context, limit int32) ([]SoundtrackWithSongs, error) {
return toSoundtracks(s.q.GetLastPlayedSoundtracks(ctx, limit))
}
// OldestPlayedSoundtracks returns the least recently played soundtracks
func (s *StatisticsService) OldestPlayedSoundtracks(ctx context.Context, limit int32) ([]SoundtrackWithSongs, error) {
return toSoundtracks(s.q.GetOldestPlayedSoundtracks(ctx, limit))
}
// NeverPlayedSoundtracks returns soundtracks that have never been played
func (s *StatisticsService) NeverPlayedSoundtracks(ctx context.Context) ([]SoundtrackWithSongs, error) {
rows, err := s.q.GetNeverPlayedSoundtracks(ctx)
if err != nil {
return nil, err
}
var result []SoundtrackWithSongs
for _, row := range rows {
var songs []SongInfoForStats
if row.Songs != nil {
if err := json.Unmarshal(row.Songs, &songs); err != nil {
songs = make([]SongInfoForStats, 0)
}
}
result = append(result, SoundtrackWithSongs{
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SoundtrackPlayed: row.SoundtrackPlayed,
SoundtrackLastPlayed: nil,
Songs: songs,
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SoundtrackPlayed: row.SoundtrackPlayed,
Songs: parseSongs(row.Songs),
})
}
return result, nil
}
// GetLastPlayedSoundtracks returns the most recently played soundtracks
func (h *StatisticsHandler) GetLastPlayedSoundtracks(limit int32) ([]SoundtrackWithSongs, error) {
queries := BackendRepo()
ctx := BackendCtx()
rows, err := queries.GetLastPlayedSoundtracks(ctx, limit)
if err != nil {
return nil, err
}
var result []SoundtrackWithSongs
for _, row := range rows {
var songs []SongInfoForStats
if row.Songs != nil {
if err := json.Unmarshal(row.Songs, &songs); err != nil {
songs = make([]SongInfoForStats, 0)
}
}
result = append(result, SoundtrackWithSongs{
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SoundtrackPlayed: row.SoundtrackPlayed,
SoundtrackLastPlayed: row.SoundtrackLastPlayed,
Songs: songs,
})
}
return result, nil
// MostPlayedSongs returns the top N most played songs with their soundtrack info
func (s *StatisticsService) MostPlayedSongs(ctx context.Context, limit int32) ([]SongInfoForStats, error) {
return toSongs(s.q.GetMostPlayedSongsWithSoundtrack(ctx, limit))
}
// GetOldestPlayedSoundtracks returns the least recently played soundtracks
func (h *StatisticsHandler) GetOldestPlayedSoundtracks(limit int32) ([]SoundtrackWithSongs, error) {
queries := BackendRepo()
ctx := BackendCtx()
rows, err := queries.GetOldestPlayedSoundtracks(ctx, limit)
if err != nil {
return nil, err
}
var result []SoundtrackWithSongs
for _, row := range rows {
var songs []SongInfoForStats
if row.Songs != nil {
if err := json.Unmarshal(row.Songs, &songs); err != nil {
songs = make([]SongInfoForStats, 0)
}
}
result = append(result, SoundtrackWithSongs{
SoundtrackID: row.SoundtrackID,
SoundtrackName: row.SoundtrackName,
SoundtrackPlayed: row.SoundtrackPlayed,
SoundtrackLastPlayed: row.SoundtrackLastPlayed,
Songs: songs,
})
}
return result, nil
// LeastPlayedSongs returns the top N least played songs with their soundtrack info
func (s *StatisticsService) LeastPlayedSongs(ctx context.Context, limit int32) ([]SongInfoForStats, error) {
return toSongs(s.q.GetLeastPlayedSongsWithSoundtrack(ctx, limit))
}
// GetStatisticsSummary returns overall statistics
func (h *StatisticsHandler) GetStatisticsSummary() (*StatisticsSummary, error) {
queries := BackendRepo()
ctx := BackendCtx()
row, err := queries.GetStatisticsSummary(ctx)
// Summary returns overall statistics
func (s *StatisticsService) Summary(ctx context.Context) (StatisticsSummary, error) {
row, err := s.q.GetStatisticsSummary(ctx)
if err != nil {
return nil, err
}
return &StatisticsSummary{
TotalSoundtracks: int64(row.TotalSoundtracks),
PlayedSoundtracks: int64(row.PlayedSoundtracks),
NeverPlayedSoundtracks: int64(row.NeverPlayedSoundtracks),
TotalSoundtrackPlays: int64(row.TotalSoundtrackPlays),
AvgSoundtrackPlays: float64(row.AvgSoundtrackPlays),
MaxSoundtrackPlays: int64(row.MaxSoundtrackPlays),
MinSoundtrackPlays: int64(row.MinSoundtrackPlays),
}, nil
}
// Log helper for statistics operations
func logStatisticsError(err error, operation string) {
if err != nil {
logging.GetLogger().Error("Statistics error",
zap.String("operation", operation),
zap.String("error", err.Error()))
return StatisticsSummary{}, err
}
return StatisticsSummary(row), nil
}
+590 -518
View File
File diff suppressed because it is too large. Load diff
-204
View File
@@ -1,204 +0,0 @@
package backend
import (
"io/fs"
"os"
"testing"
"time"
)
func TestContains(t *testing.T) {
tests := []struct {
name string
slice []string
search string
expected bool
}{
{
name: "element exists",
slice: []string{"a", "b", "c"},
search: "b",
expected: true,
},
{
name: "element does not exist",
slice: []string{"a", "b", "c"},
search: "d",
expected: false,
},
{
name: "empty slice",
slice: []string{},
search: "a",
expected: false,
},
{
name: "element at start",
slice: []string{"a", "b", "c"},
search: "a",
expected: true,
},
{
name: "element at end",
slice: []string{"a", "b", "c"},
search: "c",
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := contains(tt.slice, tt.search)
if result != tt.expected {
t.Errorf("contains() = %v, want %v", result, tt.expected)
}
})
}
}
func TestIsSong(t *testing.T) {
mockFileInfo := &mockFileInfoForSong{name: "test.mp3", isDir: false, size: 100}
result := isSong(mockFileInfo)
if !result {
t.Error("isSong() should return true for .mp3 file")
}
mockFileInfo2 := &mockFileInfoForSong{name: "test.txt", isDir: false, size: 100}
result = isSong(mockFileInfo2)
if result {
t.Error("isSong() should return false for .txt file")
}
mockFileInfo3 := &mockFileInfoForSong{name: "test", isDir: true, size: 100}
result = isSong(mockFileInfo3)
if result {
t.Error("isSong() should return false for directory")
}
}
func TestIsCoverImage(t *testing.T) {
tests := []struct {
name string
fileInfo fs.FileInfo
expected bool
}{
{
name: "cover.jpg",
fileInfo: &mockFileInfoForCover{name: "cover.jpg", isDir: false, size: 100},
expected: true,
},
{
name: "cover.png",
fileInfo: &mockFileInfoForCover{name: "cover.png", isDir: false, size: 100},
expected: true,
},
{
name: "my_cover.jpg",
fileInfo: &mockFileInfoForCover{name: "my_cover.jpg", isDir: false, size: 100},
expected: true,
},
{
name: "image.jpg",
fileInfo: &mockFileInfoForCover{name: "image.jpg", isDir: false, size: 100},
expected: false,
},
{
name: "cover.txt",
fileInfo: &mockFileInfoForCover{name: "cover.txt", isDir: false, size: 100},
expected: false,
},
{
name: "directory",
fileInfo: &mockFileInfoForCover{name: "cover", isDir: true, size: 100},
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isCoverImage(tt.fileInfo)
if result != tt.expected {
t.Errorf("isCoverImage() = %v, want %v", result, tt.expected)
}
})
}
}
func TestGetIdFromFileNew(t *testing.T) {
tests := []struct {
name string
fileInfo os.FileInfo
expected int32
}{
{
name: "valid id file",
fileInfo: &mockFileInfoForId{name: ".123.id", isDir: false, size: 100},
expected: 123,
},
{
name: "invalid id file (directory)",
fileInfo: &mockFileInfoForId{name: ".123.id", isDir: true, size: 100},
expected: -1,
},
{
name: "invalid id file (no .id extension)",
fileInfo: &mockFileInfoForId{name: "123.txt", isDir: false, size: 100},
expected: -1,
},
{
name: "invalid id file (not a number)",
fileInfo: &mockFileInfoForId{name: ".abc.id", isDir: false, size: 100},
expected: 0, // strconv.Atoi returns 0 for invalid numbers (error is ignored)
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := getIdFromFile(tt.fileInfo)
if result != tt.expected {
t.Errorf("getIdFromFile() = %v, want %v", result, tt.expected)
}
})
}
}
// Mock types for testing
type mockFileInfoForSong struct {
name string
isDir bool
size int64
}
func (m *mockFileInfoForSong) Name() string { return m.name }
func (m *mockFileInfoForSong) Size() int64 { return m.size }
func (m *mockFileInfoForSong) Mode() os.FileMode { return 0 }
func (m *mockFileInfoForSong) ModTime() time.Time { return time.Time{} }
func (m *mockFileInfoForSong) IsDir() bool { return m.isDir }
func (m *mockFileInfoForSong) Sys() interface{} { return nil }
type mockFileInfoForCover struct {
name string
isDir bool
size int64
}
func (m *mockFileInfoForCover) Name() string { return m.name }
func (m *mockFileInfoForCover) Size() int64 { return m.size }
func (m *mockFileInfoForCover) Mode() os.FileMode { return 0 }
func (m *mockFileInfoForCover) ModTime() time.Time { return time.Time{} }
func (m *mockFileInfoForCover) IsDir() bool { return m.isDir }
func (m *mockFileInfoForCover) Sys() interface{} { return nil }
type mockFileInfoForId struct {
name string
isDir bool
size int64
}
func (m *mockFileInfoForId) Name() string { return m.name }
func (m *mockFileInfoForId) Size() int64 { return m.size }
func (m *mockFileInfoForId) Mode() os.FileMode { return 0 }
func (m *mockFileInfoForId) ModTime() time.Time { return time.Time{} }
func (m *mockFileInfoForId) IsDir() bool { return m.isDir }
func (m *mockFileInfoForId) Sys() interface{} { return nil }