summaryrefslogtreecommitdiff
path: root/files/database.go
blob: 24bd5afde3c5746f0a6e35e193ecbdbdd0bc7fa2 (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
package files

import (
	"context"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"io"
	"io/fs"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/tidwall/buntdb"
)

func evaluateFile(database *buntdb.DB, hashsum string, filedata FileInfo) error {
	return database.View(func(tx *buntdb.Tx) error {
		data, err := tx.Get(hashsum)
		if err != nil {
			return err
		}

		var info FileInfo
		if err := json.Unmarshal([]byte(data), &info); err != nil {
			return err
		}
		if info == filedata {
			return UpToDate
		}
		switch info.Modtime == filedata.Modtime {
		case true:
			if info.AbsPath == filedata.AbsPath {
				if info.Process {
					return NeedsReencode
				}
				return UpToDate
			}
			if info.Process {
				return NeedsReencode
			}
			return MovedFile
		default:
			return nil
		}
	})
}

func getEncoderVer(path string) (string, error) {
	out, err := exec.Command("metaflac", "--show-vendor-tag", path).Output()
	if err != nil {
		return "", err
	}

	r := regexp.MustCompile("libFLAC \\d\\.\\d\\.\\d")
	encoder := r.FindString(string(out))
	switch encoder {
	case "":
		return "", nil
	default:
		return strings.Split(encoder, " ")[1], nil
	}
}

func updateFile(database *buntdb.DB, hashsum string, filedata FileInfo) error {
	return database.Update(func(tx *buntdb.Tx) error {
		data, err := json.Marshal(filedata)
		if err != nil {
			return err
		}
		if _, _, err := tx.Set(hashsum, string(data), nil); err != nil {
			return err
		}
		return nil
	})
}

func ProcessFile(ctx context.Context, path string, info fs.DirEntry) error {
	tmp, err := info.Info()
	if err != nil {
		return err
	}

	modtime := tmp.ModTime()

	database := ctx.Value("database").(*buntdb.DB)

	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()

	hash := sha256.New()
	if _, err := io.Copy(hash, file); err != nil {
		return err
	}
	hashsum := fmt.Sprintf("%x", hash.Sum(nil))

	abspath, err := filepath.Abs(path)
	if err != nil {
		return err
	}

	encoder, err := getEncoderVer(path)

	filedata := FileInfo{AbsPath: abspath, Modtime: modtime, Encoder: encoder, Process: true}

	err = evaluateFile(database, hashsum, filedata)
	switch err {
	case MovedFile, UpToDate:
		if filedata.Encoder == ctx.Value("encoder").(string) {
			return nil
		}
	case buntdb.ErrNotFound, NeedsReencode:

	default:
		return err
	}
	if err := updateFile(database, hashsum, filedata); err != nil {
		return err
	}
	return nil
}