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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
|
package files
import (
"context"
"crypto/sha256"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/briandowns/spinner"
"golang.org/x/sync/errgroup"
)
func (file *FileInfo) reencodeFile(ctx context.Context) error {
/* cmd := exec.Command("flac", "-8", "-f", file.AbsPath)
if err := cmd.Run(); err != nil {
log.Printf("%s\n", err.Error())
return err
}
file.Encoder = ctx.Value("encoder").(string) */
fmt.Println(file)
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 getInfoFromFile(path string, info fs.DirEntry) (*FileInfo, error) {
var filedata FileInfo
filedata.Process = true
tmp, err := info.Info()
if err != nil {
return nil, err
}
filedata.Modtime = tmp.ModTime()
abspath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
filedata.AbsPath = abspath
encoder, err := getEncoderVer(path)
if err != nil {
return nil, err
}
filedata.Encoder = encoder
return &filedata, nil
}
func getSha256(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return nil, err
}
return hash.Sum(nil), nil
}
func IndexFlacs(ctx context.Context) error {
spin := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
spin.Suffix = " Indexing flacs..."
spin.Start()
wg := new(errgroup.Group)
wg.SetLimit(100)
if err := filepath.WalkDir(ctx.Value("path").(string), func(path string, info fs.DirEntry, err error) error {
select {
case <-ctx.Done():
spin.FinalMSG = "Stopping...\n"
spin.Stop()
return filepath.SkipAll
default:
if err != nil {
return err
}
if !info.IsDir() {
if filepath.Ext(path) == ".flac" {
wg.Go(func() error {
select {
case <-ctx.Done():
return nil
default:
data, err := getInfoFromFile(path, info)
if err != nil {
return err
}
hashsum, err := getSha256(path)
if err != nil {
return err
}
return data.IndexFile(ctx, hashsum)
}
})
}
}
return nil
}
}); err != nil {
return err
}
wg.Wait()
spin.FinalMSG = "Done indexing flacs\n"
spin.Stop()
return nil
}
|