package opensubsonic import ( "context" "errors" "strconv" "strings" "time" "git.kmalloc.org/squid/sonda/internal/catalog" "git.kmalloc.org/squid/sonda/internal/listening" "git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/usersettings" ) const playlistPrefix = "pl-" func playlistID(id int64) string { return playlistPrefix + strconv.FormatInt(id, 10) } // Playlists keeps the playlists of a person: *playlists.Service. type Playlists interface { Create(ctx context.Context, userID int64, name, description string) (playlists.Playlist, error) List(ctx context.Context, userID int64, p playlists.Page) (playlists.Listing, error) Get(ctx context.Context, userID, id int64) (playlists.Playlist, error) Update(ctx context.Context, userID, id int64, name, description *string) (playlists.Playlist, error) Delete(ctx context.Context, userID, id int64) error Items(ctx context.Context, userID, id int64, p playlists.Page) (playlists.ItemsListing, error) AddTracks(ctx context.Context, userID, id int64, trackIDs []int64, position *int) (playlists.Playlist, error) RemoveItem(ctx context.Context, userID, id, itemID int64) error } // Radio makes the stations of the radio: *mixes.Service. An app has no way to play a radio that never ends, so each // station is shown as a playlist with other songs every time it is opened. type Radio interface { Radios(ctx context.Context, userID int64) ([]mixes.Mix, error) Radio(ctx context.Context, userID int64, id string) (mixes.Mix, []catalog.Track, error) } const radioPrefix = "rd-" // radioName is how a station is called in a list of playlists: "Radio · Rock". func radioName(m mixes.Mix) string { return "Radio · " + strings.TrimSuffix(m.Title, " Mix") } // radioPlaylist describes a station as a playlist. It has as many songs as one round of the radio. func radioPlaylist(m mixes.Mix, owner string, now time.Time) Playlist { p := Playlist{ ID: radioPrefix + m.ID, Name: radioName(m), Comment: "Other songs every time", Owner: owner, SongCount: mixes.Size, Created: stamp(now), Changed: stamp(now), } if len(m.AlbumIDs) > 0 { p.CoverArt = albumID(m.AlbumIDs[0]) } return p } // Settings are the choices of a person: *usersettings.Service. type Settings interface { Get(ctx context.Context, userID int64) (usersettings.Settings, error) } // radioShown says whether the stations of the radio are in the list of playlists of this person's apps: only when // there is a radio and the person asked for it (there are two dozen of them). func (h *handler) radioShown(k *call) (bool, error) { if h.Radio == nil || h.Settings == nil { return false, nil } s, err := h.Settings.Get(k.ctx, k.principal.UserID) return s.RadioInApps, err } // Listens records what a person listened to: *listening.Service. type Listens interface { Record(ctx context.Context, e listening.Event) (listening.Result, error) } // Announcer is told of every listen that counts, to share it where the person asked for it (Mastodon). type Announcer interface { Announce(userID, trackID int64) } func playlistFailure(err error) *Error { switch { case errors.Is(err, playlists.ErrNotFound), errors.Is(err, playlists.ErrTrackNotFound), errors.Is(err, playlists.ErrItemNotFound): return notFound() case errors.Is(err, playlists.ErrInvalidInput), errors.Is(err, playlists.ErrPosition), errors.Is(err, playlists.ErrTooMany): return &Error{Code: ErrGeneric, Message: err.Error()} } return &Error{Code: ErrGeneric, Message: "the playlist could not be changed"} } func playlistOf(p playlists.Playlist, owner string) Playlist { out := Playlist{ ID: playlistID(p.ID), Name: p.Name, Comment: p.Description, Owner: owner, SongCount: p.TrackCount, Duration: seconds(p.DurationMs), Created: stamp(p.CreatedAt), Changed: stamp(p.UpdatedAt), } if len(p.AlbumIDs) > 0 { out.CoverArt = albumID(p.AlbumIDs[0]) } return out } func (h *handler) playlists(k *call) (*Response, *Error) { var all []playlists.Playlist for { p, err := h.Playlists.List(k.ctx, k.principal.UserID, playlists.Page{Limit: playlists.MaxLimit, Offset: len(all)}) if err != nil { return nil, playlistFailure(err) } all = append(all, p.Items...) if len(p.Items) == 0 || len(all) >= p.Total { break } } out := make([]Playlist, len(all)) for i, p := range all { out[i] = playlistOf(p, k.principal.Email) } shown, err := h.radioShown(k) if err != nil { return nil, failure(err) } if shown { stations, err := h.Radio.Radios(k.ctx, k.principal.UserID) if err != nil { return nil, failure(err) } now := time.Now() for _, m := range stations { out = append(out, radioPlaylist(m, k.principal.Email, now)) } } return &Response{Playlists: &PlaylistList{Playlist: out}}, nil } // entries are the songs of a playlist that can be played, in order, with the id of the item that holds each. func (h *handler) entries(k *call, id int64) ([]playlists.Item, *Error) { var all []playlists.Item for { p, err := h.Playlists.Items(k.ctx, k.principal.UserID, id, playlists.Page{Limit: playlists.MaxLimit, Offset: len(all)}) if err != nil { return nil, playlistFailure(err) } all = append(all, p.Items...) if len(p.Items) == 0 || len(all) >= p.Total { break } } playable := all[:0] for _, it := range all { if it.Available { playable = append(playable, it) } } return playable, nil } // opened is the playlist with its songs. func (h *handler) opened(k *call, id int64) (*Response, *Error) { p, err := h.Playlists.Get(k.ctx, k.principal.UserID, id) if err != nil { return nil, playlistFailure(err) } items, bad := h.entries(k, id) if bad != nil { return nil, bad } tracks := make([]catalog.Track, len(items)) for i, it := range items { tracks[i] = it.Track } songs, err := h.songs(k, tracks) if err != nil { return nil, failure(err) } out := playlistOf(p, k.principal.Email) out.Entry = songs return &Response{Playlist: &out}, nil } func (h *handler) playlist(k *call) (*Response, *Error) { if station, ok := strings.CutPrefix(k.param("id"), radioPrefix); ok { shown, err := h.radioShown(k) if err != nil { return nil, failure(err) } if !shown { return nil, notFound() } return h.station(k, station) } id, bad := idParam(k, playlistPrefix) if bad != nil { return nil, bad } return h.opened(k, id) } // songIDs reads a parameter that may be given many times, each a song. func songIDs(k *call, name string) ([]int64, *Error) { var out []int64 for _, raw := range k.c.Request.Form[name] { n, err := strconv.ParseInt(strings.TrimPrefix(raw, trackPrefix), 10, 64) if !strings.HasPrefix(raw, trackPrefix) || err != nil || n < 1 { return nil, notFound() } out = append(out, n) } return out, nil } // add puts songs at the end of a playlist, as many as the service takes at once. func (h *handler) add(k *call, id int64, songs []int64) *Error { for len(songs) > 0 { chunk := songs[:min(len(songs), playlists.MaxAddAtOnce)] songs = songs[len(chunk):] if _, err := h.Playlists.AddTracks(k.ctx, k.principal.UserID, id, chunk, nil); err != nil { return playlistFailure(err) } } return nil } // createPlaylist makes a playlist with songs, or, given the id of one, puts these songs in its place. func (h *handler) createPlaylist(k *call) (*Response, *Error) { name, rawID := k.param("name"), k.param("playlistId") if name == "" && rawID == "" { return nil, missing("name or playlistId") } songs, bad := songIDs(k, "songId") if bad != nil { return nil, bad } var id int64 if rawID != "" { n, bad := idOf(rawID, playlistPrefix) if bad != nil { return nil, bad } id = n if _, err := h.Playlists.Get(k.ctx, k.principal.UserID, id); err != nil { return nil, playlistFailure(err) } items, bad := h.allItems(k, id) if bad != nil { return nil, bad } for _, it := range items { if err := h.Playlists.RemoveItem(k.ctx, k.principal.UserID, id, it.ID); err != nil { return nil, playlistFailure(err) } } if name != "" { if _, err := h.Playlists.Update(k.ctx, k.principal.UserID, id, &name, nil); err != nil { return nil, playlistFailure(err) } } } else { p, err := h.Playlists.Create(k.ctx, k.principal.UserID, name, "") if err != nil { return nil, playlistFailure(err) } id = p.ID } if bad := h.add(k, id, songs); bad != nil { return nil, bad } return h.opened(k, id) } // allItems are every item of a playlist, the ones that cannot be played too. func (h *handler) allItems(k *call, id int64) ([]playlists.Item, *Error) { var all []playlists.Item for { p, err := h.Playlists.Items(k.ctx, k.principal.UserID, id, playlists.Page{Limit: playlists.MaxLimit, Offset: len(all)}) if err != nil { return nil, playlistFailure(err) } all = append(all, p.Items...) if len(p.Items) == 0 || len(all) >= p.Total { return all, nil } } } // updatePlaylist renames a playlist, changes its comment, takes songs out by their place in the list the app was // shown, and adds songs at the end. func (h *handler) updatePlaylist(k *call) (*Response, *Error) { raw := k.param("playlistId") if raw == "" { return nil, missing("playlistId") } id, bad := idOf(raw, playlistPrefix) if bad != nil { return nil, bad } if _, err := h.Playlists.Get(k.ctx, k.principal.UserID, id); err != nil { return nil, playlistFailure(err) } add, bad := songIDs(k, "songIdToAdd") if bad != nil { return nil, bad } var remove []int for _, v := range k.c.Request.Form["songIndexToRemove"] { n, err := strconv.Atoi(v) if err != nil || n < 0 { return nil, &Error{Code: ErrGeneric, Message: "invalid songIndexToRemove"} } remove = append(remove, n) } var name, comment *string if _, given := k.c.Request.Form["name"]; given { v := k.param("name") name = &v } if _, given := k.c.Request.Form["comment"]; given { v := k.param("comment") comment = &v } if name != nil || comment != nil { if _, err := h.Playlists.Update(k.ctx, k.principal.UserID, id, name, comment); err != nil { return nil, playlistFailure(err) } } if len(remove) > 0 { items, bad := h.entries(k, id) // the places are those of the list the app was shown if bad != nil { return nil, bad } gone := map[int64]bool{} for _, n := range remove { if n >= len(items) { return nil, &Error{Code: ErrGeneric, Message: "songIndexToRemove is past the end of the playlist"} } gone[items[n].ID] = true } for itemID := range gone { if err := h.Playlists.RemoveItem(k.ctx, k.principal.UserID, id, itemID); err != nil { return nil, playlistFailure(err) } } } if bad := h.add(k, id, add); bad != nil { return nil, bad } return &Response{}, nil } func (h *handler) deletePlaylist(k *call) (*Response, *Error) { id, bad := idParam(k, playlistPrefix) if bad != nil { return nil, bad } if err := h.Playlists.Delete(k.ctx, k.principal.UserID, id); err != nil { return nil, playlistFailure(err) } return &Response{}, nil } // nowPlaying is always empty: what a person plays is nobody else's business. func (h *handler) nowPlaying(*call) (*Response, *Error) { return &Response{NowPlaying: &NowPlaying{}}, nil } // scrobble records the songs an app says were listened to. With submission=false the app only says it started // one: nothing is recorded, because only a listen counts. A retry of the same listen is recorded once. func (h *handler) scrobble(k *call) (*Response, *Error) { rawIDs := k.c.Request.Form["id"] if len(rawIDs) == 0 { return nil, missing("id") } songs, bad := songIDs(k, "id") if bad != nil { return nil, bad } submission := true switch k.param("submission") { case "", "true": case "false": submission = false default: return nil, &Error{Code: ErrGeneric, Message: "submission must be true or false"} } var times []time.Time for _, v := range k.c.Request.Form["time"] { ms, err := strconv.ParseInt(v, 10, 64) if err != nil || ms < 0 { return nil, &Error{Code: ErrGeneric, Message: "invalid time"} } times = append(times, time.UnixMilli(ms)) } if !submission { return &Response{}, nil } for i, id := range songs { at := time.Now() if i < len(times) { at = times[i] } t, err := h.Catalog.Track(k.ctx, id) if err != nil { return nil, failure(err) } res, err := h.Listens.Record(k.ctx, listening.Event{ UserID: k.principal.UserID, TrackID: id, Type: listening.Complete, OccurredAt: at, DurationPlayedMs: t.DurationMs, IdempotencyKey: "subsonic-" + strconv.FormatInt(k.principal.DeviceID, 10) + "-" + strconv.FormatInt(id, 10) + "-" + strconv.FormatInt(at.UnixMilli(), 10), }) switch { case errors.Is(err, listening.ErrTrackNotFound): return nil, notFound() case errors.Is(err, listening.ErrInvalidEvent): return nil, &Error{Code: ErrGeneric, Message: err.Error()} case err != nil: return nil, &Error{Code: ErrGeneric, Message: "the listen could not be recorded"} } if res.Created && res.Counted && h.Announcer != nil { h.Announcer.Announce(k.principal.UserID, id) } } return &Response{}, nil } // station is a station of the radio opened as a playlist: other songs every time. func (h *handler) station(k *call, id string) (*Response, *Error) { m, tracks, err := h.Radio.Radio(k.ctx, k.principal.UserID, id) if errors.Is(err, mixes.ErrNotFound) { return nil, notFound() } if err != nil { return nil, failure(err) } songs, err := h.songs(k, tracks) if err != nil { return nil, failure(err) } p := radioPlaylist(m, k.principal.Email, time.Now()) p.Name = radioName(m) p.SongCount = len(songs) var ms int64 for _, t := range tracks { ms += t.DurationMs } p.Duration = seconds(ms) p.Entry = songs return &Response{Playlist: &p}, nil }