aboutsummaryrefslogtreecommitdiff
path: root/pkg/worker/file_scanner.go
diff options
context:
space:
mode:
authorGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-02-26 19:54:48 +0100
committerGabriel Arakaki Giovanini <mail@gabrielgio.me>2023-06-18 16:30:36 +0200
commitc8e1328164e9ffbd681c3c0e449f1e6b9856b896 (patch)
treefaee639a4c55c5dc3bfc59a5400026822c40221d /pkg/worker/file_scanner.go
downloadlens-c8e1328164e9ffbd681c3c0e449f1e6b9856b896.tar.gz
lens-c8e1328164e9ffbd681c3c0e449f1e6b9856b896.tar.bz2
lens-c8e1328164e9ffbd681c3c0e449f1e6b9856b896.zip
feat: Inicial commit
It contains rough template for the server and runners. It contains rough template for the server and runners.
Diffstat (limited to 'pkg/worker/file_scanner.go')
-rw-r--r--pkg/worker/file_scanner.go81
1 files changed, 81 insertions, 0 deletions
diff --git a/pkg/worker/file_scanner.go b/pkg/worker/file_scanner.go
new file mode 100644
index 0000000..321fbca
--- /dev/null
+++ b/pkg/worker/file_scanner.go
@@ -0,0 +1,81 @@
+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 {
+ 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(),
+ })
+}