mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-08 02:17:25 +02:00
* refactor(persistence): adopt generic deluan/rest repository API Pin deluan/rest to the refactor branch. REST-facing repository methods take a context and return typed values. Drop DataStore.Resource and ResourceRepository; the native API names typed repositories directly through a per-request adapter that later commits remove. * refactor(persistence): base repository helpers take a context * refactor(persistence): LibraryRepository takes a context per call * refactor(persistence): PropertyRepository takes a context per call * refactor(persistence): UserPropsRepository takes a context per call * refactor(persistence): TranscodingRepository takes a context per call * refactor(persistence): ShareRepository takes a context per call * refactor(persistence): PlayerRepository takes a context per call * refactor(persistence): RadioRepository takes a context per call * refactor(persistence): PlayQueueRepository takes a context per call * refactor(persistence): Tag and Genre repositories take a context per call * refactor(persistence): PluginRepository takes a context per call * refactor(persistence): Scrobble repositories take a context per call * refactor(persistence): FolderRepository takes a context per call * refactor(persistence): Artwork repositories take a context per call * refactor(persistence): UserRepository takes a context per call * refactor(persistence): ArtistRepository takes a context per call ReadAll no longer rewrites the shared sort mappings for the role filter; it works on a per-call copy. * test(persistence): assert artist role sort sanitization in ReadAll * refactor(persistence): AlbumRepository takes a context per call * test(persistence): pass the test context to album repository helpers * refactor(persistence): MediaFileRepository takes a context per call * refactor(persistence): Playlist repositories take a context per call * refactor(persistence): build all repositories once per store * refactor(core): REST repository wrappers are built once * refactor(persistence): repositories are stateless Remove the context field from the base repository and the per-request REST adapter. Enable the containedctx linter so no repository can hold a request context again. * chore(lint): skip containedctx in test files * refactor: share simplifications from the stateless repositories sweep Add deleteOwnedAll on sqlRepository and use it in player/share Delete to remove the duplicated bulk-delete loop; have Share.Repository() return model.ShareRepository so subsonic sharing.go drops its repeated type assertions. * chore(core): assert REST wrappers implement Persistable * chore: reformat imports * perf(persistence): build repositories on first use Each transaction store used to construct all 21 repositories up front, paying for filter and sort mapping setup the block never touched. Fields are now sync.OnceValue thunks, so a store only builds what it uses. * fix(persistence): clean plugin references per deleted user A bulk user delete that fails on a later id had already removed the earlier rows but skipped their plugin cleanup. Cleanup now runs right after each successful delete. * fix(core): unload disabled plugins even when a user delete fails A bulk delete can fail on a later id after earlier users were removed and their plugins auto-disabled. The wrapper returned before unloading, leaving those plugins running until the next successful delete or a restart. * chore(deps): pin deluan/rest to v1.0.1 Replaces the pseudo-version of the refactor branch with the tagged release. REST error messages now name the bare type (Artist, not model.Artist). * test: use the spec context instead of context.Background() Replace the context.Background()/context.TODO() calls this branch added to tests with the spec's ctx, GinkgoT().Context(), or t/b.Context(), so repository calls are bound to the running spec's lifetime. * test: declare the spec context once per Describe Set ctx from GinkgoT().Context() first in each top-level BeforeEach and reuse it, building user contexts on top of it instead of repeating inline calls.
166 lines
4.9 KiB
Go
166 lines
4.9 KiB
Go
package persistence
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
. "github.com/Masterminds/squirrel"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/model/request"
|
|
)
|
|
|
|
const bookmarkTable = "bookmark"
|
|
|
|
func (r sqlRepository) withBookmark(ctx context.Context, query SelectBuilder, idField string) SelectBuilder {
|
|
userID := loggedUser(ctx).ID
|
|
if userID == invalidUserId {
|
|
return query
|
|
}
|
|
return query.
|
|
LeftJoin("bookmark on (" +
|
|
"bookmark.item_id = " + idField +
|
|
" AND bookmark.user_id = '" + userID + "')").
|
|
Columns("coalesce(position, 0) as bookmark_position")
|
|
}
|
|
|
|
func (r sqlRepository) bmkID(ctx context.Context, itemID ...string) And {
|
|
return And{
|
|
Eq{bookmarkTable + ".user_id": loggedUser(ctx).ID},
|
|
Eq{bookmarkTable + ".item_type": r.tableName},
|
|
Eq{bookmarkTable + ".item_id": itemID},
|
|
}
|
|
}
|
|
|
|
func (r sqlRepository) bmkUpsert(ctx context.Context, itemID, comment string, position int64) error {
|
|
client, _ := request.ClientFrom(ctx)
|
|
user, _ := request.UserFrom(ctx)
|
|
values := map[string]any{
|
|
"comment": comment,
|
|
"position": position,
|
|
"updated_at": time.Now(),
|
|
"changed_by": client,
|
|
}
|
|
|
|
upd := Update(bookmarkTable).Where(r.bmkID(ctx, itemID)).SetMap(values)
|
|
c, err := r.executeSQL(ctx, upd)
|
|
if err == nil {
|
|
log.Debug(ctx, "Updated bookmark", "id", itemID, "user", user.UserName, "position", position, "comment", comment)
|
|
}
|
|
if c == 0 || errors.Is(err, sql.ErrNoRows) {
|
|
values["user_id"] = user.ID
|
|
values["item_type"] = r.tableName
|
|
values["item_id"] = itemID
|
|
values["created_at"] = time.Now()
|
|
values["updated_at"] = time.Now()
|
|
ins := Insert(bookmarkTable).SetMap(values)
|
|
_, err = r.executeSQL(ctx, ins)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
log.Debug(ctx, "Added bookmark", "id", itemID, "user", user.UserName, "position", position, "comment", comment)
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func (r sqlRepository) AddBookmark(ctx context.Context, id, comment string, position int64) error {
|
|
user, _ := request.UserFrom(ctx)
|
|
err := r.bmkUpsert(ctx, id, comment, position)
|
|
if err != nil {
|
|
log.Error(ctx, "Error adding bookmark", "id", id, "user", user.UserName, "position", position, "comment", comment)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (r sqlRepository) DeleteBookmark(ctx context.Context, id string) error {
|
|
user, _ := request.UserFrom(ctx)
|
|
del := Delete(bookmarkTable).Where(r.bmkID(ctx, id))
|
|
_, err := r.executeSQL(ctx, del)
|
|
if err != nil {
|
|
log.Error(ctx, "Error removing bookmark", "id", id, "user", user.UserName)
|
|
}
|
|
return err
|
|
}
|
|
|
|
type bookmark struct {
|
|
UserID string `json:"user_id"`
|
|
ItemID string `json:"item_id"`
|
|
ItemType string `json:"item_type"`
|
|
Comment string `json:"comment"`
|
|
Position int64 `json:"position"`
|
|
ChangedBy string `json:"changed_by"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
UpdatedAt time.Time `json:"updatedAt"`
|
|
}
|
|
|
|
func (r sqlRepository) GetBookmarks(ctx context.Context) (model.Bookmarks, error) {
|
|
user, _ := request.UserFrom(ctx)
|
|
|
|
idField := r.tableName + ".id"
|
|
sq := r.newSelect(ctx).Columns(r.tableName + ".*")
|
|
sq = r.withAnnotation(ctx, sq, idField)
|
|
sq = r.withBookmark(ctx, sq, idField).Where(NotEq{bookmarkTable + ".item_id": nil})
|
|
sq = r.applyLibraryFilter(ctx, sq)
|
|
var mfs dbMediaFiles // TODO Decouple from media_file
|
|
err := r.queryAll(ctx, sq, &mfs)
|
|
if err != nil {
|
|
log.Error(ctx, "Error getting mediafiles with bookmarks", "user", user.UserName, err)
|
|
return nil, err
|
|
}
|
|
|
|
ids := make([]string, len(mfs))
|
|
mfMap := make(map[string]int)
|
|
for i, mf := range mfs {
|
|
ids[i] = mf.ID
|
|
mfMap[mf.ID] = i
|
|
}
|
|
|
|
sq = Select("*").From(bookmarkTable).Where(r.bmkID(ctx, ids...))
|
|
var bmks []bookmark
|
|
err = r.queryAll(ctx, sq, &bmks)
|
|
if err != nil {
|
|
log.Error(ctx, "Error getting bookmarks", "user", user.UserName, "ids", ids, err)
|
|
return nil, err
|
|
}
|
|
|
|
resp := make(model.Bookmarks, len(bmks))
|
|
for i, bmk := range bmks {
|
|
if itemIdx, ok := mfMap[bmk.ItemID]; !ok {
|
|
log.Debug(ctx, "Invalid bookmark", "id", bmk.ItemID, "user", user.UserName)
|
|
continue
|
|
} else {
|
|
resp[i] = model.Bookmark{
|
|
Comment: bmk.Comment,
|
|
Position: bmk.Position,
|
|
CreatedAt: bmk.CreatedAt,
|
|
UpdatedAt: bmk.UpdatedAt,
|
|
ChangedBy: bmk.ChangedBy,
|
|
Item: *mfs[itemIdx].MediaFile,
|
|
}
|
|
}
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
func (r sqlRepository) reassignBookmark(ctx context.Context, prevID, newID string) error {
|
|
upd := Expr("update or ignore "+bookmarkTable+" set item_id = ? where item_type = ? and item_id = ?",
|
|
newID, r.tableName, prevID)
|
|
_, err := r.executeSQL(ctx, upd)
|
|
return err
|
|
}
|
|
|
|
func (r sqlRepository) cleanBookmarks(ctx context.Context) error {
|
|
del := Delete(bookmarkTable).Where(Eq{"item_type": r.tableName}).Where("item_id not in (select id from " + r.tableName + ")")
|
|
c, err := r.executeSQL(ctx, del)
|
|
if err != nil {
|
|
return fmt.Errorf("error cleaning up %s bookmarks: %w", r.tableName, err)
|
|
}
|
|
if c > 0 {
|
|
log.Debug(ctx, "Clean-up bookmarks", "totalDeleted", c, "itemType", r.tableName)
|
|
}
|
|
return nil
|
|
}
|