-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexopus
executable file
·894 lines (744 loc) · 36.1 KB
/
indexopus
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
#!/bin/bash
# depends: opustags, ffmpeg/ffprobe, mediainfo
# config: "$HOME/.config/indexopus.conf"
# absserver="https://web.address.com"
# abssqlite="/path/to/location/of/config/absdatabase.sqlite"
# files must be in the format of Title -- Part ##: Chapter Title.opus and present ONLY works for .opus; there are other tools for e.g., m4b: use them.
# presumably, this script could easily be changed out for another codec, however opustags would need to change to something else that can write metadata, e.g, ffmpeg which should be able to do any format.
# that said, the author feels that this satisfices for the purposes at hand and if/when the codec changes, that bridge will be burnt when it is arrived upon.
# Would like to make it so that the files do not need a chapter name and are iterated with 000, 001, 002, .... for Chapter Title
# ffmpeg could presumably take over for opustags to eliminate that dependency and then all that would be required is ffmpeg
# Also, given that tagging is being done, it might be useful to tag at least the tracknumber and the track title in this script rather than doing it after.
# ffprobe -sexagesimal -> "00:00:00.00"
#
# Promlem with colons in the part description:
# That could still indicate a problem if the code is later attempting to do shell arithmetic on the value, in which case you got lucky by having printf throw an error. You could fix that by adding a test and failing early, because printf won't cause the script to exit.
# https://mywiki.wooledge.org/BashFAQ/054 -- How can I tell whether a variable contains a valid number?
shopt -s extglob nullglob dotglob
scriptpath=$(realpath "$0")
scriptname="${scriptpath##*\/}"
confpath="$HOME/.config/indexopus.conf"
. "$confpath" #this needs to move.
. "$HOME/bin/gits/indexopus/indexopus.lib"
ulon="$(tput smul)" #underline on
uloff="$(tput rmul)" #underline off
iton="$(tput sitm)" #italics on
itoff="$(tput ritm)" #italics off
red="$(tput setaf 9)" #red fg
white="$(tput setaf 15)" #white fg
tput0="$(tput sgr0)" #reset tput changes
bold="$(tput bold)" #bold on
relipsis="$red..."
stamp="$(date +%s)" #sets datecode for all of indexopus - could use info from m4b2opus later
tmp="/tmp/indexopus-$stamp" #this could change based on info from m4b2opus
remove_mp4tags=("major_brand" "minor_version" "compatible_brands" "encoded_by" 'OverDrive MediaMarkers' "handler_name" "vendor_id")
####this needs to be done better, but for now if the dependencies aren't here, i want it to just exit the script
! command -v opustags > /dev/null && sudo apt install opustags
! command -V opustags > /dev/null && { echo "opustags missing; exit 1"; exit 1; }
editscript(){
local script path; script="${scriptpath##*/}"; path="${scriptpath%/*}"; swp="$path/.$script.swp"
if [[ ! -e "$swp" ]]; then printf "\n\n%s\n\n" "$swp"; (/usr/bin/nano "$scriptpath"); exit
else printf "\n%s is already being edited.\n%s exists; try fg or look in another window.\n" "$scriptpath" "$swp"; exit;
fi; }
##--> editscript() <--#################################################################################
pause(){ read -p "$*" ; }
##--> pause() <--######################################################################################
usage() {
echo "Usage: $0 [-e] [-y] [-t <title>] [-s <timestamp>] [-m <temp path>] [-c <config path>] [-r] [-h]"
echo "Options:"
echo " -e, --edit Call editscript function"
echo " -y, -f, --force Accept all prompts if the times line up"
echo " -t, --title <title> Specify title"
echo " -s, --stamp <timestamp> Specify timestamp"
echo " -m, --tmp <temp path> Specify temporary path"
echo " -c, --config <config path> or blank for default location: $HOME/.config/indexopus.conf"
echo " -r, --reindex, reindex Reindex the file"
echo " -h, --help Display this help message"
exit 1 ; }
##--> usage() <--######################################################################################
confirm(){
local ans IFS=
while read -rp "$1" -n1 ans
do
printf '\n'
case "$ans" in
[Yy]) return 0;;
[Nn]) return 1;;
esac
done
}
##--> confirm() <--###################################################################################
#unused
#tagtt(){
# for i in *\ --\ Part\ ??\:\ *opus
# do
# title="${i%.opus}"
# title="${title#* -- }"
# tracknumber="${i%:*}"
# tracknumber="${tracknumber#*Part }"
# opustags -i "$i" -s title="$title" -s tracknumber="$tracknumber"
# done
#}
##--> tagtt() <--######################################################################################
rmyn(){
while true
read -rp "$1" rmyn
do
case "$rmyn" in
[yY] ) "${@:3}"; rmynres=0; break;;
[nN] ) printf '\n%s\n' "$2"; rmynres=1; break;;
* ) printf "Invalid response...\n";;
esac
done
}
##--> rmyn() <--#######################################################################################
#yn(){
# while true
# read -p "$1" yn
# do
# case "$yn" in
# [yY] ) "$2"; break;;
# [nN] ) "$3"; break;;
# * ) printf "Invalid response...\n";;
# esac
# done
#}
##--> yn() <--#########################################################################################
#is_even() {
# if [ $(( $1 % 2 )) -eq 0 ]; then return 0
# else return 1; fi
#}
##--> is_even() <--####################################################################################
gettitle(){
[[ ! -n "$title" ]] && titles=(*Part\ ??*.opus) && title="${titles[0]% -- Part*}"
ititle="${iton}$title${itoff}"
output="$title -- Audiobook.opus"
ioutput="$ititle -- Audiobook.opus"
}
##--> gettitle() <--###################################################################################
createindex(){
chno=0
for i in "$title -- Part "*.opus
do
chna="${i#* -- Part }"; chna="${chna%.opus}"; chna="${chna#*: }"
[[ "$chna" = @(Chapter|Part)\ ? || "$chna" = @(Chapter|Part)\ ?\ * ]] && chna="${chna/ / 0}"
if [[ "$t" != 0 ]]; then
ts=$(echo "$t" | perl -nle '/([0-9\.]+)/ && ($t +=$1) && printf "%02d:%02d:%06.03f\n", $t/3600, $t/60%60, $t%60 + $t-int($t)' | tail -n 1)
printf 'CHAPTER%03d=%s\n' "$chno" "$ts" >> "$tmp/opusindex"
printf 'CHAPTER%03dNAME=%s\n' "$chno" "$chna" >> "$tmp/opusindex"
createdindex+=( "$i" )
createdindex+=( "$(printf 'CHAPTER%03d=%s' "$chno" "$ts")" )
createdindex+=( "$(printf 'CHAPTER%03dNAME=%s' "$chno" "$chna")" )
rawindex+=( "$ts" )
rawindex+=( "$chna" )
else
ts="00:00:00.000"
printf 'CHAPTER%03d=%s\n' "$chno" "$ts" >> "$tmp/opusindex"
printf 'CHAPTER%03dNAME=%s\n' "$chno" "$chna" >> "$tmp/opusindex"
createdindex+=( "$i" )
createdindex+=( "$(printf 'CHAPTER%03d=%s' "$chno" "$ts")" )
createdindex+=( "$(printf 'CHAPTER%03dNAME=%s' "$chno" "$chna")" )
rawindex+=( "$ts" )
rawindex+=( "$chna" )
fi
d=$(ffprobe -v error -show_entries format=duration -of default=nk=1:nw=1 "$i")
# d=$(mplayer -vo dummy -ao dummy -identify "$i" 2>/dev/null | perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "$t"' | tail -n 1)
t=$(echo "$d + $t" | bc)
((chno++))
done
#ffmpeg will not take filenames with ' in them, they must be quoted:
#check index for single quotes:
for f in @("$title -- Part "??\:\ *.opus|"$title -- Part "???\:\ *.opus)
do
if [[ "$PWD/$f" == *\'* ]]
then
ff="$f"; dir="$PWD"
[[ "$f" == *\'* ]] && ff="${f//\'/\'\\\'\'}" || ff="$f"
[[ "$PWD" = *\'* ]] && dir="${PWD//\'/\'\\\'\'}"
echo "file '$dir/$ff'" >> "$tmp/opusfiles"
else
echo "file '$PWD/$f'" >> "$tmp/opusfiles"
fi
done
}
##--> createindex() <--################################################################################
##
## Need to check metadata.json files to see if the keys match up with the abs pattern...
## Need to check chapter.json files for `{"error":"Chapters not found"}`
##
itemid_pwd(){
local itempwd="${1:-"${PWD}"}}"
sqlitepwd="${PWD//\'/\'\'}"
}
reindex(){
local t chap_title chap_starts reintitle
t=0
chno=0
if [[ ! -f "chapters.json" ]]; then
if confirm "${bold}No chapters.json; retrieve chapter info from the web? ${tput0}"; then
curl -X POST "$absserver/api/items/$(itemid)/scan" -H "Authorization: Bearer $abstoken" -sSo /dev/null
curl "$absserver/api/search/chapters?asin=$(jq -r '.asin' metadata.json)" -H "Authorization: Bearer $abstoken" -sSo chapters.json
newchapters=true
fi
fi
if [[ -f "chapters.json" ]] && [[ ! $(grep '{"error":"Chapters not found"}' "chapters.json") ]]; then
readarray -t chap_titles < <(jq -r '.chapters[] | .title' "chapters.json" 2>/dev/null)
readarray -t chap_starts < <(jq -r '.chapters[] | .startOffsetMs' "chapters.json" 2>/dev/null)
for ((i=0; i<"${#chap_starts[@]}"; i++)); do
sec=$(( chap_starts[i] / 1000 ))
ms=$(( chap_starts[i] % 1000 ))
chap_starts[i]="${sec}.${ms}"
done
else
readarray -t chap_titles < <(jq -r '.chapters[] | .title' "metadata.json" 2>/dev/null)
readarray -t chap_starts < <(jq -r '.chapters[] | .start' "metadata.json" 2>/dev/null)
fi
[[ ! "${chap_titles[@]}" ]] || [[ ! "${chap_starts[@]}" ]] &&
printf 'Error with %s/metadata.json; check and retry.\nexit 1' "$PWD" &&
exit 1
reintitle=( *\ --\ Audiobook.opus )
[[ ! "${#reintitle[@]}" -eq 1 ]] && printf 'No suitable audiobook found in pwd of format * -- Audiobook.opus\nCheck path %s and try again.\nexit 1' "$PWD" && exit 1
for ((chno=0;chno<"${#chap_titles[@]}";chno++))
do
t="${chap_starts[$chno]}"
# pause "${chap_starts[0]} $t"
if [[ "$t" != @(0|0.0) ]]; then
ts=$(echo "$t" | perl -nle '/([0-9\.]+)/ && ($t +=$1) && printf "%02d:%02d:%06.03f\n", int($t / 3600), int($t / 60) % 60, $t % 60 + ($t - int($t))' | tail -n 1)
chna="${chap_titles[$chno]}"
[[ "$chna" = *@(Part|Chapter)\ ? ]] && chna="${chna/ / 0}"
printf 'CHAPTER%03d=%s\n' "$chno" "$ts" >> "$tmp/opusindex"
printf 'CHAPTER%03dNAME=%s\n' "$chno" "$chna" >> "$tmp/opusindex"
rawindex+=( "$ts" )
rawindex+=( "$chna" )
createdindex+=( "$(printf 'CHAPTER%03dNAME=%s' "$chno" "$chna")" )
createdindex+=( "$chno" )
createdindex+=( "$(printf 'CHAPTER%03d=%s' "$chno" "$ts")" )
createdindex+=( "$(printf 'CHAPTER%03dNAME=%s' "$chno" "$chna")" )
else
ts="00:00:00.000"
chna="${chap_titles[$chno]}"
[[ "$chna" = *@(Part|Chapter)\ ? ]] && chna="${chna/ / 0}"
printf 'CHAPTER%03d=%s\n' "$chno" "$ts" >> "$tmp/opusindex"
printf 'CHAPTER%03dNAME=%s\n' "$chno" "$chna" >> "$tmp/opusindex"
rawindex+=( "$ts" )
rawindex+=( "$chna" )
createdindex+=( "$chno" )
createdindex+=( "$(printf 'CHAPTER%03d=%s' "$chno" "$ts")" )
createdindex+=( "$(printf 'CHAPTER%03dNAME=%s' "$chno" "$chna")" )
fi
done
mediainfo "$reintitle"
printf '%s%sProposed index for %s:%s%s\n' "$red" "$bold" "$reintitle" "${tput0}" "$bold"
printf '%s\t\t\t\t : %s\n' "${rawindex[@]}"
# printf '%s : %s\n' "${rawindex[@]}"
itemid_pwd
readarray -t itemids < <( sqlite3 "$abs_sqlite" "select id FROM libraryitems WHERE path=='$sqlitepwd';" )
if (( ${#itemids[@]} > 1 )); then
printf '\n%s%saudiobookself reports more than one matching title; investigate: %s\n' "$red" "$bold" "$tput0"
for itemid in "${itemids[@]}"; do
printf '%s/item/%s\n' "$absserver" "$itemid"
done
else
printf '%s\n%sThis index was generated from existing %s;\n' "$tput0" "$relipsis" "$jsonfile"
[[ "$itemids" ]] && printf '...look up new chapter information at\ngoogle-chrome %s/audiobook/%s/chapters\n\n\n' "$absserver" "$itemids"
[[ ! "$itemids" ]] && printf '%s%s not found in absdatabase.sqlite!%s\n%sCheck path and metadata.json file\n\n\n' "$bold" "$PWD" "$tput0" "$red"
if [[ "$rmmatch" = true ]]; then
writeindex "$reintitle"
[[ "$newchapters" = true ]] && curl -X POST "$absserver/api/items/$(itemid)/scan" -H "Authorization: Bearer $abstoken"
elif confirm "${bold}${red}Apply index? ${tput0}"; then
writeindex "$reintitle"
[[ "$newchapters" = true ]] && curl -X POST "$absserver/api/items/$(itemid)/scan" -H "Authorization: Bearer $abstoken"
rmmatch=true #at this point, having said yes to apply index, yes the rest of the way.
else
mediainfo "$reintitle"
printf '%s\t\t\t\t : %s\n' "${rawindex[@]}"
if confirm "Would you like to start over so you can look up chapter information in audiobookshelf? "; then
indexopus reindex
exit
else
printf 'Not reindexing opus file with above index; exiting.'
exit
fi
fi
fi
mediainfo *Audiobook.opus
rm -rf "$tmp"
}
##reindex()####################################################################################
writeindex(){
local output="$1" mp4grep mp4opustags chaptag tags ck4tags args
[[ ! "$remove_mp4tags" ]] &&
remove_mp4tags=("major_brand" "minor_version" "compatible_brands" "encoded_by" "OverDrive MediaMarkers")
#pause "$(printf %s\\n "${remove_mp4tags[@]}")"
#this works, why won't it work in the array?
# opustags -d "OverDrive MediaMarkers" -i "$output"
if [[ "$(opustags "$output")" = *CHAPTER* ]]
then
printf '\n%s%s%s contains existing tags; removing...%s\n' "$relipsis" "$bold" "$title" "$tput0"
tags=( $(opustags "$output") )
tags=( $(printf -- '-d%s\n' "${tags[@]%=*}"|\grep CHAPTER|sort -u) )
printf '\n%smediainfo of existing %s:%s\n' "$relipsis" "$output" "$tput0"
mediainfo "$output"
printf '\n%sremoving exiting CHAPTER tags with opustags...%s\n\n' "$relipsis" "$tput0"
opustags "${tags[@]}" -i "$output"
ck4tags=( "$(opustags "$output" | grep --color=always -i chapter)" ) &&
printf 'Error!\nCHAPTER tags still present in opus file.\n%s' "${ck4tags[@]}" &&
exit
else
printf '%smediainfo of existing %s:%s\n' "$relipsis" "$output" "$tput0"
mediainfo "$output"
fi
while read -r chaptag
do
args+=(-a "$chaptag"\ )
done < "$tmp/opusindex"
opustags -i "$output" "${args[@]}"
printf '%sChapter info added...\n%s' "$relipsis" "$tput0"
printf '%sStripping MP4 tags%s\n%s' "$relipsis" "$relipsis" "$tput0"
# [[ "$rmmatch" != 'true' ]] && ####why the fuck is this here?
mp4grep="$(IFS=\|; echo "${remove_mp4tags[*]}")"
# This is method one to remove the unwanted mp4 tags:
readarray -t mp4opustags -- < <(printf -- '-d\n%s\n' "${remove_mp4tags[@]}")
mp4opustags+=(-i "$output")
[[ $( opustags "$output" |grep -E "$mp4grep" ) ]] && opustags "${mp4opustags[@]}"
# This is method two to remove the unwanted mp4 tags...
# Both of them work, but I couldn't get the first one to work so I wrote this one
# Keeping for reference for a while since this is such a fucking pain in the ass.
if [[ $( opustags "$output" |grep -E "$mp4grep" ) ]]; then
for i in "${remove_mp4tags[@]}"; do
mp4args+=(-d "$i")
done
mp4args+=(-i "$output") # Should I also use readarray here? difference?
opustags "${mp4argss[@]}"
fi
}
##--> writeindex() <--#################################################################################
rename() {
ext=opus #local?
declare -A confirm_rename
declare -A parts
local hundreds width length
mvopus() {
max_length=0
width=$(tput cols)
for i in "${confirm_rename[@]}"; do
rnlength="${#i}"
if (( rnlength > max_length )); then
max_length=$rnlength
fi
done
length=$((${#i} + max_length + 10))
offset=$(( width - max_length - 2 ))
for i in "${!confirm_rename[@]}"; do
if (( length > width )); then
# printf '%s %s---->%s\n %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
for key in "${!confirm_rename[@]}"; do break; done
if [[ "$key" =~ .+\ -\ .+\.opus && ! "$key" =~ .+\ --\ .+\.opus ]]; then
printrn+=( "$(printf ' %s %s---->%s %s%s\n%s' "${i##* - }" "$bold" "$tput0" "$red" "${confirm_rename["$i"]##* -- }" "$tput0")" )
else
printrn+=( "$(printf ' %s %s---->%s %s%s\n%s' "${i##* -- }" "$bold" "$tput0" "$red" "${confirm_rename["$i"]##* -- }" "$tput0")" )
# printrn1+=( "$(printf '%s %s---->%s\n%*s%s%s\n%s' "$i" "$bold" "$tput0" "$offset" "" "$red" "${confirm_rename["$i"]}" "$tput0")" )
fi
else
unset printrn1 printrn2
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
fi
done
# [[ "$printrn1" ]] && printf %s\\n "${printrn1[@]}"
(( length > width )) && printf '%s --\n' "${opusarray[0]% -- *}"
[[ "$printrn" ]] && printf %s "${printrn[@]}"
echo
[[ "$rmmatch" = true ]] || confirm "${bold}Continue with Proposed Rename (y/n) ${tput0}" &&
for i in "${!confirm_rename[@]}"; do
mv "$i" "${confirm_rename["$i"]}"
done || exit 1
} #end of mvopus
##############
if [[ "$opusarray" =~ .+\ --\ ((C|c)hapter|(P|p)art|(D|d)isc)\ [[:digit:]]{1,3}\.opus ]]; then
echo "Using rename pattern 1."
for i in "${opusarray[@]}"; do
n="${i%.opus}"; n="${n##* }"
[[ "$n" =~ \ [[:digit:]]\.opus ]] && n="0$n"
title="${i% -- *}"
order="${i##* -- }"
newname="${i/ -- @(@(p|P)art|@(c|C)hapter|@(d|D)isc) */ -- Part $n: Part $n.opus}"
confirm_rename["$i"]="$newname"
done
mvopus
elif [[ "$opusarray" =~ .+\ -\ ((C|c)hapter|(P|p)art|(D|d)isc)\ [[:digit:]]{1,3}\.opus ]]; then
echo "Using rename pattern 2."
for i in "${opusarray[@]}"; do
n="${i%.opus}"; n="${n##* }"
# [[ "$n" =~ \ [[:digit:]]\.opus ]] && n="0$n" #this won't work, .opus was removed but the logic's wrong too
(( "${#n}" == 1 )) && n="0$n"
title="${i% - *}"
order="${i##* - }"
newname="${i/ - @(@(P|p)art|@(c|C)hapter|@(d|D)isc) */ -- Part $n: Part $n.opus}"
confirm_rename["$i"]="$newname"
done
mvopus
elif [[ "${opusarray[@]}" =~ .+-(p|P)art[[:digit:]]{1,3}\.opus ]]; then
echo "Using rename pattern 3."
# for i in *-Part??.opus; do
for i in "${opusarray[@]}"; do
n="${i%.opus}"; n="${n##*-Part}"
[[ "$n" =~ [[:digit:]] ]] && n="0$n"
newname="${i/-@(p|P)art/ -- Part $n: Part }"
confirm_rename["$i"]="$newname"
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
elif [[ "$opusarray" = .+\ Part\ [[:digit:]]{1,3}\.opus ]]; then
echo "Using rename pattern 4."
# this is logic to add double or triple digits to all the part numbers.
for i in "${opusarray[@]}"; do n="${i%.opus}"; n="${n##* }"; parts["$i"]="$n"; done
(( "$(printf %s\\n "${parts[@]}"|sort|tail -n1)" > 99 )) && hundreds=true
#
for i in "${opusarray[@]}"; do
n="${i%.opus}"; n="${n##* }"; [[ "$hundreds" = true ]] && n="$(printf %03d "$n")" || n="$(printf %02d "$n")"
newname="${i% *}"; newname="${newname% @(p|P)art*} -- Part $n: Part $n.opus"
confirm_rename["$i"]="$newname"
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
elif [[ "${opusarray[@]}" =~ .+[[:space:]]-[[:space:]][[:digit:]]{1,3}\.opus ]]; then
echo "Using rename pattern 5."
regex=".+[[:space:]]-[[:space:]][[:digit:]]{1,3}\.opus"
for i in *\ -\ @(?|??|???).opus; do
n="${i%.opus}"; n="${n##* - }"
(( 10#$n < 10 ))
[[ $n =~ ^[0-9]+$ ]] || pause "There's probably a problem, here's the value of \$n: $n"
newname="${i/ - / -- Part $n: Part }"
confirm_rename["$i"]="$newname"
# printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
elif [[ "${opusarray[@]}" =~ .+[[:space:]][[:digit:]]{1,3}\.opus ]]; then
echo "Using rename pattern 6:"
regex=".+[[:space:]][[:digit:]]{1,3}\.opus"
for i in "${opusarray[@]}"; do
n="${i##* }"; n="${n%.opus}"; (( "${#n}" < 2 )) && n="0$n"
newname="${i% *}"; newname="$newname -- Part $n: Part $n.opus"
confirm_rename["$i"]="$newname"
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
###############################################################################################################
## The above pattern search fails on file names with this pattern. This would, in theory, be pretty hard
## to come up with a regex for without somehow checking for those digits at the beginning.
## it is a terrible naming format and hopefully will not be run across much. Regardless,
## THE CURRENT SCRIPT CANNOT ACCOMIDATE THIS FILE PATTERN AND IT MUST BE MANUALLY CHANGED FOR NOW.
## '001 Barry Posen - Restraint_ A New Foundation for U.S. Grand Strategy - Opening Credits.opus'
## '002 Barry Posen - Restraint_ A New Foundation for U.S. Grand Strategy - Chapter 1.opus'
## ⋮
## '018 Barry Posen - Restraint_ A New Foundation for U.S. Grand Strategy - Chapter 17.opus'
## '019 Barry Posen - Restraint_ A New Foundation for U.S. Grand Strategy - End Credits.opus'
###############################################################################################################
elif [[ "${opusarray[@]}" =~ [[:digit:]]{1,3}\ -\ (.+)\.opus ]]; then
echo "Using rename pattern 7:"
regex="[[:digit:]]{1,3}\ -\ (.+)\.opus"
for i in "${opusarray[@]}"; do
n="${i%% *}"
newname="${i%.opus}"; newname="${newname#* - } -- Part $n: Part $n.opus"
confirm_rename["$i"]="$newname"
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
elif [[ "$opusarray" =~ .+_[[:digit:]]{1,3}\.opus ]]; then
echo "Using rename pattern 8:"
for i in "${opusarray[@]}"; do
n="${i%.opus}"; n="${n##*_}"
newname="${i%_*} -- Part $n: Part $n.opus"
confirm_rename["$i"]="$newname"
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
elif [[ "$opusarray" =~ ^[\(\[]?[[:digit:]]{2,3}[.]?[\]\)]?\ .+\.opus$ ]]; then
echo "Using rename pattern 9:"
for i in "${opusarray[@]}"; do
if [[ "$i" =~ ^[\(\[] ]]; then
n="${i#*[([]}"; n="${n%%[]).]}"
newname="${i#* }"; newname="${newname%.opus}"
elif [[ "$i" =~ ^[[:digit:]] ]]; then
n="${i%%[ .]*}"
newname="${i#*[. ]}"; newname="${newname%.opus}"
[[ "$newname" =~ ^\ ]] && newname="${newname#\ }"
newname="$newname -- Part $n: Part $n.opus"
fi
confirm_rename["$i"]="$newname"
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
elif [[ "$opusarray" =~ .+\ \([[:digit:]]{1,3}\)\.opus ]]; then
echo "Using rename pattern 10:"
for i in "${opusarray[@]}"; do
# n="${i%).opus}"; n="${n:0:-3}-- ${n: -2}"
n="${i%).opus}.opus"; n="$(echo "$n"|rev)"; n="$(echo "${n/\( / traP :00 traP -- }"|rev)"
# newname="${i%_*} -- Part $n: Part $n.opus"
newname="$n"
confirm_rename["$i"]="$newname"
printf '%s %s---->%s %s%s\n%s' "$i" "$bold" "$tput0" "$red" "${confirm_rename["$i"]}" "$tput0"
done
mvopus
fi
# Check if files match the expected naming pattern after renaming
renopus=( *\ --\ Part\ *.opus )
if ! compgen -G '@(*\ --\ Part\ ???\:\ *.opus|*\ --\ Part\ ??\:\ *.opus)' &> /dev/null; then
# If files do not match expected naming pattern, attempt to rename them
if [[ "${renopus[0]/ -- Part / -- Part 00: Part }" == *\ --\ Part\ ??\:\ *.opus ]]; then
for opusfile in *opus; do
n="${opusfile#* -- Part }"; n="${n%%.opus}"
mv "$opusfile" "${opusfile/ -- Part / -- Part $n: Part }"
done
else
allfiles=(*)
# Exit if files do not match expected naming pattern and cannot be renamed
[[ "${allfiles[@]}" != *.opus\ * ]] && printf 'This directory does not contain files in the expected format or filename.\n'
[[ "${allfiles[@]}" = *.opus\ * ]] && printf 'The rudimentarly built-in file renaming was unable to put the opus files into the pattern of <Title> -- Part ##: <Chapter Title>.opus\nPlease rename files and retry indexopus.'
exit
fi
fi
}
##--> Main Code <--####################################################################################
##--> indexopus <--####################################################################################
echo
printline "${bold} Welcome to ${red}indexopus ${tput0}"
echo
# Parse command-line options
while [[ "$#" -gt 0 ]]; do
if [[ "$1" = @(e|edit|--edit) ]]; then
editscript;
elif [[ "$1" = @(-y|--force) ]]; then
rmmatch=true
elif [[ "$1" = -f ]]; then
fd="$2"; shift
elif [[ "$1" = @(-d) ]]; then
opuspartdur="$2"; shift
elif [[ "$1" = @(-t|--title) ]]; then
title="$2"; shift
elif [[ "$1" = @(-s|--stamp) ]]; then
stamp="$2"; shift
elif [[ "$1" = @(-m|--tmp) ]]; then
tmp="$2"; shift
elif [[ "$1" = @(c|config|--config) ]]; then
if [[ -n "$2" && -f "$2" && $(grep -q "absserver" "$2") ]]; then
config="$2"
shift
else
# if [[ -f "$confpath" && $(grep -q "absserver" "$confpath") ]]; then
# config="$confpath"
# fi
echo "Default config file location: $confpath"
fi
elif [[ "$1" = @(-r|--reindex|reindex) ]]; then
reindex=true
elif [[ "$1" = @(-h|help|--help) ]]; then
usage
else
echo "Unknown option: $1"
exit 1
fi
shift
done
if [[ ! -d "$tmp" ]]; then
mkdir "$tmp" || printf '%s%sFailed to create %s!\nexit 1\n%s' "$red" "$bold" "$tmp" "$tput0" #&& exit
fi
if [[ "$reindex" = true ]] #if reindex is true, check for rmmatch and reindex.
then
reindex
printf '%sPlease see %s/%s for indexed file.%s\n\n' "$red" "$PWD" "$reintitle" "$tput0"
exit
fi
opusarray=( *.opus )
# this checks for a metadata.json, ideally from audiobookshelf. there could be other metadata.json files
# abs doesn't support json files with other names, nor is there anything in the json identifying it
# as an abs file. It does check the .json for the chapter index, so there's at least that...
if [[ -f metadata.json ]] && [[ "$(jq -r '.chapters[0].title' metadata.json)" ]]
then
reindex=true; itemid_pwd
[[ "$(jq -r '.chapters[0] | .title' metadata.json)".opus == "${opusarray[0]}" ]] ||
[[ "$(jq -r '.chapters[0] | .title' metadata.json)" == "001" ]] &&
reindex=false
[[ "$reindex" = false ]] &&
printf '%sA metadata.json file exists with duplicate chapter information; look up new chapter information at\ngoogle-chrome %s/audiobook/%s/chapters\n\n' "$red" "$absserver" "$(sqlite3 "$abssqlite" "select id FROM libraryitems WHERE path=='$sqlitepwd';" ".exit")" &&
[[ ! "$rmmatch" = true ]] && confirm "${bold}Would you like to try to reindex the file after importing chapter information? ${tput0}" &&
reindex=true
fi
if ! compgen -G *\ --\ Part\ @(??|???)\:\ *.opus &> /dev/null
then
rename
fi
d=0
t=0
gettitle "$title"
if [[ -f ./"$output" ]] && [[ "$rmmatch" != true ]]
then
printf 'This directory already contains %s\n\n' "$ioutput"
if confirm "Overwrite the existing file? (y/n) "
then
printf '\n%sOverwriting %s -- Audiobook.opus...%s\n' "$relipsis" "$ititle" "${tput0}"
else
[[ -f metadata.json ]] &&
confirm "$(printf '\nNot overwriting.\nA metadata.json file was found. Would you like to reindex the file?')" &&
reindex=true && overwrite=false ||
printf '\n%s\n\n' "$(printline " Exiting ${scriptname}: ${red}user abort. exit (130)${tput0} ")"
exit 130
fi
fi
[[ "$opuspartdur" ]] && duration="$opuspartdur" ||
duration=$(find . -type f \( -iname "$title -- Part ??:*.opus" -o -iname "$title -- Part ???:*.opus" \) -print0 |
xargs -0 mplayer -vo dummy -ao dummy -identify 2>/dev/null |
perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "%02d:%02d:%02d\n",$t/3600,$t/60%60,$t%60' |
tail -n 1)
printf '\n%sGenerating the index for %s -- Audiobook.opus from...%s\n\n' "$relipsis" "$ititle" "$tput0"
rm opusindex opusfiles 2>/dev/null
createindex
printf '%s:~%s~%s\n\n' "${createdindex[@]}"|paste|column -t -s "~"
printf '\n%s%sProposed index for %s:%s%s\n' "$red" "$bold" "$ititle" "${tput0}" "$bold"
printf '%s .. %s\n' "${rawindex[@]}" # DO NOT touch this line
echo
if [[ "$rmmatch" != "true" ]] &&
! $(confirm "Continue with concatination? (y/n) "); then
printf '\n\nWell why are you here then?%s\n\n' "$tput0"
printline " ${bold}Leaving ${scriptname}: ${red}User abort. exit (130) ${tput0}$(echo)"
exit 130
fi
printf '\n\n%sConcatenating %s -- Part ??: *.opus...%s\n\n' "$relipsis" "$ititle" "$tput0"
#concatination step:
dirsize="$(du -csb *Part*opus|tail -n1)"
dirsize="${dirsize%%$'\t'*}" #remove everything after first tab stop
dirsize="$((dirsize/1000))" #convert bytes to KiB
#printf %sPart\ files\:\\n%s "$red" "$tput0"
#printf '%ssize %s: %sKiB\n%stime %s: %s\n' \
# "$red" \
# "$tput0" \
# "$dirsize" \
# "$red" \
# "$tput0" \
# "$duration"
#[[ "$overwrite" != false ]] && ffout="$(ffmpeg -nostdin -hide_banner -v error -stats -f concat -safe 0 -thread_queue_size 1024 -i "$tmp/opusfiles" -n -acodec copy "$tmp/$output" |& tail -n1 )"
#[[ "$overwrite" != false ]] &&
ffout="$(ffmpeg -nostdin -hide_banner -v info -stats -f concat -safe 0 -thread_queue_size 1024 -i "$tmp/opusfiles" -n -acodec copy "$tmp/$output" |& tail -n1 )"
#ffout="$(printf %s|tail -n2|head -n1)"
#ffout="$(printf %s|tail -n2|head -n1)"
if [[ "$ffout" =~ $'\r' ]]; then declare -p ffout; ffout="${ffout#*$'\r'}"; fi
ffsize=$(awk '{for(i=1;i<=NF;i++) if ($i ~ /^size=/) {print $(1+i)} }' <<< "$ffout" | sed 's/size=//')
ffsize="${ffsize%KiB}"
fftime=$(awk '{for(i=1;i<=NF;i++) if ($i ~ /^time=/) {print $i} }' <<< "$ffout" | sed 's/time=//')
ffbitrate=$(awk '{for(i=1;i<=NF;i++) if ($i ~ /^bitrate=/) {print $(i+1)} }' <<< "$ffout" | sed 's/bitrate=//')
ffspeed=$(awk '{for(i=1;i<=NF;i++) if ($i ~ /^speed=/) {print $i} }' <<< "$ffout" | sed 's/speed=//')
labelwidth=12
valuewidth=15
totalwidth=$((labelwidth + valuewidth + 5))
printf "\n%-${totalwidth}s | %-${totalwidth}s\n" "${red}Concatenated file${tput0}:" "${red}Part files${tput0}:"
printf "%-${labelwidth}s %-${valuewidth}s | %-${labelwidth}s %s\n" \
"${red}size ${tput0}:" "$ffsize KiB" "${red}size${tput0}:" "${dirsize} KiB"
printf "%-${labelwidth}s %-${valuewidth}s | %-${labelwidth}s %s\n" \
"${red}time ${tput0}:" "$fftime" "${red}time${tput0}:" "$duration"
printf "%-${labelwidth}s %-${valuewidth}s |\n" \
"${red}bitrate${tput0}:" "$ffbitrate"
printf "%-${labelwidth}s %-${valuewidth}s |\n" \
"${red}speed ${tput0}:" "$ffspeed"
printf '\n%sSize reduction%s: %s KiB / %s%%\n' "$red" "$tput0" "$(( dirsize - ffsize ))" "$(( ( 100*${dirsize} - 100 * ${ffsize%KiB} ) / ${dirsize} ))"
if [[ "$overwrite" != false ]] && [[ "$?" != 0 ]]; then
printf "\nffmpeg failed to concatinate; exit 1\n\n" && exit 1
fi
if [[ ! -f "$tmp/$output" ]]; then
printf '\n\n\n%s%sWhere the fuck is %s/%s?\nexit 1%s' "$red" "$bold" "$tmp" "$output" "$tput0"
printline "Leaving $scriptname: error, exit 1!"
exit 1
fi
printf '\n\n%sIncorporating index into%s %s -- Audiobook.opus%s\n\n%s' "$relipsis" "$white" "$ititle" "$relipsis" "$tput0"
#mvout="$(mv "$tmp/$output" "$output" 2>&1)"
#mvec="$?"
#
#pause "$tmp/$output $PWD/$output $mvec $mvout"
#
#if (( mvec == 0 )); then
# echo "File moved successfully."
#else
# if echo "$mvout" | grep -q "are the same file"; then
# echo "Source and destination files are identical. Deleting the source file."
# rm "$tmp/$output"
# else
# echo "Error: $mvout"
# exit 1
# fi
#fi
output="$tmp/$output"
writeindex "$output"
wiec="$?"
(( "$?" != 0 )) && { echo "writeindex did not exit cleanly, exit 1"; exit 1; }
if [[ -f "$output" ]] && eval command -v mediainfo &> /dev/null; then
printf '%sChecking output from mediainfo...\n\n%s' "$relipsis" "$tput0"
mediainfo "$output"
outdur="$(mediainfo -f "$output"|grep Duration|head -n1)"
outdur="${outdur#*: }"
outdur="$(echo "$outdur" | perl -nle '/([0-9\.]+)/ && ($t += $1) && printf "%02d:%02d:%02d\n", $t/3600000, ($t/60000)%60, ($t/1000)%60')"
data=( "${bold}Duration(s):${tput0}"
"${red}${bold} $duration ${tput0}${ititle} -- Part .*opus $tput0"
"${red}${bold} $outdur ${tput0}${ititle} -- Audiobook.opus $tput0")
# Print the aligned data using column, right justifying durations
printf '%s\n' "${data[@]}" #| column -s "~" -t -R 2
echo "$tput0 $white"
elif [[ -f "$output" ]] && eval command -v ffprobe &> /dev/null; then
printf 'Checking the output from ffprobe...\n\n'
ffprobe "$output"
printf 'Original duration... %s' "$duration"
else
echo "Indexed opus file not found! Exit 1"
rmyn "remove $tmp? " "leaving files" rm -r "$tmp"
# (( $rmynres == 1 )) && >&2 echo "$tmp"
printline "${bold} Exiting (1) ${white}indexopus ${tput0}"
exit 1
fi
if [[ "$rmmatch" = true && "$duration" = "$outdur" ]]; then
# pause "output=$output; PWD=$PWD; tmp=$tmp"
printf '%sDurations of part and indexed opus files match, automatically deleting temporary files!\n' "$relipsis"
rm -r "$title"\ --\ Part\ *.opus "$tmp"/opus@(files|index)
if mvoutput="$(mv "$output" "$PWD" 2>&1)"; then
printf '\nPlease see %s%s%s/%s%s\n\n%sDone.\n\n%s' "$white" "$bold" "$PWD" "$ioutput" "$tput0" "$relipsis" "$tput0"
rm -r "$tmp"
printline "${bold} Exiting (0) ${white}indexopus ${tput0}"
exit 0
elif [[ "$mvoutput" =~ ^mv\:\ [\'\"].+[\'\"]\ and\ [\'\"].+[\'\"]\ are\ the\ same\ file$ ]]; then
printf '\nPlease see %s%s%s/%s%s\n\n%sDone.\n\n%s' "$white" "$bold" "$PWD" "$ioutput" "$tput0" "$relipsis" "$tput0"
printf '%sNB: $tmp = %s%s%s\n and\n $PWD = %s%s%s\n' "$red" "$white" "$tmp" "$red" "$white" "$PWD" "$red"
if [[ "$tmp" != "$PWD" ]]; then
rmr "$tmp"
printf ' %sremoving %s%s\n\n' "$relipsis" "$white" "$tmp"
else
printf ' %snot removing %s%s\n\n' "$relipsis" "$white" "$tmp"
fi
printline "${bold} Exiting (0) ${white}indexopus ${tput0}"
exit 0
else
echo "mvoutput= $mvoutput"
pause "output=$output; PWD=$PWD; tmp=$tmp"
printf '\nthere is something wrong here. exit 1\n\n'
printline "${bold} Exiting (1) ${white}indexopus ${tput0}"
exit 1
fi
fi
[[ "$reindex" = true ]] && confirm "$(printf '%sA metadata.json file was found!\n%sReindex the file with audiobookshelf chapter info? %s' "${red}" "${bold}" "${tput0}")" && indexopus reindex
#this isnt working right tonight and it is late.
#this was "$reindex" != true... changing to "$rmmatch":
#[[ "$reindex" != true ]] && rmyn "${bold}${red}Remove $title -- Part *.opus & temp files? (y/n) ${tput0}" "$bold Leaving temporary files $tput0" rm -r "$title"\ --\ Part\ *.opus "$tmp"/opus@(files|index) && iorm=true ||
[[ "$rmmatch" != true ]] && rmyn "${bold}${red}Remove $title -- Part *.opus & temp files? (y/n) ${tput0}" "$bold Leaving temporary files $tput0" rm -r "$title"\ --\ Part\ *.opus "$tmp"/opus@(files|index) && iorm=true ||
rm -r "$title"\ --\ Part\ *.opus "$tmp"/opus@(files|index)
mv "$output" "$PWD"
rm -r "$tmp"
printf '\n\n%sDone.\n\nPlease see %s%s%s/%s\n\n' "$relipsis" "$white" "$bold" "$PWD" "$ioutput"
#exec 5<> "$tmp/5"
(( $rmynres == 1 )) 2>/dev/null && echo "$tmp remains"
#clean up /tmp/indexopus-* files older than a day:
find /tmp -iname "indexopus-1*" -mtime -1 -exec rm -rf {} 2>/dev/null \;
printf '%s' "$tput0"
printline "${bold} Exiting (0) ${white}indexopus ${tput0}"
echo
[[ "$iorm" = true ]] && exit 2 || exit 0 # this exit 2 has to be here so that it is passed back to m4b2opus
exit 1 #how did it get here?!?
to get chapters for a new abs book, it looks like the following api calls:
curl -X POST "$absserver/api/items/$(itemid)/scan" -H "Authorization: Bearer $abstoken"
curl "$absserver/api/search/chapters?asin=$(jq -r '.asin' metadata.json)" -H "Authorization: Bearer $abstoken" >chapters.json
curl -X POST "$absserver/api/items/$(itemid)/match" -H "Authorization: Bearer $abstoken" -H "Content-Type: application/json" -d '{"provider": "audible", "overrideDefaults": "true"}'