aboutsummaryrefslogtreecommitdiff
path: root/pkg/worker/file_scanner.go
blob: 0dc2eb2d4ec01556a88a96ac284a0cd695b68f93 (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
package worker

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"io/fs"
	"path/filepath"

	"github.com/gabriel-vasile/mimetype"

	"git.sr.ht/~gabrielgio/img/pkg/components/media"
)

type (
	FileScanner struct {
		root       string
		repository media.Repository
	}
)

var _ ChanProcessor[string] = &FileScanner{}

func NewFileScanner(root string, repository media.Repository) *FileScanner {
	return &FileScanner{
		root:       root,
		repository: repository,
	}
}

func (f *FileScanner) Query(ctx context.Context) (<-chan string, error) {
	c := make(chan string)
	go func() {
		defer close(c)
		_ = filepath.Walk(f.root, func(path string, info fs.FileInfo, err error) error {
			select {
			case <-ctx.Done():
				return filepath.SkipAll
			default:
			}

			if info.IsDir() && filepath.Base(info.Name())[0] == '.' {
				return filepath.SkipDir
			}

			if info.IsDir() {
				return nil
			}

			if filepath.Ext(info.Name()) != ".jpg" &&
				filepath.Ext(info.Name()) != ".jpeg" &&
				filepath.Ext(info.Name()) != ".png" {
				return nil
			}
			c <- path
			return nil
		})
	}()
	return c, nil
}

func (f *FileScanner) Process(ctx context.Context, path string) error {
	hash := md5.Sum([]byte(path))
	str := hex.EncodeToString(hash[:])
	name := filepath.Base(path)

	exists, errResp := f.repository.Exists(ctx, str)
	if errResp != nil {
		return errResp
	}

	if exists {
		return nil
	}

	mime, errResp := mimetype.DetectFile(path)
	if errResp != nil {
		return errResp
	}

	return f.repository.Create(ctx, &media.CreateMedia{
		Name:     name,
		Path:     path,
		PathHash: str,
		MIMEType: mime.String(),
	})
}