summaryrefslogtreecommitdiff
path: root/player-server/internal/service/progress_test.go
blob: 9d8e4902245c445d58a63f77ec60b784f7f8b0e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package service

import (
	"context"
	"errors"
	"testing"
	"time"

	"codeberg.org/snonux/player/internal/clock"
	"codeberg.org/snonux/player/internal/model"
	"codeberg.org/snonux/player/internal/repository"
)

func TestProgressService_UpdateProgress_Validation(t *testing.T) {
	ctx := context.Background()
	svc := NewProgressService(&repository.MockStore{}, newMockClock())

	if err := svc.UpdateProgress(ctx, "", 1, 10, 5); err == nil {
		t.Fatal("expected error for empty sessionID")
	}
	if err := svc.UpdateProgress(ctx, "sess", 1, 0, 5); err == nil {
		t.Fatal("expected error for mediaID=0")
	}
}

func TestProgressService_UpdateProgress(t *testing.T) {
	ctx := context.Background()

	tests := []struct {
		name              string
		sessionID         string
		userID            int64
		mediaID           int64
		position          float64
		accLastPosition   float64
		accAccumulated    float64
		accCounted        bool
		accErr            error
		upsertProgressErr error
		upsertAccErr      error
		incrementErr      error
		wantErr           bool
		wantCounted       bool
	}{
		{
			name:            "fresh accumulator does not reach 60 due to clamp",
			sessionID:       "sess1",
			userID:          1,
			mediaID:         10,
			position:        65,
			accLastPosition: 0,
			accAccumulated:  0,
			accCounted:      false,
			wantCounted:     false,
		},
		{
			name:            "accumulator reaches 60",
			sessionID:       "sess1",
			userID:          1,
			mediaID:         10,
			position:        12,
			accLastPosition: 0,
			accAccumulated:  48,
			accCounted:      false,
			wantCounted:     true,
		},
		{
			name:            "delta clamped to 12",
			sessionID:       "sess1",
			userID:          1,
			mediaID:         10,
			position:        20,
			accLastPosition: 0,
			accAccumulated:  0,
			accCounted:      false,
			wantCounted:     false,
		},
		{
			name:            "negative delta clamped",
			sessionID:       "sess1",
			userID:          1,
			mediaID:         10,
			position:        5,
			accLastPosition: 10,
			accAccumulated:  50,
			accCounted:      false,
			wantCounted:     false,
		},
		{
			name:            "already counted",
			sessionID:       "sess1",
			userID:          1,
			mediaID:         10,
			position:        10,
			accLastPosition: 0,
			accAccumulated:  65,
			accCounted:      true,
			wantCounted:     true,
		},
		{
			name:              "upsert progress error",
			sessionID:         "sess1",
			userID:            1,
			mediaID:           10,
			position:          12,
			accAccumulated:    48,
			upsertProgressErr: errors.New("boom"),
			wantErr:           true,
		},
		{
			name:           "get accumulator error",
			sessionID:      "sess1",
			userID:         1,
			mediaID:        10,
			position:       12,
			accAccumulated: 48,
			accErr:         errors.New("boom"),
			wantErr:        true,
		},
		{
			name:           "upsert accumulator error",
			sessionID:      "sess1",
			userID:         1,
			mediaID:        10,
			position:       12,
			accAccumulated: 48,
			upsertAccErr:   errors.New("boom"),
			wantErr:        true,
		},
		{
			name:           "increment error",
			sessionID:      "sess1",
			userID:         1,
			mediaID:        10,
			position:       12,
			accAccumulated: 48,
			incrementErr:   errors.New("boom"),
			wantErr:        true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var savedAcc *model.PlaybackAccumulator
			var incremented int64

			store := &repository.MockStore{
				PlaybackProgressRepo: repository.MockPlaybackProgressRepo{
					UpsertProgressFunc: func(ctx context.Context, progress *model.PlaybackProgress) error {
						return tt.upsertProgressErr
					},
				},
				PlaybackAccumulatorRepo: repository.MockPlaybackAccumulatorRepo{
					GetAccumulatorFunc: func(ctx context.Context, sessionID string, mediaID int64) (*model.PlaybackAccumulator, error) {
						if tt.accErr != nil {
							return nil, tt.accErr
						}
						return &model.PlaybackAccumulator{
							SessionID:          sessionID,
							MediaID:            mediaID,
							LastPosition:       tt.accLastPosition,
							AccumulatedSeconds: tt.accAccumulated,
							Counted:            tt.accCounted,
						}, nil
					},
					UpsertAccumulatorFunc: func(ctx context.Context, acc *model.PlaybackAccumulator) error {
						savedAcc = acc
						return tt.upsertAccErr
					},
				},
				MediaRepo: repository.MockMediaRepo{
					// GetMediaByID feeds verifyAccess, which UpdateProgress
					// now calls to reject missing/deleted/forbidden media.
					GetMediaByIDFunc: func(ctx context.Context, id int64) (*model.Media, error) {
						return &model.Media{ID: id, SetID: 7}, nil
					},
					IncrementPlayCountFunc: func(ctx context.Context, id int64) error {
						incremented = id
						return tt.incrementErr
					},
				},
				UserRepo: repository.MockUserRepo{
					// Admin user short-circuits checkSetPermission so the
					// progress flow doesn't need a permissions fixture.
					GetUserByIDFunc: func(ctx context.Context, id int64) (*model.User, error) {
						return &model.User{ID: id, IsAdmin: true}, nil
					},
				},
			}

			svc := NewProgressService(store, newMockClock())
			err := svc.UpdateProgress(ctx, tt.sessionID, tt.userID, tt.mediaID, tt.position)
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if savedAcc == nil {
				t.Fatal("expected accumulator saved")
			}
			if savedAcc.Counted != tt.wantCounted {
				t.Fatalf("expected Counted=%v, got %v", tt.wantCounted, savedAcc.Counted)
			}
			if tt.wantCounted && !tt.accCounted && incremented != tt.mediaID {
				t.Fatalf("expected IncrementPlayCount called with %d", tt.mediaID)
			}
		})
	}
}

func TestProgressService_BatchUpdateProgress_OrdersByObservedAt(t *testing.T) {
	ctx := context.Background()
	observedBase := time.Date(2026, 5, 17, 10, 0, 0, 0, time.UTC)
	progressByMedia := make(map[int64]*model.PlaybackProgress)
	accByMedia := make(map[int64]*model.PlaybackAccumulator)
	var positions []float64

	store := &repository.MockStore{
		PlaybackProgressRepo: repository.MockPlaybackProgressRepo{
			GetProgressFunc: func(ctx context.Context, userID, mediaID int64) (*model.PlaybackProgress, error) {
				return progressByMedia[mediaID], nil
			},
			UpsertProgressFunc: func(ctx context.Context, progress *model.PlaybackProgress) error {
				cp := *progress
				progressByMedia[progress.MediaID] = &cp
				positions = append(positions, progress.PositionSeconds)
				return nil
			},
		},
		PlaybackAccumulatorRepo: repository.MockPlaybackAccumulatorRepo{
			GetAccumulatorFunc: func(ctx context.Context, sessionID string, mediaID int64) (*model.PlaybackAccumulator, error) {
				return accByMedia[mediaID], nil
			},
			UpsertAccumulatorFunc: func(ctx context.Context, acc *model.PlaybackAccumulator) error {
				cp := *acc
				accByMedia[acc.MediaID] = &cp
				return nil
			},
		},
		// BatchUpdateProgress now calls verifyAccess per item; the two
		// repos below give it real media + an admin user so each item
		// passes the access check before reaching applyProgress.
		MediaRepo: repository.MockMediaRepo{
			GetMediaByIDFunc: func(ctx context.Context, id int64) (*model.Media, error) {
				return &model.Media{ID: id, SetID: 7}, nil
			},
		},
		UserRepo: repository.MockUserRepo{
			GetUserByIDFunc: func(ctx context.Context, id int64) (*model.User, error) {
				return &model.User{ID: id, IsAdmin: true}, nil
			},
		},
	}

	svc := NewProgressService(store, &clock.MockClock{T: observedBase})
	err := svc.BatchUpdateProgress(ctx, "sess", 1, []ProgressUpdate{
		{MediaID: 10, PositionSeconds: 30, ObservedAt: observedBase.Add(2 * time.Minute)},
		{MediaID: 10, PositionSeconds: 10, ObservedAt: observedBase},
		{MediaID: 11, PositionSeconds: 20, ObservedAt: observedBase.Add(time.Minute)},
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	wantPositions := []float64{10, 20, 30}
	if len(positions) != len(wantPositions) {
		t.Fatalf("expected %d progress writes, got %d", len(wantPositions), len(positions))
	}
	for i, want := range wantPositions {
		if positions[i] != want {
			t.Fatalf("position call %d: expected %v, got %v", i, want, positions[i])
		}
	}
	if got := progressByMedia[10].PositionSeconds; got != 30 {
		t.Fatalf("expected latest media 10 position to win, got %v", got)
	}
}

func TestProgressService_BatchUpdateProgress_TransactionRollback(t *testing.T) {
	ctx := context.Background()
	store, err := repository.Open(":memory:")
	if err != nil {
		t.Fatalf("open store: %v", err)
	}
	defer store.Close()

	now := time.Date(2026, 5, 17, 10, 0, 0, 0, time.UTC)
	userID, err := store.CreateUser(ctx, &model.User{Username: "alice", PasswordHash: "hash", CreatedAt: now})
	if err != nil {
		t.Fatalf("create user: %v", err)
	}
	setID, err := store.CreateSet(ctx, &model.Set{Name: "set", RootPath: "/media/set", CreatedAt: now})
	if err != nil {
		t.Fatalf("create set: %v", err)
	}
	mediaID, err := store.CreateMedia(ctx, &model.Media{
		SetID:     setID,
		RelPath:   "one.mp4",
		FileName:  "one.mp4",
		AbsPath:   "/media/set/one.mp4",
		Type:      model.MediaTypeVideo,
		CreatedAt: now,
	})
	if err != nil {
		t.Fatalf("create media: %v", err)
	}
	if err := store.CreateSession(ctx, &model.Session{
		ID:        "sess",
		UserID:    userID,
		ExpiresAt: now.Add(time.Hour),
		CreatedAt: now,
	}); err != nil {
		t.Fatalf("create session: %v", err)
	}

	svc := NewProgressService(store, &clock.MockClock{T: now})
	err = svc.BatchUpdateProgress(ctx, "sess", userID, []ProgressUpdate{
		{MediaID: mediaID, PositionSeconds: 10, ObservedAt: now},
		{MediaID: 9999, PositionSeconds: 20, ObservedAt: now.Add(time.Second)},
	})
	if err == nil {
		t.Fatal("expected batch update error")
	}
	progress, err := store.GetProgress(ctx, userID, mediaID)
	if err != nil {
		t.Fatalf("get progress: %v", err)
	}
	if progress != nil {
		t.Fatalf("expected transaction rollback to remove first progress update, got %+v", progress)
	}
}

func TestProgressService_MarkFinished(t *testing.T) {
	ctx := context.Background()
	var saved *model.PlaybackProgress

	store := &repository.MockStore{
		MediaRepo: repository.MockMediaRepo{
			GetMediaByIDFunc: func(ctx context.Context, id int64) (*model.Media, error) {
				return &model.Media{ID: id, SetID: 7, Duration: 123.5}, nil
			},
		},
		UserRepo: repository.MockUserRepo{
			GetUserByIDFunc: func(ctx context.Context, id int64) (*model.User, error) {
				return &model.User{ID: id, IsAdmin: true}, nil
			},
		},
		PlaybackProgressRepo: repository.MockPlaybackProgressRepo{
			UpsertProgressFunc: func(ctx context.Context, progress *model.PlaybackProgress) error {
				saved = progress
				return nil
			},
		},
	}

	svc := NewProgressService(store, newMockClock())
	if err := svc.MarkFinished(ctx, 1, 10); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if saved == nil {
		t.Fatal("expected saved progress")
	}
	if !saved.Finished {
		t.Fatal("expected progress marked finished")
	}
	if saved.PositionSeconds != 123.5 {
		t.Fatalf("expected position_seconds=duration, got %v", saved.PositionSeconds)
	}
}

func TestProgressService_MarkFinished_Validation(t *testing.T) {
	ctx := context.Background()
	svc := NewProgressService(&repository.MockStore{}, newMockClock())

	if err := svc.MarkFinished(ctx, 1, 0); err == nil {
		t.Fatal("expected error for mediaID=0")
	}
}

func TestProgressService_MarkNotStarted(t *testing.T) {
	ctx := context.Background()
	var deletedProgress bool
	var deletedAccumulator bool

	store := &repository.MockStore{
		MediaRepo: repository.MockMediaRepo{
			GetMediaByIDFunc: func(ctx context.Context, id int64) (*model.Media, error) {
				return &model.Media{ID: id, SetID: 7}, nil
			},
		},
		UserRepo: repository.MockUserRepo{
			GetUserByIDFunc: func(ctx context.Context, id int64) (*model.User, error) {
				return &model.User{ID: id, IsAdmin: true}, nil
			},
		},
		PlaybackProgressRepo: repository.MockPlaybackProgressRepo{
			DeleteProgressFunc: func(ctx context.Context, userID, mediaID int64) error {
				deletedProgress = userID == 1 && mediaID == 10
				return nil
			},
		},
		PlaybackAccumulatorRepo: repository.MockPlaybackAccumulatorRepo{
			DeleteAccumulatorByMediaFunc: func(ctx context.Context, mediaID int64) error {
				deletedAccumulator = mediaID == 10
				return nil
			},
		},
	}

	svc := NewProgressService(store, newMockClock())
	if err := svc.MarkNotStarted(ctx, 1, 10); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !deletedProgress {
		t.Fatal("expected DeleteProgress called")
	}
	if !deletedAccumulator {
		t.Fatal("expected DeleteAccumulatorByMedia called")
	}
}

func TestProgressService_MarkNotStarted_Validation(t *testing.T) {
	ctx := context.Background()
	svc := NewProgressService(&repository.MockStore{}, newMockClock())

	if err := svc.MarkNotStarted(ctx, 1, 0); err == nil {
		t.Fatal("expected error for mediaID=0")
	}
}

func TestProgressService_ListInProgress(t *testing.T) {
	ctx := context.Background()

	tests := []struct {
		name      string
		user      *model.User
		perms     []model.SetPermission
		want      []model.Media
		wantAllow []int64
		wantCalls int
	}{
		{
			name:      "admin lists without allowed set filter",
			user:      &model.User{ID: 1, IsAdmin: true},
			want:      []model.Media{{ID: 10, SetID: 7}},
			wantAllow: nil,
			wantCalls: 1,
		},
		{
			name:      "viewer lists only permitted sets",
			user:      &model.User{ID: 2, IsAdmin: false},
			perms:     []model.SetPermission{{SetID: 7, UserID: 2}, {SetID: 8, UserID: 2}},
			want:      []model.Media{{ID: 10, SetID: 7}},
			wantAllow: []int64{7, 8},
			wantCalls: 1,
		},
		{
			name:      "viewer with no permissions does not query media",
			user:      &model.User{ID: 3, IsAdmin: false},
			want:      []model.Media{},
			wantAllow: nil,
			wantCalls: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var calls int
			var gotAllowed []int64

			store := &repository.MockStore{
				UserRepo: repository.MockUserRepo{
					GetUserByIDFunc: func(ctx context.Context, id int64) (*model.User, error) {
						return tt.user, nil
					},
				},
				SetPermissionRepo: repository.MockSetPermissionRepo{
					ListPermissionsByUserFunc: func(ctx context.Context, userID int64) ([]model.SetPermission, error) {
						return tt.perms, nil
					},
				},
				PlaybackProgressRepo: repository.MockPlaybackProgressRepo{
					ListInProgressMediaFunc: func(ctx context.Context, userID int64, filter repository.MediaFilter) ([]model.Media, error) {
						calls++
						gotAllowed = filter.AllowedSetIDs
						return tt.want, nil
					},
				},
			}

			svc := NewProgressService(store, newMockClock())
			got, err := svc.ListInProgress(ctx, tt.user.ID)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if calls != tt.wantCalls {
				t.Fatalf("expected %d ListInProgressMedia calls, got %d", tt.wantCalls, calls)
			}
			if len(got) != len(tt.want) {
				t.Fatalf("expected %d media, got %d", len(tt.want), len(got))
			}
			if tt.wantCalls > 0 && !equalInt64Slices(gotAllowed, tt.wantAllow) {
				t.Fatalf("expected AllowedSetIDs=%v, got %v", tt.wantAllow, gotAllowed)
			}
		})
	}
}

func equalInt64Slices(a, b []int64) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}