navidrome/engine/scrobbler.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

70 lines
1.9 KiB
Go
Raw Normal View History

package engine
import (
2020-01-08 20:45:07 -05:00
"context"
"fmt"
"time"
2020-04-06 19:42:35 -04:00
"github.com/deluan/navidrome/log"
2020-01-23 19:44:08 -05:00
"github.com/deluan/navidrome/model"
)
type Scrobbler interface {
2020-01-14 22:22:34 -05: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 22:22:34 -05:00
func (s *scrobbler) Register(ctx context.Context, playerId int, trackId string, playTime time.Time) (*model.MediaFile, error) {
2020-01-20 15:51:33 -05: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 15:51:33 -05:00
if err != nil {
return err
}
2020-01-31 21:09:23 -05:00
err = s.ds.MediaFile(ctx).IncPlayCount(trackId, playTime)
2020-01-20 15:51:33 -05:00
if err != nil {
return err
}
2020-01-31 21:09:23 -05: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 15:51:33 -05:00
return err
})
2020-04-06 19:42:35 -04:00
2020-05-25 10:54:07 -04:00
if err != nil {
log.Error("Error while scrobbling", "trackId", trackId, err)
} else {
log.Info("Scrobbled", "title", mf.Title, "artist", mf.Artist, "user", userName(ctx))
}
2020-04-06 19:42:35 -04:00
return mf, err
}
2016-03-16 20:51:03 -04:00
2020-01-20 15:51:33 -05:00
// TODO Validate if NowPlaying still works after all refactorings
2020-01-14 22:22:34 -05: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 21:04:41 -04:00
if err != nil {
return nil, err
}
if mf == nil {
2020-04-26 12:35:26 -04:00
return nil, fmt.Errorf(`ID "%s" not found`, trackId)
2016-03-16 21:04:41 -04:00
}
2020-04-06 19:42:35 -04:00
log.Info("Now Playing", "title", mf.Title, "artist", mf.Artist, "user", userName(ctx))
info := &NowPlayingInfo{TrackID: trackId, Username: username, Start: time.Now(), PlayerId: playerId, PlayerName: playerName}
return mf, s.npRepo.Enqueue(info)
2016-03-16 20:51:03 -04:00
}