music-library/library.go

67 lines
1.4 KiB
Go
Raw Permalink Normal View History

2023-02-14 21:59:56 +01:00
package main
import (
"os"
"path/filepath"
2023-02-16 12:16:04 +01:00
"git.milar.in/milarin/adverr"
2023-02-14 21:59:56 +01:00
"git.milar.in/milarin/slices"
)
type Playlist struct {
2023-02-16 12:16:04 +01:00
Name string `json:"name"`
Songs []Song `json:"songs"`
2023-02-14 21:59:56 +01:00
}
2023-02-16 12:16:04 +01:00
type Song struct {
Name string `json:"name"`
File string `json:"file"`
}
func GetAllPlaylists() ([]Playlist, error) {
playlistNames, err := GetAllPlaylistNames()
2023-02-14 21:59:56 +01:00
if err != nil {
return nil, err
}
playlists := make([]Playlist, 0, len(playlistNames))
for _, playlistName := range playlistNames {
2023-02-16 12:16:04 +01:00
songs, err := GetSongsByPlaylist(playlistName)
2023-02-14 21:59:56 +01:00
if err != nil {
return nil, err
}
playlists = append(playlists, Playlist{
Name: playlistName,
Songs: songs,
})
}
return playlists, nil
}
2023-02-16 12:16:04 +01:00
func GetAllPlaylistNames() ([]string, error) {
2023-02-14 21:59:56 +01:00
entries, err := os.ReadDir(LibraryPath)
if err != nil {
return nil, err
}
directories := slices.Filter(entries, And(IsDir, Not(IsHidden)))
return slices.Map(directories, FsEntry2Name), nil
}
2023-02-16 12:16:04 +01:00
func GetSongsByPlaylist(playlist string) ([]Song, error) {
2023-02-14 21:59:56 +01:00
entries, err := os.ReadDir(filepath.Join(LibraryPath, playlist))
if err != nil {
return nil, err
}
2023-02-16 12:16:04 +01:00
symlinks := slices.Filter(entries, IsSymlink)
return slices.Map(symlinks, func(entry os.DirEntry) Song {
return Song{
Name: FsEntry2Name(entry),
File: filepath.Base(adverr.Must(os.Readlink(filepath.Join(LibraryPath, playlist, entry.Name())))),
}
}), nil
2023-02-14 21:59:56 +01:00
}