scotty/pkg/scrobblerlog/parser.go
2025-05-01 13:22:20 +02:00

286 lines
7.6 KiB
Go

/*
Copyright © 2023-2025 Philipp Wolfer <phw@uploadedlobster.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Package to parse and write .scrobbler.log files as written by Rockbox.
//
// The parser supports reading version 1.1 and 1.0 of the scrobbler log file
// format. The latter is only supported if encoded in UTF-8.
//
// When written it always writes version 1.1 of the scrobbler log file format,
// which includes the MusicBrainz recording ID as the last field of each row.
//
// See
// - https://www.rockbox.org/wiki/LastFMLog
// - https://git.rockbox.org/cgit/rockbox.git/tree/apps/plugins/lastfm_scrobbler.c
// - https://web.archive.org/web/20110110053056/http://www.audioscrobbler.net/wiki/Portable_Player_Logging
package scrobblerlog
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"strconv"
"strings"
"time"
"go.uploadedlobster.com/mbtypes"
)
// TZInfo is the timezone information in the header of the scrobbler log file.
// It can be "UTC" or "UNKNOWN", if the device writing the scrobbler log file
// knows the time, but not the timezone.
type TZInfo string
const (
TimezoneUnknown TZInfo = "UNKNOWN"
TimezoneUTC TZInfo = "UTC"
)
// L if listened at least 50% or S if skipped
type Rating string
const (
RatingListened Rating = "L"
RatingSkipped Rating = "S"
)
// A single entry of a track in the scrobbler log file.
type Record struct {
ArtistName string
AlbumName string
TrackName string
TrackNumber int
Duration time.Duration
Rating Rating
Timestamp time.Time
MusicBrainzRecordingID mbtypes.MBID
}
// Represents a scrobbler log file.
type ScrobblerLog struct {
TZ TZInfo
Client string
Records []Record
// Timezone to be used for timestamps in the log file,
// if TZ is set to [TimezoneUnknown].
FallbackTimezone *time.Location
}
// Parses a scrobbler log file from the given reader.
//
// The reader must provide a valid scrobbler log file with a valid header.
// This function implicitly calls [ScrobblerLog.ReadHeader].
func (l *ScrobblerLog) Parse(data io.Reader, ignoreSkipped bool) error {
l.Records = make([]Record, 0)
reader := bufio.NewReader(data)
err := l.ReadHeader(reader)
if err != nil {
return err
}
tsvReader := csv.NewReader(reader)
tsvReader.Comma = '\t'
// Row length is often flexible
tsvReader.FieldsPerRecord = -1
for {
// A row is:
// artistName releaseName trackName trackNumber duration rating timestamp recordingMBID
row, err := tsvReader.Read()
if err == io.EOF {
break
} else if err != nil {
return err
}
// fmt.Printf("row: %v\n", row)
// We consider only the last field (recording MBID) optional
// This was added in the 1.1 file format.
if len(row) < 7 {
line, _ := tsvReader.FieldPos(0)
return fmt.Errorf("invalid record in scrobblerlog line %v", line)
}
record, err := l.rowToRecord(row)
if err != nil {
return err
}
if ignoreSkipped && record.Rating == RatingSkipped {
continue
}
l.Records = append(l.Records, record)
}
return nil
}
// Append writes the given records to the writer.
//
// The writer should be for an existing scrobbler log file or
// [ScrobblerLog.WriteHeader] should be called before this function.
// Returns the last timestamp of the records written.
func (l *ScrobblerLog) Append(data io.Writer, records []Record) (lastTimestamp time.Time, err error) {
tsvWriter := csv.NewWriter(data)
tsvWriter.Comma = '\t'
for _, record := range records {
if record.Timestamp.After(lastTimestamp) {
lastTimestamp = record.Timestamp
}
// A row is:
// artistName releaseName trackName trackNumber duration rating timestamp recordingMBID
err = tsvWriter.Write([]string{
record.ArtistName,
record.AlbumName,
record.TrackName,
strconv.Itoa(record.TrackNumber),
strconv.Itoa(int(record.Duration.Seconds())),
string(record.Rating),
strconv.FormatInt(record.Timestamp.Unix(), 10),
string(record.MusicBrainzRecordingID),
})
}
tsvWriter.Flush()
return
}
// Parses just the header of a scrobbler log file from the given reader.
//
// This function sets [ScrobblerLog.TZ] and [ScrobblerLog.Client].
func (l *ScrobblerLog) ReadHeader(reader *bufio.Reader) error {
// Skip header
for i := 0; i < 3; i++ {
line, _, err := reader.ReadLine()
if err != nil {
return err
}
if len(line) == 0 || line[0] != '#' {
err = fmt.Errorf("unexpected header (line %v)", i)
} else {
text := string(line)
if i == 0 && !strings.HasPrefix(text, "#AUDIOSCROBBLER/1") {
err = fmt.Errorf("not a scrobbler log file")
}
// The timezone can be set to "UTC" or "UNKNOWN", if the device writing
// the log knows the time, but not the timezone.
timezone, found := strings.CutPrefix(text, "#TZ/")
if found {
l.TZ = TZInfo(timezone)
continue
}
client, found := strings.CutPrefix(text, "#CLIENT/")
if found {
l.Client = client
continue
}
}
if err != nil {
return err
}
}
return nil
}
// Writes the header of a scrobbler log file to the given writer.
func (l *ScrobblerLog) WriteHeader(writer io.Writer) error {
headers := []string{
"#AUDIOSCROBBLER/1.1\n",
"#TZ/" + string(l.TZ) + "\n",
"#CLIENT/" + l.Client + "\n",
}
for _, line := range headers {
_, err := writer.Write([]byte(line))
if err != nil {
return err
}
}
return nil
}
func (l ScrobblerLog) rowToRecord(row []string) (Record, error) {
var record Record
trackNumber, err := strconv.Atoi(row[3])
if err != nil {
return record, err
}
duration, err := strconv.Atoi(row[4])
if err != nil {
return record, err
}
timestamp, err := strconv.ParseInt(row[6], 10, 64)
if err != nil {
return record, err
}
var timezone *time.Location = nil
if l.TZ == TimezoneUnknown {
timezone = l.FallbackTimezone
}
record = Record{
ArtistName: row[0],
AlbumName: row[1],
TrackName: row[2],
TrackNumber: trackNumber,
Duration: time.Duration(duration) * time.Second,
Rating: Rating(row[5]),
Timestamp: timeFromLocalTimestamp(timestamp, timezone),
}
if len(row) > 7 {
record.MusicBrainzRecordingID = mbtypes.MBID(row[7])
}
return record, nil
}
// Convert a Unix timestamp to a [time.Time] object, but treat the timestamp
// as being in the given location's timezone instead of UTC.
// If location is nil, the timestamp is returned assumed to already be in UTC
// and returned unchanged.
func timeFromLocalTimestamp(timestamp int64, location *time.Location) time.Time {
t := time.Unix(timestamp, 0)
// The time is now in UTC. Get the offset to the requested timezone
// and shift the time accordingly.
if location != nil {
_, offset := t.In(location).Zone()
if offset != 0 {
t = t.Add(-time.Duration(offset) * time.Second)
}
}
return t
}