-
Notifications
You must be signed in to change notification settings - Fork 3
/
goprox
executable file
·1542 lines (1357 loc) · 47.8 KB
/
goprox
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/zsh
#
# The MIT License (MIT)
#
# Copyright (c) 2021, 2022, 2023 by Oliver Ratzesberger
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
__author__='Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__='Copyright (C) 2021, 2022, 2023 Oliver Ratzesberger'
__license__='MIT'
__version__='00.53.dev'
__github__='https://github.com/fxstein/GoProX'
__this__=$(basename $0)
readonly VERSION_TEXT="$__this__ v$__version__"
readonly BANNER_TEXT="$VERSION_TEXT
$__copyright__
License: $__license__
$__github__
"
readonly HELP_TEXT="goprox - import and process GoPro media files
Usage: goprox [commands] [options] [advanced options] ...
Commands:
-a, --archive archive source sdcard
-i, --import import media files
-p, --process process imported files
default: process imported files since last process run
all: process all imported files
val[ymwdHMS]: process files modified within the specified time period
--clean clean up source sdcard
checks if source is a GoPro sdcard format
--firmware update sdcard to the latest GoPro firmware version
labs: use GoPro Labs firmware
--geonames add geonames information to imported directories to enable time processing
--mount trigger mountpoint processing
will search for GoPro media card mountpoints and kick of processing
this is also leveraged by the goprox launch agent
--setup run program setup
--test run program tests
this option is reserved for developers who clone the GitHub project
Options:
-h, --help show this help message and exit
-c, --copyright add copyright information to processed files
-l, --library specify library directory
-s, --source specify source directory for media files commonly .
-t, --timeshift adjust timestamps of imported files
-q, --quiet run program quietly
-v, --verbose run program verbosely
--config specify config file
defaults to ~/.goprox
--debug run program in debug mode
--time specify time format for output
format: specify time format for output
--version show version information and exit
Advanced Options:
--if specify conditional processing
condition: specify condition for processing
--created-on filter files by creation date
date: filter files created on the specified date
--created-after filter files by creation date
date: filter files created after the specified date
--created-before filter files by creation date
date: filter files created before the specified date
--modified-on filter files by modification date
date: filter files modified on the specified date
--modified-after filter files by modification date
date: filter files modified after the specified date
--modified-before filter files by modification date
date: filter files modified before the specified date
--repair repair imported files time information
created: repair file creation dates
For more detailed documentation type: man goprox or visit $__github__
"
# Various defaults
readonly DEFAULT_CONFIG=~/.goprox
readonly DEFAULT_SOURCE="."
readonly DEFAULT_LIBRARY="~/goprox"
readonly DEFAULT_COPYRIGHT=""
readonly DEFAULT_GEONAMESACCT=""
readonly DEFAULT_GEONAMESFILE="geonames.json"
readonly DEFAULT_MOUNTOPTIONS=(--archive --import --clean --firmware)
readonly DEFAULT_TIMEFORMAT='%Y-%m-%d %H:%M:%S'
readonly DEFAULT_FILETYPES="JPG|MP4|360|JPEG|HEIC"
readonly TIMESTAMP_PRE='perl -pe '"'"'use POSIX strftime; $|=1; print strftime "['
readonly TIMESTAMP_POST='] ", localtime'"'"
readonly DEFAULT_OUTPUT='tee'
readonly DEFAULT_LOGLEVEL=2 #debug:0; info:1; warn:2; error:3
readonly DEFAULT_EXIFTOOL_LOGLEVEL0="-v2 -progress"
readonly DEFAULT_EXIFTOOL_LOGLEVEL1="-v1 -progress"
readonly DEFAULT_EXIFTOOL_LOGLEVEL2="-q -q -progress"
readonly DEFAULT_EXIFTOOL_LOGLEVEL3="-q -q -q"
readonly GOPROX=$(which $0)
readonly REALGOPROX=$(readlink -f $GOPROX)
readonly GOPROX_HOME=$(dirname $REALGOPROX)
readonly DEFAULT_LOCKFILE=".goprox.lock"
readonly DEFAULT_ARCHIVED_MARKER=".goprox.archived"
readonly DEFAULT_IMPORTED_MARKER=".goprox.imported"
readonly DEFAULT_CLEANED_MARKER=".goprox.cleaned"
readonly DEFAULT_FWCHECKED_MARKER=".goprox.fwchecked"
# Initializing...
config=$DEFAULT_CONFIG
source=$DEFAULT_SOURCE
library=$DEFAULT_LIBRARY
geonamesacct=$DEFAULT_GEONAMESACCT
geonamesfile=$DEFAULT_GEONAMESFILE
copyright=$DEFAULT_COPYRIGHT
mountoptions=$DEFAULT_MOUNTOPTIONS
output=$DEFAULT_OUTPUT
filetypes=$DEFAULT_FILETYPES
loglevel=$DEFAULT_LOGLEVEL
exifloglevel=$DEFAULT_EXIFTOOL_LOGLEVEL2
test=false
setup=false
debug=false
import=false
process=false
geonames=false
archive=false
clean=false
firmware=false
version=false
mount=false
sourceopt=""
libraryopt=""
processopt=""
copyrightopt=""
geonamesopt=""
firmwareopt=""
mountopt=""
# filter options
filter=false
createdfilter=false
createdonopt=""
createdafteropt=""
createdbeforeopt=""
ifopt=""
modifiedfilter=false
modifiedonopt=""
modifiedafteropt=""
modifiedbeforeopt=""
iffilter=() # default is empty array for later parameter expansion
# The api filter is used to rename camera models globally
apifilter=()
apifilter+=('Filter=s/HERO11 Black/GoPro_Hero11/g;')
apifilter+=('s/HERO11 Black Mini/GoPro_Hero11_Mini/g;')
apifilter+=('s/HERO10 Black/GoPro_Hero10/g;')
apifilter+=('s/HERO9 Black/GoPro_Hero9/g;')
apifilter+=('s/HERO8 Black/GoPro_Hero8/g;')
apifilter+=('s/GoPro Max/GoPro_Max/g')
exiftoolstatus=0
validlibrary=false
validarchive=false
validimported=false
validprocessed=false
validdeleted=false
tempdir=""
function _debug()
{
if [[ $loglevel -le 0 ]] ; then
echo $fg[blue]"Debug: "$1 $2$reset_color
logger -t "goprox" -p user.debug "goprox: Debug: "$1 $2
fi
}
function _info()
{
if [[ $loglevel -le 1 ]] ; then
echo $fg[green]"Info: "$1 $2$reset_color
logger -t "goprox" -p user.info "goprox: Info: "$1 $2
fi
}
function _echo()
{
if [[ $loglevel -le 2 ]] ; then
echo $fg[green]$1 $2$reset_color
logger -t "goprox" -p user.notice "goprox: "$1 $2
fi
}
function _warning()
{
if [[ $loglevel -le 2 ]] ; then
echo $fg[yellow]"Warning: "$1 $2$reset_color
logger -t "goprox" -p user.warning "goprox: Warning: "$1 $2
fi
}
function _error()
{
if [[ $loglevel -le 3 ]] ; then
>&2 echo $fg[red]"Error: "$1 $2$reset_color
logger -t "goprox" -p user.error -s "goprox: Error: "$1 $2
fi
}
function _help()
{
echo $HELP_TEXT
}
function _validate_dependencies()
{
# only works if the exiftool is installed
_info "Validating exiftool..."
if (( ${+commands[exiftool]} )); then
[[ $loglevel -le 1 ]] && which exiftool
if [[ "$debug" = true ]]; then
exiftool -ver -v
else
[[ $loglevel -le 1 ]] && exiftool -ver
fi
else
_error "ERROR: Please install exiftool first, run:"
_warning "brew install exiftool"
exit 1
fi
# jq is needed to parse and write json data
_info "Validating jq..."
if (( ${+commands[jq]} )); then
[[ $loglevel -le 1 ]] && which jq && jq --version
else
_error "ERROR: Please install jq first, run:"
_warning "brew install jq"
exit 1
fi
}
function _test_library_component()
{
# $1 ... library component name (for logging)
# $2 ... library component path (to be tested)
# returns 0 if successfully validated, 1 if not
if [[ -L "$2" ]] ; then
librarylink=$(readlink -f $2)
if [[ -e "$2" ]] ; then
# Valid link
_info "goprox $1: $2 is valid link to $librarylink"
else
# Broken link
_warning "goprox $1: $2 is a broken link to $librarylink"
_warning "Make sure the storage device is mounted and the directory has not been moved."
return 2
fi
elif [[ -d "$2" ]] ; then
# valid directory
_info "goprox $1: $2 directory validated"
else
# completly missing
_warning "goprox $1: $2 directory or link is missing"
_info "Creating $2 directory..."
mkdir $2 || {
_error "Failed to create $2 directory."
return 1
}
fi
# All validation checks have been successful
return 0
}
function _validate_storage()
{
# perform test to validate the storage hierarchy
_info "Validating storage hierarchy..."
# Start with the root and validate its existence
_test_library_component "library" $library && validlibrary=true
# Only test the subtree if the root library is valid
if [[ $validlibrary = true ]] ; then
_test_library_component "archive" "$library/archive" && validarchive=true
_test_library_component "imported" "$library/imported" && validimported=true
_test_library_component "processed" "$library/processed" && validprocessed=true
_test_library_component "deleted" "$library/deleted" && validdeleted=true
fi
_info "Finished storage hierarchy validation."
}
function _setup()
{
# check if file exists
if [[ -f "$config" ]]; then
_info "Existing $config file."
timestamp=`date +%s`
backup=$config.bak.$timestamp
_info "Creating backup: $backup"
mv $config $backup
fi
touch $config
if [ $? -ne 0 ]
then
_error "Unable to create config file: $config"
exit(1)
fi
_info "Source: "$source
_info "Library: "$library
_info "Copyright: "$copyright
_info "GeoNamesAcct: "$geonamesacct
_info "Writing config file: $config"
echo "source="$source>>$config
echo "library=\""$library"\"">>$config
echo "copyright=\""$copyright"\"">>$config
echo "geonamesacct=\""$geonamesacct"\"">>$config
echo "mountoptions=(${mountoptions})">>$config
_info "Config saved as $config"
# check if library exists, otherwise create the skeleton
_validate_storage
_info "Finished setup task."
}
function _create_timefilter()
{
if [[ $filter = false ]] ; then
_debug "Nothing to filter."
return 0
fi
# Assemble time filter based on various filter options:
# --created-on:[date]
# --created-after:[date]
# --created-before:[date]
# --modified-on:[date]
# --modified-after:[date]
# --modified-before:[date]
_info "Creating time filter..."
if [[ $createdfilter = true ]] ; then
_debug "FileCreatedDate filter assembly"
if [[ -n $createdonopt ]]; then
_debug "CreatedOnFilter: "${createdonopt}
# Need to assemble as an array to preserve whitespaces within $ifopt
iffilter+='-if4'
iffilter+='${FileCreateDate#;DateFmt("%Y%m%d%H%M%S")} =~ "'${createdonopt}'"'
elif [[ -n $createdafteropt && -n $createdbeforeopt ]]; then
iffilter+='-if4'
iffilter+='${FileCreateDate#;DateFmt("%Y%m%d%H%M%S")} ge "'${createdafteropt}'"'\
' and ${FileCreateDate#;DateFmt("%Y%m%d%H%M%S")} lt "'${createdbeforeopt}'"'
elif [[ -n $createdafteropt ]]; then
iffilter+='-if4'
iffilter+='${FileCreateDate#;DateFmt("%Y%m%d%H%M%S")} ge "'${createdafteropt}'"'
elif [[ -n $createdbeforeopt ]]; then
iffilter+='-if4'
iffilter+='${FileCreateDate#;DateFmt("%Y%m%d%H%M%S")} lt "'${createdbeforeopt}'"'
else
_error "Invalid filter options."
return 1
fi
fi
if [[ $modifiedfilter = true ]] ; then
_debug "FileModifiedDate filter assembly"
if [[ -n $modifiedonopt ]]; then
_debug "ModifiedOnFilter: "${modifiedonopt}
# Need to assemble as an array to preserve whitespaces within $ifopt
iffilter+='-if4'
iffilter+='${FileModifyDate#;DateFmt("%Y%m%d%H%M%S")} =~ "'${modifiedonopt}'"'
elif [[ -n $modifiedafteropt && -n $modifiedbeforeopt ]]; then
iffilter+='-if4'
iffilter+='${FileModifyDate#;DateFmt("%Y%m%d%H%M%S")} ge "'${modifiedafteropt}'"'\
' and ${FileModifyDate#;DateFmt("%Y%m%d%H%M%S")} lt "'${modifiedbeforeopt}'"'
elif [[ -n $modifiedafteropt ]]; then
iffilter+='-if4'
iffilter+='${FileModifyDate#;DateFmt("%Y%m%d%H%M%S")} ge "'${modifiedafteropt}'"'
elif [[ -n $modifiedbeforeopt ]]; then
iffilter+='-if4'
iffilter+='${FileModifyDate#;DateFmt("%Y%m%d%H%M%S")} lt "'${modifiedbeforeopt}'"'
else
_error "Invalid filter options."
return 1
fi
fi
_info "Finished time filter."
return 0
}
function _create_iffilter()
{
if [[ $filter = false ]] ; then
_debug "Nothing to filter."
return 0
fi
_info "Creating if filter..."
if [[ -n $ifopt ]]; then
_debug "IfFilter: "${ifopt}
# Need to assemble as an array to preserve whitespaces within $ifopt
iffilter+='-if0'
iffilter+="${ifopt}"
fi
_info "Finished if filter..."
return 0
}
function _import_media()
{
if [[ $validimported = false ]] ; then
_error "Invalid imported directory. Cannot proceed with import."
exit 1
fi
importdir=$library/imported
_echo "Starting media import..."
_info "Source: $source ($(realpath $source))"
_info "Library: $importdir ($(realpath $importdir))"
# Remove previous import marker
rm -f $source/$DEFAULT_IMPORTED_MARKER
exiftool -r $=exifloglevel "${iffilter[@]}" -o "${importdir}"'/NODATE/'\
'-FileCreateDate<FileCreateDate'\
'-FileCreateDate<CreateDate'\
'-filename<${FileName}'\
'-filename<${FileCreateDate;DateFmt("%Y%m%d%H%M%S")}_NODATA_%f.%e'\
'-filename<${CreateDate;DateFmt("%Y%m%d%H%M%S")}_NODATA_%f.%e'\
'-filename<${CreateDate;DateFmt("%Y%m%d%H%M%S")}_'\
'${Model;s/\s/_/g;}_%f.%e'\
'-filename<${CreateDate;DateFmt("%Y%m%d%H%M%S")}_'\
'${Encoder;s/\s/_/g;}_%f.%e'\
'-filename<${CreateDate;DateFmt("%Y%m%d%H%M%S")}_'\
'${Model;s/\s/_/g;}_'\
'${CameraSerialNumber;$_=substr($_,-4);}_%f.%e'\
'-directory<'"${importdir}"'/${FileCreateDate;DateFmt("%Y")}/${FileCreateDate;DateFmt("%Y%m%d")}'\
'-directory<'"${importdir}"'/${CreateDate;DateFmt("%Y")}/${CreateDate;DateFmt("%Y%m%d")}'\
-if '$MIMEType=~/image/ or $MIMEType=~/video/'\
--ext lrv --ext thm --ext xmp --ext . --ext tar --ext gz --ext zip --ext dmg\
-api "${apifilter}"\
"${source}" || {
# exiftool reported one or more errors
exiftoolstatus=$?
_warning "exiftool reported one or more errors. Please check output."
}
_echo "Finished media import"
# Leave a marker
touch $source/$DEFAULT_IMPORTED_MARKER
}
function _process_media()
{
if [[ $validimported = false || $validexported = false ]] ; then
_error "Invalid imported and/or processed directory. Cannot proceed with processing."
exit 1
fi
importdir=$library/imported
processdir=$library/processed
_echo "Starting media processing..."
_info "ImportDir: "$importdir
_info "ProcessDir: "$processdir
_info "Process option: "$processopt
if [[ -n $copyright ]]; then
_info "Copyright: "$copyright
artist="-artist="${copyright}
author="-author="${copyright}
xmpcopyright="-xmp:copyright="${copyright}
fi
# Only process files that have changed since we last ran
# TODO: Needs to be hardened for various edge cases
# Right now this will skip files if eg a single manual edit happens in the
# processed tree or a processing run gets aborted.
if [[ $filter = false ]] ; then
# Get the latest modification date in the processdir
# zsh -c 'zmodload zsh/stat; stat +mtime -- **/*(.om[1])'
# -if '${FileModifyDate;DateFmt("%s")} gt '"\"$(stat -f %m temp)"\"...
lastprocess=$(stat +mtime -- ${processdir}/**/*(.om[1]))
_debug "Latest process timestamp: ${lastprocess}"
lastimport=$(stat +mtime -- ${importdir}/**/*(.om[1]))
_debug "Latest import timestamp: ${lastimport}"
if [[ $processopt == "all" ]]; then
_info "Requested processing: ${processopt}. Processing all files from ${importdir}"
elif [[ $processopt == *[0-9](y|m|w|d|H|M|S) ]]; then
_info " Processing the past ${processopt} of imported media files."
deltadate=$(date -v-${processopt} +%s)
_debug "Delta date: ${deltadate}"
iffilter+='-if4'
iffilter+='${FileModifyDate#;DateFmt("%s")} gt '${deltadate}
elif [[ -n $processopt ]]; then
_error "Unknown processing option: ${processopt} specified."
exit 1
elif [[ -n $lastprocess ]]; then
iffilter+='-if4'
iffilter+='${FileModifyDate#;DateFmt("%s")} gt '${lastprocess}
else
_info "Process dir ${processdir} is empty. Processing all files from ${importdir}"
fi
fi
# The following keywords and tags are being created and added in order to
# make our image files exif data accessible inside of Apple Photos and other
# Applications. By turning them into tags inside of Photos, they can be used
# to filter, sort or setup smart albums.
# Not every camera model and firmware supports all of these tags, hence the
# incremental additions that allow missing data to be omitted without error.
local exififd=()
exififd+=('-ExifIFD:LensMake-=')
exififd+=('-ExifIFD:LensMake<${Make;}')
exififd+=('-ExifIFD:LensModel-=')
exififd+=('-ExifIFD:LensModel<${Make;}')
exififd+=('-ExifIFD:LensModel<${Make;} - ${ExifIFD:FocalLength;} f/${ExifIFD:FNumber}')
# GPS keys needed for Apple Photos to recognize the location of a video
local gpsdata=()
gpsdata+=('-Keys:GPSCoordinates-=')
gpsdata+=('-Keys:GPSCoordinates<${GPSLatitude;}, ${GPSLongitude;}, 0')
# Add lineage data to the processed media files.
local xmpdata=()
# Need definied positions for entries that vary by processing pass
xmpdata+=('-XMP:PreservedFileName<P_${FileName;s/\.[^.]*$//}.${FileTypeExtension}') # Must be first entry
# Add tags for Apple Photos
local taglist=()
# HERO 10 jpg examples:
# [GoPro] DeviceName : Global Settings
# [GoPro] MetadataVersion : 8 1 4
# [GoPro] FirmwareVersion : H21.01.01.10.00
# [GoPro] CameraSerialNumber : C3461324698034
# [GoPro] Model : HERO10 Black
# [GoPro] AutoRotation : U
# [GoPro] DigitalZoom : N
# [GoPro] ProTune : Y
# [GoPro] WhiteBalance : AUTO
# [GoPro] Sharpness : MED
# [GoPro] ColorMode : GOPRO
# [GoPro] AutoISOMax : 3200
# [GoPro] AutoISOMin : 100
# [GoPro] ExposureCompensation : 0.0
# [GoPro] Rate : 1
# [GoPro] PhotoResolution : 20MP_N
# [GoPro] HDRSetting : S_HDR
# HERO 10 mp4 example:
# [GoPro] DeviceName : Global Settings
# [GoPro] MetadataVersion : 8 1 4
# [GoPro] FirmwareVersion : H21.01.01.10.00
# [GoPro] CameraSerialNumber : C3461324698034
# [GoPro] Model : HERO10 Black
# [GoPro] AutoRotation : U
# [GoPro] DigitalZoom : N
# [GoPro] ProTune : Y
# [GoPro] WhiteBalance : AUTO
# [GoPro] Sharpness : MED
# [GoPro] ColorMode : NATURAL
# [GoPro] AutoISOMax : 1600
# [GoPro] AutoISOMin : 100
# [GoPro] ExposureCompensation : 0.0
# [GoPro] Rate :
# [GoPro] FieldOfView : N
# [GoPro] ElectronicImageStabilization : HS Boost
# [GoPro] AudioSetting : AUTO
# [GoPro] DeviceName : Highlights
function _create_tag_list()
{
# exclude goprox version tag when testing to avoid changed files due to version numbering
if [ "$test" != true ]; then
taglist+=('-'$1'=GoProX: '${__version__})
fi
taglist+=('-'$1'+<Make: ${Make;s/\s/_/g;}')
taglist+=('-'$1'+<Camera: ${Model;s/\s/_/g;}')
taglist+=('-'$1'+<Camera: ${Model;s/\s/_/g;}_${CameraSerialNumber;$_=substr($_,-4);}')
taglist+=('-'$1'+<Software: ${Software;}')
taglist+=('-'$1'+<AutoRotation: ${AutoRotation;}')
taglist+=('-'$1'+<Orientation: ${Orientation;}')
taglist+=('-'$1'+<DigitalZoom: ${DigitalZoom;}')
taglist+=('-'$1'+<SceneCaptureType: ${SceneCaptureType;}')
taglist+=('-'$1'+<ProTune: ${ProTune;}')
taglist+=('-'$1'+<Sharpness: ${Sharpness;}')
taglist+=('-'$1'+<ColorMode: ${ColorMode;}')
taglist+=('-'$1'+<AutoISOMax: ${AutoISOMax;}')
taglist+=('-'$1'+<AutoISOMin: ${AutoISOMin;}')
taglist+=('-'$1'+<MeteringMode: ${MeteringMode;}')
taglist+=('-'$1'+<GainControl: ${GainControl;}')
taglist+=('-'$1'+<Contrast: ${Contrast;}')
taglist+=('-'$1'+<Saturation: ${Saturation;}')
taglist+=('-'$1'+<WhiteBalance: ${WhiteBalance;}')
taglist+=('-'$1'+<PhotoResolution: ${PhotoResolution;}')
taglist+=('-'$1'+<HDRSetting: ${HDRSetting;}')
taglist+=('-'$1'+<ExposureCompensation: ${ExposureCompensation;}')
taglist+=('-'$1'+<FieldOfView: ${FieldOfView;}')
taglist+=('-'$1'+<FieldOfView: ${FieldOfView;}')
taglist+=('-'$1'+<ExposureLockUsed: ${ExposureLockUsed;}')
taglist+=('-'$1'+<ProjectionType: ${ProjectionType;}')
taglist+=('-'$1'+<ImageStabilization: ${ElectronicImageStabilization;}')
taglist+=('-'$1'+<AudioSetting: ${AudioSetting;}')
}
# Now populate tag lists...
_create_tag_list 'XMP:Subject'
_create_tag_list 'IPTC:Keywords'
# _create_tag_list 'ItemList:Keyword'
# _create_tag_list 'Quicktime:Keywords'
# Additional Quicktime tags for movies
local quicktimedata=()
quicktimedata+=('-Keys:Make<${Make;}')
quicktimedata+=('-Keys:Model<${Model;}')
# quicktimedata+=('-Keys:Information=My Information')
# quicktimedata+=('-Keys:Description=My Description')
# quicktimedata+=('-Keys:Keywords="GoProX:'${__version__}'","Make:MyGoPro"')
# Additional data...
#
# Inspect raw GPS data:
# exiftool -s -a '-gps*' -n -G FILE
#
# To consider adding for timeshift functionality...
# 0x882a TimeZoneOffset int16s[n] ExifIFD (1 or 2 values: 1. The time zone offset of DateTimeOriginal from GMT in hours, 2. If present, the time zone offset of ModifyDate)
# 0x9011 OffsetTimeOriginal string ExifIFD (time zone for DateTimeOriginal)
# First pass - exlude mp4 and 360 files
_echo "First pass: 1/4 - All files but mp4 and 360"
# exiftool -r -F -sep ", " -q -q -progress -addTagsFromFile @ -o "${processdir}"'/NODATE/'\
exiftool -r -F -sep ", " $=exifloglevel "${iffilter[@]}" -addTagsFromFile @ -o "${processdir}"'/NODATE/'\
'-FileCreateDate<FileCreateDate'\
'-FileCreateDate<CreateDate'\
'-filename<P_%f.${FileTypeExtension}'\
'-directory<'"${processdir}"'/${FileType}/${FileCreateDate;DateFmt("%Y")}/${FileCreateDate;DateFmt("%Y%m%d")}'\
'-directory<'"${processdir}"'/${FileType}/${CreateDate;DateFmt("%Y")}/${CreateDate;DateFmt("%Y%m%d")}'\
"${artist}"\
"${author}"\
"${xmpcopyright}"\
"${exififd[@]}"\
"${taglist[@]}"\
"${xmpdata[@]}"\
--ext mp4 --ext 360\
-api "${apifilter}"\
-api largefilesupport=1\
"${importdir}" || {
# exiftool reported one or more errors
exiftoolstatus=$?
if [[ $exiftoolstatus = 2 ]]; then
_warning "First pass: No files processed by exiftool."
else
_warning "First pass: exiftool reported one or more errors. Please check output."
fi
}
# Second pass - only mp4 files
# Need to apply different logic for various tags
_echo "Second pass: 2/4 - Only mp4 files"
# exiftool -r -F -sep ", " -q -q -progress -addTagsFromFile @ -o "${processdir}"'/NODATE/'\
exiftool -r -F -sep ", " $=exifloglevel "${iffilter[@]}" -addTagsFromFile @ -o "${processdir}"'/NODATE/'\
'-FileCreateDate<FileCreateDate'\
'-FileCreateDate<CreateDate'\
'-filename<P_%f.${FileTypeExtension}'\
'-directory<'"${processdir}"'/${FileType}/${FileCreateDate;DateFmt("%Y")}/${FileCreateDate;DateFmt("%Y%m%d")}'\
'-directory<'"${processdir}"'/${FileType}/${CreateDate;DateFmt("%Y")}/${CreateDate;DateFmt("%Y%m%d")}'\
"${artist}"\
"${author}"\
"${xmpcopyright}"\
"${exififd[@]}"\
"${taglist[@]}"\
"${gpsdata[@]}"\
"${quicktimedata[@]}"\
"${xmpdata[@]}"\
-ext mp4\
-api "${apifilter}"\
-api largefilesupport=1\
-api QuickTimeHandler=1\
"${importdir}" || {
# exiftool reported one or more errors
exiftoolstatus=$?
if [[ $exiftoolstatus = 2 ]]; then
_warning "Second pass: No files processed by exiftool."
else
_warning "Second pass: exiftool reported one or more errors. Please check output."
fi
}
# Third pass - only 360 files
# Need to apply different logic for various tags and sort into 360 subtree
_echo "Third pass: 3/4 - Only 360 files"
# Override - File name pattern is different for 360 media
xmpdata[1]='-XMP:PreservedFileName<P_${FileName;s/\.[^.]*$//}.360'
# exiftool -r -F -sep ", " -q -q -progress -addTagsFromFile @ -o "${processdir}"'/NODATE/'\
exiftool -r -F -sep ", " $=exifloglevel "${iffilter[@]}" -addTagsFromFile @ -o "${processdir}"'/NODATE/'\
'-FileCreateDate<FileCreateDate'\
'-FileCreateDate<CreateDate'\
'-filename=P_%f.%e'\
'-directory<'"${processdir}"'/%e/${FileCreateDate;DateFmt("%Y")}/${FileCreateDate;DateFmt("%Y%m%d")}'\
'-directory<'"${processdir}"'/%e/${CreateDate;DateFmt("%Y")}/${CreateDate;DateFmt("%Y%m%d")}'\
"${artist}"\
"${author}"\
"${xmpcopyright}"\
"${exififd[@]}"\
"${taglist[@]}"\
"${gpsdata[@]}"\
"${quicktimedata[@]}"\
"${xmpdata[@]}"\
-ext 360\
-api "${apifilter}"\
-api largefilesupport=1\
-api QuickTimeHandler=1\
"${importdir}" || {
# exiftool reported one or more errors
exiftoolstatus=$?
if [[ $exiftoolstatus = 2 ]]; then
_warning "Third pass: No files processed by exiftool."
else
_warning "Third pass: exiftool reported one or more errors. Please check output."
fi
}
# Forth pass - timeshift gopro video files
# To eliminate issues with Apple & Google photos we need to convert the QuickTime date/time
# fields into UTC. Since GoPro records those fields in local time of the camera, we need to
# leverage the GPSDateTime to calculate the approx DST offset and then shift all the
# QuickTime tags by that amount.
_echo "Forth pass: 4/4 - Only mp4 & 360 files - timeshift QuickTime to UTC"
# exiftool -r -wm w -ee -d '%s' -q -q -progress -P -overwrite_original_in_place\
exiftool -r -wm w -ee -d '%s' $=exifloglevel "${iffilter[@]}" -P -overwrite_original_in_place\
'-quicktime:time:all<${GPSDateTime;$_=$self->GetValue("CreateDate")+'\
'int((($_-$self->GetValue("CreateDate"))/3600)+(($_-$self->GetValue("CreateDate"))/3600)/'\
'abs((($_-$self->GetValue("CreateDate"))/3600)*2 || 1))*3600}'\
-ext mp4 -ext 360\
-api "${apifilter}"\
-api largefilesupport=1\
-api QuickTimeHandler=1\
-api TimeZone=GMT\
"${processdir}" || {
# exiftool reported one or more errors
exiftoolstatus=$?
if [[ $exiftoolstatus = 2 ]]; then
_warning "Forth pass: No files processed by exiftool."
else
_warning "Forth pass: exiftool reported one or more errors. Please check output."
fi
}
_echo "Finished media processing"
}
function _geonames_media()
{
if [[ $validimported = false ]] ; then
_error "Invalid imported directory. Cannot proceed with geonames task."
exit 1
fi
importdir=$library/imported
_echo "Starting GeoNames processing..."
_info "Library: "$library
_info "ImportDir: "$importdir
_info "GeoNames account: "$geonamesacct
# case independent globing
unsetopt CASE_GLOB
ndir=0
ngeo=0
for d in ${importdir}/**/; do # all subdirectories of import
if [[ $d =~ .*/[0-9]{8} ]]; then # only those that match an 8 digit date
if [[ ! -f "${d}${geonamesfile}" ]]; then
_info "Processing "$d
((ndir++))
# Find first media file with valid gps exif data
_debug "Filetypes: "$filetypes
# for file in "$d"*.(JPG|MP4|360|JPEG|HEIC)(N); do
for file in "$d"*.($~filetypes)(N); do
_info "Media file: "$file
# Get GPS info from file
# @todo Add exiftool error handling
# @body Need to test exiftool for errors
gpsdata=$(exiftool -n -q -q \
-p 'lat=$gpslatitude&lng=$gpslongitude' "$file" | head -n 1)
_debug "GPS Data: "$gpsdata
# Check if gpsdata is empty = no match for the simplified GPS tag search
if [[ -z $gpsdata ]]; then
gpsdata=$(exiftool -n -ee -q -q -p 'lat=$gpslatitude&lng=$gpslongitude' "$file" | head -n 1)
_debug "Extended GPS Data: "$gpsdata
fi
if [[ -n $gpsdata ]]; then
geonamesdata=$(curl -s 'http://api.geonames.org/timezoneJSON?'${gpsdata}'&username='${geonamesacct})
_debug "GeoNames Data: "$geonamesdata
_info "Writing GeoNames file: ${d}${geonamesfile}"
# Add our current file as reference
# @todo Add geonames error handling
# @body Add check if geonames call resulted in valid geonames data, at the minimum that it is not empty
echo $geonamesdata | jq ". + {reference: \"${file}\"}">${d}${geonamesfile}
((ngeo++))
# Delay subsequent geonames calls to stay within free geonames account limits
sleep 2
break
fi
done
fi
fi
done
_info "$ndir directories processed."
_info "$ngeo GeoNames files created."
_echo "Finished GeoNames processing"
}
function _timeshift_media()
{
if [[ $validimported = false || $validexported = false ]] ; then
_error "Invalid imported and/or processed directory. Cannot proceed with processing."
exit 1
fi
importdir=$library/imported
processdir=$library/processed
# TODO: Implement timeshift functionality
geooffset=$(TZ=Europe/Vienna date -j -f "%Y%m%d" "20200601" "+%z")
_debug "GeoOffset: "$geooffset
# /TODO
}
function _archive_media()
{
if [[ $validarchive = false ]] ; then
_error "Invalid archive directory. Cannot proceed with archive."
exit 1
fi
archivedir=$library/archive
_echo "Starting media archive..."
_info "Source: $source ($(realpath $source))"
_info "Library: $archivedir ($(realpath $archivedir))"
# Remove previous archive marker
rm -f $source/$DEFAULT_ARCHIVED_MARKER
# Check if this is a GoPro storage card
if [[ -f "$source/MISC/version.txt" ]]; then
# Extract camera model and firmware version
# Due to some broken version.txt files for some models and firmware versions
# we have to apply a rather complicated looking fix: remove comma from the
# end of the second to last line in the file:
# sed -e x -e '$ {s/,$//;p;x;}' -e 1d ./MISC/version.txt
# Otherwise we could simply cat
# camera=$(cat MISC/version.txt | jq '."camera type"')
# camera=$(sed -e x -e '$ {s/,$//;p;x;}' -e 1d ./MISC/version.txt | jq '."camera type"')
camera=$(sed -e x -e '$ {s/,$//;p;x;}' -e 1d $source/MISC/version.txt | jq -r '."camera type"')
serial=$(sed -e x -e '$ {s/,$//;p;x;}' -e 1d $source/MISC/version.txt | jq -r '."camera serial number"')
timestamp=$(date +%Y%m%d%H%M%S)
_info "Camera: "${camera}
_info "Serial: "${serial:(-4)}
_info "Time: "$timestamp
archivename=${timestamp}_${camera// /_}_${serial:(-4)}
_info "Archive: "$archivename
tar --totals --exclude='.Spotlight-V100' --exclude='.Trash*' --exclude='.goprox.*' \
-zcvf "${archivedir}"/"${archivename}".tar.gz $source || {
# Archive failed
_error "Archive creation failed!"
exit 1
}
else
_error "Cannot verify that $(realpath ${source}) is a GoPro storage device"
_error "Missing $(realpath ${source})/MISC/version.txt"
exit 1
fi
_echo "Finished media archive"
# Leave a marker
touch $source/$DEFAULT_ARCHIVED_MARKER
}
function _clean_media()
{
_echo "Cleaning Source Media..."
_info "Source: $source ($(realpath $source))"
# Remove previous clean marker
rm -f $source/$DEFAULT_CLEANED_MARKER
# Check if this is a GoPro storage card
if [[ -f "$source/MISC/version.txt" ]]; then
# Only proceed if we just finished archiving or importing this media
if [ "$archive" = true ] || [ "$import" = true ]; then
# One more check to make sure any prior step did not result in an exiftool error
_debug "exiftool status: $exiftoolstatus"
if (( $exiftoolstatus )) then
_error "Will not clean ${source} ($(realpath $source)) due to exiftool error status: ${exiftoolstatus}"
_error "Please check output."
exit 1
fi
if [ -e "$source/DCIM" ]; then
_debug "Removing $source/DCIM"
rm -rfv $source/DCIM || {
# Cleanup failed
_error "Cleaning ${source} ($(realpath $source)) failed!"
exit 1
}
fi
for xfile in $source/mdb*(N); do
_debug "Removing $xfile"
rm -rfv $xfile || {
# Cleanup failed
_error "Cleaning ${source} failed!"
exit 1
}
done
else
_error "Will not clean ${source} ($(realpath $source)) without prior archive or import"
_error "Run options --archive or --import and --clean together"
exit 1
fi
else
_error "Will not clean ${source} ($(realpath $source)) cannot verify it is a GoPro storage device"
_error "Missing $source/MISC/version.txt ($(realpath $source)/MISC/version.txt)"
exit 1
fi
_echo "Finished cleanup tasks"
# Leave a marker
touch $source/$DEFAULT_CLEANED_MARKER
}
function _firmware()
{
_echo "Checking firmware..."
_info "Source: $source ($(realpath $source))"
# Check if this is a GoPro storage card
if [[ -f "$source/MISC/version.txt" ]]; then