aboutsummaryrefslogtreecommitdiff
path: root/pkg/worker/scanner/thumbnail_scanner.go
blob: 6446c53271d918ffe3ee24fa68950db8a3bd6fac (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
package scanner

import (
	"context"
	"fmt"
	"math"
	"os"
	"path"

	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
	"git.sr.ht/~gabrielgio/img/pkg/fileop"
	"git.sr.ht/~gabrielgio/img/pkg/worker"
)

type (
	ThumbnailScanner struct {
		repository repository.MediaRepository
		cachePath  string
	}
)

var _ worker.ListProcessor[*repository.Media] = &EXIFScanner{}

func NewThumbnailScanner(cachePath string, repository repository.MediaRepository) *ThumbnailScanner {
	return &ThumbnailScanner{
		repository: repository,
		cachePath:  cachePath,
	}
}

func (t *ThumbnailScanner) Query(ctx context.Context) ([]*repository.Media, error) {
	return t.repository.ListEmptyThumbnail(ctx, &repository.Pagination{
		Page: 0,
		Size: 100,
	})
}

func (t *ThumbnailScanner) OnFail(ctx context.Context, media *repository.Media, _ error) {
	_ = t.repository.CreateThumbnail(ctx, media.ID, &repository.MediaThumbnail{
		Path: "",
	})
}

func (t *ThumbnailScanner) Process(ctx context.Context, media *repository.Media) error {
	split := media.PathHash[:2]
	filename := media.PathHash[2:]
	folder := path.Join(t.cachePath, split)
	output := path.Join(folder, filename+".jpeg")

	err := os.MkdirAll(folder, os.ModePerm)
	if err != nil {
		return err
	}

	if media.IsVideo() {
		err := fileop.EncodeVideoThumbnail(media.Path, output, 1080, 1080)
		if err != nil {
			return fmt.Errorf("Error thumbnail video %d; %w", media.ID, err)
		}
	} else {
		err := fileop.EncodeImageThumbnail(media.Path, output, 1080, math.MinInt32)
		if err != nil {
			return fmt.Errorf("Error thumbnail image %d; %w", media.ID, err)
		}
	}

	return t.repository.CreateThumbnail(ctx, media.ID, &repository.MediaThumbnail{
		Path: output,
	})
}