navidrome/engine/scrobbler.go

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

71 lines
1.9 KiB
Go
Raw Normal View History

package engine
import (
2020-01-09 02:45:07 +01:00
"context"
"fmt"
"time"
2020-04-07 01:42:35 +02:00
"github.com/deluan/navidrome/log"
2020-01-24 01:44:08 +01:00
"github.com/deluan/navidrome/model"
)
type Scrobbler interface {
2020-01-15 04:22:34 +01: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-15 04:22:34 +01:00
func (s *scrobbler) Register(ctx context.Context, playerId int, trackId string, playTime time.Time) (*model.MediaFile, error) {
2020-01-20 21:51:33 +01: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 21:51:33 +01:00
if err != nil {
return err
}
2020-02-01 03:09:23 +01:00
err = s.ds.MediaFile(ctx).IncPlayCount(trackId, playTime)
2020-01-20 21:51:33 +01:00
if err != nil {
return err
}
2020-02-01 03:09:23 +01: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 21:51:33 +01:00
return err
})
2020-04-07 01:42:35 +02:00
2020-05-25 16:54:07 +02: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-07 01:42:35 +02:00
return mf, err
}
2016-03-17 01:51:03 +01:00
2020-01-20 21:51:33 +01:00
// TODO Validate if NowPlaying still works after all refactorings
2020-01-15 04:22:34 +01: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-17 02:04:41 +01:00
if err != nil {
return nil, err
}
if mf == nil {
2020-04-26 18:35:26 +02:00
return nil, fmt.Errorf(`ID "%s" not found`, trackId)
2016-03-17 02:04:41 +01:00
}
2020-04-07 01:42:35 +02: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-17 01:51:03 +01:00
}