summaryrefslogtreecommitdiff
path: root/internal/service/progress.go
blob: 60d9c25f2a0733ec054b06bcffe1e398ab4ef709 (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
package service

import (
	"context"
	"fmt"

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

// progressService is the concrete implementation of ProgressService.
type progressService struct {
	store repository.ProgressServiceStore
	clock clock.Clock
}

// NewProgressService creates a concrete ProgressService.
func NewProgressService(store repository.ProgressServiceStore, clk clock.Clock) ProgressService {
	return &progressService{
		store: store,
		clock: clk,
	}
}

func (s *progressService) UpdateProgress(ctx context.Context, sessionID string, userID, mediaID int64, position float64) error {
	now := s.clock.Now()

	if err := s.store.UpsertProgress(ctx, &model.PlaybackProgress{
		UserID:          userID,
		MediaID:         mediaID,
		PositionSeconds: position,
		UpdatedAt:       now,
	}); err != nil {
		return fmt.Errorf("upsert progress: %w", err)
	}

	acc, err := s.store.GetAccumulator(ctx, sessionID, mediaID)
	if err != nil {
		return fmt.Errorf("get accumulator: %w", err)
	}
	if acc == nil {
		acc = &model.PlaybackAccumulator{
			SessionID:          sessionID,
			MediaID:            mediaID,
			LastPosition:       0,
			AccumulatedSeconds: 0,
			Counted:            false,
			UpdatedAt:          now,
		}
	}

	delta := position - acc.LastPosition
	if delta < 0 {
		delta = 0
	}
	if delta > 12 {
		delta = 12
	}
	acc.AccumulatedSeconds += delta
	acc.LastPosition = position
	acc.UpdatedAt = now

	if acc.AccumulatedSeconds >= 60 && !acc.Counted {
		if err := s.store.IncrementPlayCount(ctx, mediaID); err != nil {
			return fmt.Errorf("increment play count: %w", err)
		}
		acc.Counted = true
	}

	if err := s.store.UpsertAccumulator(ctx, acc); err != nil {
		return fmt.Errorf("upsert accumulator: %w", err)
	}

	return nil
}