quintodrome/engine/scrobbler.go

62 lines
1.6 KiB
Go
Raw Normal View History

package engine
import (
2020-01-08 16:45:07 -09:00
"context"
"errors"
"fmt"
"time"
2020-01-23 15:44:08 -09:00
"github.com/deluan/navidrome/model"
)
type Scrobbler interface {
2020-01-14 18:22:34 -09:00
Register(ctx context.Context, playerId int, trackId string, playDate time.Time) (*model.MediaFile, error)
NowPlaying(ctx context.Context, playerId int, playerName, trackId, username string) (*model.MediaFile, error)
}
func NewScrobbler(ds model.DataStore, npr NowPlayingRepository) Scrobbler {
return &scrobbler{ds: ds, npRepo: npr}
}
type scrobbler struct {
ds model.DataStore
npRepo NowPlayingRepository
}
2020-01-14 18:22:34 -09:00
func (s *scrobbler) Register(ctx context.Context, playerId int, trackId string, playTime time.Time) (*model.MediaFile, error) {
2020-01-20 11:51:33 -09:00
var mf *model.MediaFile
var err error
err = s.ds.WithTx(func(tx model.DataStore) error {
mf, err = s.ds.MediaFile(ctx).Get(trackId)
2020-01-20 11:51:33 -09:00
if err != nil {
return err
}
2020-01-31 17:09:23 -09:00
err = s.ds.MediaFile(ctx).IncPlayCount(trackId, playTime)
2020-01-20 11:51:33 -09:00
if err != nil {
return err
}
2020-01-31 17:09:23 -09:00
err = s.ds.Album(ctx).IncPlayCount(mf.AlbumID, playTime)
if err != nil {
return err
}
err = s.ds.Artist(ctx).IncPlayCount(mf.ArtistID, playTime)
2020-01-20 11:51:33 -09:00
return err
})
return mf, err
}
2016-03-16 16:51:03 -08:00
2020-01-20 11:51:33 -09:00
// TODO Validate if NowPlaying still works after all refactorings
2020-01-14 18:22:34 -09:00
func (s *scrobbler) NowPlaying(ctx context.Context, playerId int, playerName, trackId, username string) (*model.MediaFile, error) {
mf, err := s.ds.MediaFile(ctx).Get(trackId)
2016-03-16 17:04:41 -08:00
if err != nil {
return nil, err
}
if mf == nil {
return nil, errors.New(fmt.Sprintf(`ID "%s" not found`, trackId))
2016-03-16 17:04:41 -08:00
}
info := &NowPlayingInfo{TrackID: trackId, Username: username, Start: time.Now(), PlayerId: playerId, PlayerName: playerName}
return mf, s.npRepo.Enqueue(info)
2016-03-16 16:51:03 -08:00
}