/
main.go
346 lines (308 loc) · 10.5 KB
/
main.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/DanielRenne/GoCore/core/extensions"
"github.com/DanielRenne/GoCore/core/logger"
"github.com/DanielRenne/GoCore/core/path"
"github.com/DanielRenne/GoCore/core/utils"
"github.com/rwcarlsen/goexif/exif"
)
type filesSync struct {
sync.Mutex
Items []string
}
func RecurseFiles(fileDir string) (files []string, err error) {
defer func() {
if r := recover(); r != nil {
return
}
}()
var wg sync.WaitGroup
var syncedItems filesSync
path := fileDir
if extensions.DoesFileExist(path) == false {
return
}
err = filepath.Walk(path, func(path string, f os.FileInfo, errWalk error) (err error) {
if errWalk != nil {
err = errWalk
return
}
if !f.IsDir() {
wg.Add(1)
syncedItems.Lock()
syncedItems.Items = append(syncedItems.Items, path)
syncedItems.Unlock()
wg.Done()
}
return
})
wg.Wait()
files = syncedItems.Items
return
}
type processJob struct {
Func func(string)
File string
Wg *sync.WaitGroup
}
var (
jobs chan processJob
fmtDesired string
attemptRenameToDifferentMinute bool // set to false if you dont want this desire
)
// mov spec: https://developer.apple.com/standards/qtff-2001.pdf
// Page 31-33 contain information used in this file
const appleEpochAdjustment = 2082844800
const (
colisionMax = 15000
movieResourceAtomType = "moov"
movieHeaderAtomType = "mvhd"
referenceMovieAtomType = "rmra"
compressedMovieAtomType = "cmov"
)
func getVideoCreationTimeMetadata(videoBuffer io.ReadSeeker) (time.Time, error) {
buf := make([]byte, 8)
// Traverse videoBuffer to find movieResourceAtom
for {
// bytes 1-4 is atom size, 5-8 is type
// Read atom
if _, err := videoBuffer.Read(buf); err != nil {
return time.Time{}, err
}
if bytes.Equal(buf[4:8], []byte(movieResourceAtomType)) {
break // found it!
}
atomSize := binary.BigEndian.Uint32(buf) // check size of atom
videoBuffer.Seek(int64(atomSize)-8, 1) // jump over data and set seeker at beginning of next atom
}
// read next atom
if _, err := videoBuffer.Read(buf); err != nil {
return time.Time{}, err
}
atomType := string(buf[4:8]) // skip size and read type
switch atomType {
case movieHeaderAtomType:
// read next atom
if _, err := videoBuffer.Read(buf); err != nil {
return time.Time{}, err
}
// byte 1 is version, byte 2-4 is flags, 5-8 Creation time
appleEpoch := int64(binary.BigEndian.Uint32(buf[4:])) // Read creation time
return time.Unix(appleEpoch-appleEpochAdjustment, 0).Local(), nil
case compressedMovieAtomType:
return time.Time{}, errors.New("Compressed video")
case referenceMovieAtomType:
return time.Time{}, errors.New("Reference video")
default:
return time.Time{}, errors.New("Did not find movie header atom (mvhd)")
}
}
func init() {
attemptRenameToDifferentMinute = true
numConcurrent := 100
jobs = make(chan processJob)
for i := 0; i < numConcurrent; i++ {
go worker(i)
}
}
func worker(idx int) {
defer func() {
if r := recover(); r != nil {
return
}
}()
for job := range jobs {
job.Func(job.File)
job.Wg.Done()
}
}
func main() {
potentialPath := os.Args[1]
if len(os.Args) == 3 {
fmtDesired = os.Args[2]
} else {
fmtDesired = "2006-01-02 15.04.05"
}
startEntireProcess := time.Now()
stdErr := log.New(os.Stderr, "", 0)
if len(os.Args) < 2 {
log.Fatal("Please pass your MP3 directory to process")
}
var directoryToIterate string
var processJobs []processJob
var wg sync.WaitGroup
lastByte := potentialPath[len(potentialPath)-1:]
if lastByte != "\\" && path.IsWindows {
directoryToIterate = potentialPath + "\\"
} else if lastByte != "/" {
directoryToIterate = potentialPath + "/"
}
if path.IsWindows && strings.Index(directoryToIterate, "\\\\") != -1 {
log.Fatal("Please only escape your directory path once with \\")
}
if extensions.DoesFileExist(directoryToIterate) == false {
log.Fatal("Path does not exist or is invalid")
}
pictureExtensions := []string{
"JPG", "TIF", "BMP", "PNG", "JPEG", "GIF", "CR2", "ARW", "HEIC", "NEF",
}
movieExtensions := []string{
"MOV", "MP4",
}
files, _ := RecurseFiles(directoryToIterate)
for _, fileToWorkOn := range files {
pieces := strings.Split(fileToWorkOn, ".")
ext := strings.ToUpper(pieces[len(pieces)-1:][0])
if utils.InArray(ext, pictureExtensions) || utils.InArray(ext, movieExtensions) {
pieces := strings.Split(filepath.Base(fileToWorkOn), ".")
existingExt := "." + pieces[len(pieces)-1:][0]
fileName := strings.ReplaceAll(filepath.Base(fileToWorkOn), existingExt, "")
_, err := time.Parse(fmtDesired, fileName)
if err == nil {
log.Println(fileName + " is in desired date format skipping")
continue
}
processJobs = append(processJobs, processJob{
Wg: &wg,
File: fileToWorkOn,
Func: func(fileWork string) {
pieces := strings.Split(filepath.Base(fileWork), ".")
extUpper := strings.ToUpper(pieces[len(pieces)-1:][0])
existingExt := "." + pieces[len(pieces)-1:][0]
// Movie files
if utils.InArray(extUpper, movieExtensions) {
fd, err := os.Open(fileWork)
timeInfo, err := getVideoCreationTimeMetadata(fd)
fd.Close()
if err != nil {
stdErr.Println("Could not Read timestamp on movie file " + fileWork + ": " + err.Error())
return
}
potentialName := timeInfo.Format(fmtDesired)
fileName := strings.ReplaceAll(filepath.Base(fileWork), existingExt, "")
if fileName != potentialName {
newName := strings.ReplaceAll(fileWork, path.PathSeparator+fileName+existingExt, path.PathSeparator+potentialName+existingExt)
err := os.Rename(fileWork, newName)
if err != nil {
if attemptRenameToDifferentMinute {
// In a case of old scanned photos, you could have exif of approx dates, so this is a colision handler if you had 15000 images in one directory with the same exif Date
for i := 1; i < colisionMax; i++ {
potentialName := potentialName + "-" + extensions.IntToString(i)
newName = strings.ReplaceAll(fileWork, path.PathSeparator+fileName+existingExt, path.PathSeparator+potentialName+existingExt)
if err := os.Rename(fileWork, newName); err == nil {
log.Println("Renamed " + fileName + " to " + potentialName)
return
}
}
}
stdErr.Println("Could not rename: " + fileWork + ": " + err.Error())
return
}
log.Println("Renamed " + fileName + " to " + potentialName)
}
return
}
// Picture files
data, err := os.ReadFile(fileWork)
if err != nil {
stdErr.Println("Could not ReadFile" + fileWork + ": " + err.Error())
return
}
reader := bytes.NewReader(data)
x, err := exif.Decode(reader)
if err != nil {
stdErr.Println("Could not exif.Decode " + fileWork + ": " + err.Error())
return
}
data, err = x.MarshalJSON()
if err != nil {
stdErr.Println("Could not MarshalJSON " + fileWork + ": " + err.Error())
return
}
exifFields := make(map[string]interface{})
json.Unmarshal(data, &exifFields)
dateTimeOriginalValue, dateTimeOriginalok := exifFields["DateTimeOriginal"]
dateTimeValue, dateTimeok := exifFields["DateTime"]
if dateTimeOriginalok {
timeInfo, err := time.Parse("2006:01:02 15:04:05", dateTimeOriginalValue.(string))
if err != nil {
stdErr.Println("Failed to parse DateTimeOriginal Exif Data: " + fileWork + ": " + err.Error())
return
}
potentialName := timeInfo.Format(fmtDesired)
fileName := strings.ReplaceAll(filepath.Base(fileWork), existingExt, "")
if fileName != potentialName {
newName := strings.ReplaceAll(fileWork, path.PathSeparator+fileName+existingExt, path.PathSeparator+potentialName+existingExt)
err := os.Rename(fileWork, newName)
if err != nil {
if attemptRenameToDifferentMinute {
// In a case of old scanned photos, you could have exif of approx dates, so this is a colision handler if you had 15000 images in one directory with the same exif Date
for i := 1; i < colisionMax; i++ {
potentialName := potentialName + "-" + extensions.IntToString(i)
newName = strings.ReplaceAll(fileWork, path.PathSeparator+fileName+existingExt, path.PathSeparator+potentialName+existingExt)
if err := os.Rename(fileWork, newName); err == nil {
log.Println("Renamed " + fileName + " to " + potentialName)
return
}
}
}
stdErr.Println("Could not rename: " + fileWork + ": " + err.Error())
return
}
log.Println("Renamed " + fileName + " to " + potentialName)
}
} else if dateTimeok {
timeInfo, err := time.Parse("2006:01:02 15:04:05", dateTimeValue.(string))
if err != nil {
stdErr.Println("Failed to parse DateTime Exif Data: " + fileWork + ": " + err.Error())
return
}
potentialName := timeInfo.Format(fmtDesired)
fileName := strings.ReplaceAll(filepath.Base(fileWork), existingExt, "")
if fileName != potentialName {
newName := strings.ReplaceAll(fileWork, path.PathSeparator+fileName+existingExt, path.PathSeparator+potentialName+existingExt)
err := os.Rename(fileWork, newName)
if err != nil {
if attemptRenameToDifferentMinute {
// In a case of old scanned photos, you could have exif of approx dates, so this is a colision handler if you had 15000 images in one directory with the same exif Date
for i := 1; i < colisionMax; i++ {
potentialName := potentialName + "-" + extensions.IntToString(i)
newName = strings.ReplaceAll(fileWork, path.PathSeparator+fileName+existingExt, path.PathSeparator+potentialName+existingExt)
if err := os.Rename(fileWork, newName); err == nil {
log.Println("Renamed " + fileName + " to " + potentialName)
return
}
}
}
stdErr.Println("Could not rename: " + fileWork + ": " + err.Error())
return
}
log.Println("Renamed " + fileName + " to " + potentialName)
}
}
},
})
}
}
wg.Add(len(processJobs))
go func() {
for _, job := range processJobs {
j := job
jobs <- j
}
}()
log.Println("Waiting on threads to finish reading all your images and media...")
wg.Wait()
log.Println(logger.TimeTrack(startEntireProcess, "Completed in"))
}