-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_and_transcode_files.go
211 lines (174 loc) · 6.09 KB
/
find_and_transcode_files.go
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/xfrr/goffmpeg/transcoder"
)
type fileToTranscode struct {
sourcePath string
destinationPath string
}
// findAndTranscodeFiles traverses the specified directory and transcodes music files to .mp3 format.
// MP3 files will be copied to the destination directory as-is.
func findAndTranscodeFiles(sourceDir, destinationDir string) error {
fmt.Printf("🔍 Finding files in source directory %s\n", sourceDir)
if err := os.MkdirAll(destinationDir, 0755); err != nil {
return fmt.Errorf("failed to create destination directory: %v", err)
}
filesThatNeedToBeTranscoded, err := compareDirectories(sourceDir, destinationDir)
if err != nil {
return fmt.Errorf("error: %v", err)
}
for _, file := range filesThatNeedToBeTranscoded {
sourcePath := filepath.Join(sourceDir, file.sourcePath)
if isUntranscodedMusicFile(sourcePath) {
err := transcodeFileAtPath(file.sourcePath, sourcePath, destinationDir)
if err != nil {
fmt.Fprintf(os.Stderr, "❗️ Error while transcoding file: %v\n", err)
// TODO: Maybe return error or queue for return
}
} else {
// Copy mp3 from source to destination
destinationPath := filepath.Join(destinationDir, file.sourcePath)
if err := copyFile(sourcePath, destinationPath); err != nil {
fmt.Fprintf(os.Stderr, "❗️ Error while copying file: %v\n", err)
// TODO: Maybe return error or queue for return
}
fmt.Printf("📂 Copied MP3: %s\n", destinationPath)
}
}
return nil
}
// copyFile copies a file from the source path to the destination path.
// It creates any necessary directories in the destination path.
// If the file cannot be copied for any reason, it returns an error.
//
// Example usage:
//
// err := copyFile("/path/to/source", "/path/to/destination")
// if err != nil {
// log.Fatal(err)
// }
func copyFile(source, destination string) error {
if err := os.MkdirAll(filepath.Dir(destination), 0755); err != nil {
return fmt.Errorf("❗️Failed to create directories: %v", err)
}
// Open the source file for reading
sourceFile, err := os.Open(source)
if err != nil {
return err
}
defer sourceFile.Close()
// Create the destination file
destinationFile, err := os.Create(destination)
if err != nil {
return err
}
defer destinationFile.Close()
// Copy the contents of the source file into the destination file
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
return err
}
// Call Sync to flush writes to stable storage
destinationFile.Sync()
return nil
}
// transcodeFileAtPath transcodes the music file at the specified path to .mp3 format.
func transcodeFileAtPath(fileSourcePath, sourcePath, destinationDir string) error {
// TODO: Rename fileSourcePath to a more descriptive name. It's a relative path and is used for source and destination subdirs (with filename)
destinationPath := filepath.Join(destinationDir, convertSourceToDestinationFilename(fileSourcePath))
if err := os.MkdirAll(filepath.Dir(destinationPath), 0755); err != nil {
return fmt.Errorf("❗️Failed to create directories: %v", err)
}
trans := new(transcoder.Transcoder)
if err := trans.Initialize(sourcePath, destinationPath); err != nil {
return err
}
done := trans.Run(false)
if err := <-done; err != nil {
return err
}
fmt.Printf("🔊 Transcoded: %s ➡️ %s\n", sourcePath, destinationPath)
return nil
}
// compareDirectories compares the files in two directories and returns a list of the files exclusive to directory A.
// The return value is the files that need to be transcoded (or copied to the destination, if already MP3).
func compareDirectories(a string, b string) ([]fileToTranscode, error) {
filesA, err := getFilenames(a)
if err != nil {
return nil, err
}
filesB, err := getFilenames(b)
if err != nil {
return nil, err
}
exclusiveFiles := getExclusiveFiles(filesA, filesB)
return exclusiveFiles, nil
}
// getFilenames returns a list of filenames in the specified directory.
func getFilenames(directory string) ([]string, error) {
var filenames []string
err := filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
relativePath := strings.TrimPrefix(path, directory)
filenames = append(filenames, relativePath)
}
return nil
})
if err != nil {
return nil, err
}
return filenames, nil
}
// getExclusiveFiles returns the files exclusive to filesA compared to filesB.
func getExclusiveFiles(filesA, filesB []string) []fileToTranscode {
exclusiveFiles := make([]fileToTranscode, 0)
fileMap := make(map[string]bool)
for _, file := range filesB {
fileMap[file] = true
}
// Generate list of filenames that need to be transcoded later
var sourceFileOutputNameList []fileToTranscode
for _, file := range filesA {
destinationFilename := ""
if strings.HasPrefix(filepath.Base(file), "._") {
// Skip hidden files
continue
} else if strings.HasSuffix(file, ".mp3") {
// Save .mp3 file name verbatim so it can be copied later
destinationFilename = file
} else if isUntranscodedMusicFile(file) {
// Add file to struct so it can be transcoded to .mp3 later
destinationFilename = convertSourceToDestinationFilename(file)
} else {
// Ignore .DS_Store, .txt and other files
file = ""
}
fileToTranscode := fileToTranscode{
sourcePath: file,
destinationPath: destinationFilename,
}
sourceFileOutputNameList = append(sourceFileOutputNameList, fileToTranscode)
}
for _, file := range sourceFileOutputNameList {
if !fileMap[file.destinationPath] && file.destinationPath != "" {
exclusiveFiles = append(exclusiveFiles, file)
}
}
return exclusiveFiles
}
// convertSourceToDestinationFilename converts the filename by replacing the .m4a suffix with .mp3 and replacing non-ASCII characters with an ASCII equivalent.
func convertSourceToDestinationFilename(filename string) string {
// Replace .m4a suffix with .mp3
filename = strings.TrimSuffix(filename, filepath.Ext(filename)) + ".mp3"
// Replace non-ASCII characters with an ASCII equivalent
filename = removeNonASCII(filename)
return filename
}