/* Copyright © 2025 Philipp Wolfer 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 listenbrainz import ( "archive/zip" "encoding/json" "fmt" "io" "iter" "os" "regexp" "sort" "strconv" "time" "github.com/simonfrey/jsonl" ) // Represents a ListenBrainz export archive. // // The export contains the user's listen history, favorite tracks and // user information. type Archive struct { backend archiveBackend } // Close the archive and release any resources. func (a *Archive) Close() error { return a.backend.Close() } // Read the user information from the archive. func (a *Archive) UserInfo() (UserInfo, error) { f, err := a.backend.OpenUserInfoFile() if err != nil { return UserInfo{}, err } defer f.Close() userInfo := UserInfo{} bytes, err := io.ReadAll(f) if err != nil { return userInfo, err } json.Unmarshal(bytes, &userInfo) return userInfo, nil } // Yields all listens from the archive that are newer than the given timestamp. // The listens are yielded in ascending order of their listened_at timestamp. func (a *Archive) IterListens(minTimestamp time.Time) iter.Seq2[Listen, error] { return func(yield func(Listen, error) bool) { files, err := a.backend.ListListenExports() if err != nil { yield(Listen{}, err) return } sort.Slice(files, func(i, j int) bool { return files[i].TimeRange.Start.Before(files[j].TimeRange.Start) }) for _, file := range files { if file.TimeRange.End.Before(minTimestamp) { continue } f := NewExportFile(file.f) for l, err := range f.IterListens() { if err != nil { yield(Listen{}, err) return } if !time.Unix(l.ListenedAt, 0).After(minTimestamp) { continue } if !yield(l, nil) { break } } } } } // Open a ListenBrainz archive from file path. func OpenArchive(path string) (*Archive, error) { fi, err := os.Stat(path) if err != nil { return nil, err } switch mode := fi.Mode(); { case mode.IsRegular(): backend := &zipArchive{} err := backend.Open(path) if err != nil { return nil, err } return &Archive{backend: backend}, nil case mode.IsDir(): // TODO: Implement directory mode return nil, fmt.Errorf("directory mode not implemented") default: return nil, fmt.Errorf("unsupported file mode: %s", mode) } } type UserInfo struct { ID string `json:"user_id"` Name string `json:"username"` } type archiveBackend interface { Close() error OpenUserInfoFile() (io.ReadCloser, error) ListListenExports() ([]ListenExportFileInfo, error) } type timeRange struct { Start time.Time End time.Time } type openableFile interface { Open() (io.ReadCloser, error) } type ListenExportFileInfo struct { Name string TimeRange timeRange f openableFile } type zipArchive struct { zip *zip.ReadCloser } func (a *zipArchive) Open(path string) error { zip, err := zip.OpenReader(path) if err != nil { return err } a.zip = zip return nil } func (a *zipArchive) Close() error { if a.zip == nil { return nil } return a.zip.Close() } func (a *zipArchive) OpenUserInfoFile() (io.ReadCloser, error) { file, err := a.zip.Open("user.json") if err != nil { return nil, err } return file, nil } func (a *zipArchive) ListListenExports() ([]ListenExportFileInfo, error) { re := regexp.MustCompile(`^listens/(\d{4})/(\d{1,2})\.jsonl$`) result := make([]ListenExportFileInfo, 0) for _, file := range a.zip.File { match := re.FindStringSubmatch(file.Name) if match == nil { continue } year := match[1] month := match[2] times, err := getMonthTimeRange(year, month) if err != nil { return nil, err } info := ListenExportFileInfo{ Name: file.Name, TimeRange: *times, f: file, } result = append(result, info) } return result, nil } type ListenExportFile struct { file openableFile } func NewExportFile(f openableFile) ListenExportFile { return ListenExportFile{file: f} } func (f *ListenExportFile) openReader() (*jsonl.Reader, error) { fio, err := f.file.Open() if err != nil { return nil, err } reader := jsonl.NewReader(fio) return &reader, nil } func (f *ListenExportFile) IterListens() iter.Seq2[Listen, error] { return func(yield func(Listen, error) bool) { reader, err := f.openReader() if err != nil { yield(Listen{}, err) return } defer reader.Close() for { listen := Listen{} err := reader.ReadSingleLine(&listen) if err != nil { break } if !yield(listen, nil) { break } } } } func getMonthTimeRange(year string, month string) (*timeRange, error) { yearInt, err := strconv.Atoi(year) if err != nil { return nil, err } monthInt, err := strconv.Atoi(month) if err != nil { return nil, err } r := &timeRange{} r.Start = time.Date(yearInt, time.Month(monthInt), 1, 0, 0, 0, 0, time.UTC) // Get the end of the month nextMonth := monthInt + 1 r.End = time.Date( yearInt, time.Month(nextMonth), 1, 0, 0, 0, 0, time.UTC).Add(-time.Second) return r, nil }