Migrating hosting from Codeberg to git.kmalloc.org. Renames the module path in go.mod, every internal import, and the OCI image source label in the Dockerfile. Build and full test suite verified green after the rename.
59 lines
2 KiB
Go
59 lines
2 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/spotifyimport"
|
|
)
|
|
|
|
type spotifyImportRow struct {
|
|
bun.BaseModel `bun:"table:spotify_imports"`
|
|
|
|
ID int64 `bun:"id,pk,autoincrement"`
|
|
UserID int64 `bun:"user_id,notnull"`
|
|
CreatedAt int64 `bun:"created_at,notnull"`
|
|
Report string `bun:"report,notnull"`
|
|
}
|
|
|
|
// SpotifyImportRepo keeps the reports of the imports of Spotify exports. It implements spotifyimport.Runs.
|
|
type SpotifyImportRepo struct{ db *bun.DB }
|
|
|
|
// NewSpotifyImportRepo builds a SpotifyImportRepo.
|
|
func NewSpotifyImportRepo(db *bun.DB) *SpotifyImportRepo { return &SpotifyImportRepo{db: db} }
|
|
|
|
// Save keeps a report and gives its id.
|
|
func (r *SpotifyImportRepo) Save(ctx context.Context, userID int64, at time.Time, rep spotifyimport.Report) (int64, error) {
|
|
body, err := json.Marshal(rep)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("encode the report: %w", err)
|
|
}
|
|
row := &spotifyImportRow{UserID: userID, CreatedAt: at.Unix(), Report: string(body)}
|
|
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
|
|
return 0, fmt.Errorf("insert spotify import: %w", err)
|
|
}
|
|
return row.ID, nil
|
|
}
|
|
|
|
// List gives one page of the reports of a person, newest first, and how many there are.
|
|
func (r *SpotifyImportRepo) List(ctx context.Context, userID int64, limit, offset int) ([]spotifyimport.Run, int, error) {
|
|
var rows []spotifyImportRow
|
|
total, err := r.db.NewSelect().Model(&rows).Where("user_id = ?", userID).
|
|
OrderExpr("created_at DESC, id DESC").Limit(int64(limit)).Offset(int64(offset)).ScanAndCount(ctx)
|
|
if err != nil {
|
|
return nil, 0, fmt.Errorf("list spotify imports: %w", err)
|
|
}
|
|
runs := make([]spotifyimport.Run, 0, len(rows))
|
|
for _, row := range rows {
|
|
run := spotifyimport.Run{ID: row.ID, At: time.Unix(row.CreatedAt, 0)}
|
|
if err := json.Unmarshal([]byte(row.Report), &run.Report); err != nil {
|
|
return nil, 0, fmt.Errorf("decode spotify import %d: %w", row.ID, err)
|
|
}
|
|
runs = append(runs, run)
|
|
}
|
|
return runs, int(total), nil
|
|
}
|