-
Notifications
You must be signed in to change notification settings - Fork 1
/
rdfetch.in
1557 lines (1305 loc) · 60.5 KB
/
rdfetch.in
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
# shellcheck shell=bash disable=SC2016,SC2028,SC2051,SC2064,SC2086,SC2154,SC2162
# Globally ignore shellcheck directives:
# SC2016: our menu entries do not want the variables expanded until used.
# SC2028: escape sequences in ZSH actually work with echo.
# SC2034: those 'apparently unused' variable are actually used.
# SC2051: unlike BASH, ZSH supports variables in brace range expansions.
# SC2064: I want the trap expressions to be evaluated when the traps are set.
# SC2086: sometimes things are already double-quoted.
# SC2154: those variables that are 'referenced but not assigned' actually are assigned.
# SC2162: we do not care about backslashes in values read from STDIN.
##########################################################################################
##########################################################################################
##
## rdfetch
##
## Copyright 2022, David Klann <dklann@broadcasttool.com>
##
## A Broadcast Tool & Die tool to manage podcast feeds (i.e., RSS,
## ATOM, etc.) and downloads by podget(1), for later import into a
## Rivendell library.
##
##########################################################################################
##########################################################################################
# FUNCTION_ARGZERO to make error messages and troubleshooting
# functions and externally-sourced scripts make more sense.
setopt NO_CASE_MATCH FUNCTION_ARGZERO
zmodload zsh/regex
zmodload zsh/datetime
zmodload zsh/terminfo
zmodload zsh/stat
autoload colors
colors
# This script complies with Semantic Versioning: http://semver.org/
vMajor=0
vMinor=4
vPatch=15
vHash='$Hash$'
# Get zsh functions necessary for this script.
# SC1091: breaks before running configure.
# shellcheck disable=SC1091
if [[ -r @bindir@/zsh-functions ]] ; then
source @bindir@/zsh-functions
else
exit "$(error 'Cannot read support library @bindir@/zsh-functions. Please consult your tarot card reader!')"
fi
##########################################################################################
## Locally defined subroutines
##########################################################################################
# How to use this command.
function usage() {
local -r myName="${1:t}"
${CAT} << EOF
${myName}: add a new RSS feed to the list of podcasts.
SUMMARY
${myName} [ --verbose (-v) ] [ --version (-V) ] [ --help (-h) ]
[ --config (-c) <podget_configuration_file> ]
[ --dir_config (-d) <podget_configuration_directory> ]
DESCRIPTION
${myName} is a text-menu driven command-line tool for fetching and
importing audio files from podcasts (also known as RSS feeds) into the
Rivendell Radio Automation System. By default, a new cart will be
created for each podcast, although this behavior can be modified by
choosing the appropriate option when adding a podcast.
${myName} leads you through the process using a text-based wizard,
asking questions about the podcast you want to retrieve and where to
store the audio in Rivendell.
EOF
}
function addOrReplaceFeed() {
local -r myName=${1} ; shift
local -r verbose=${1}
local feedURL feedUser feedPassword protocol hostANDport route urlWithCredentials
local feedTitle name group
local backupServerlist=/var/tmp/${CONFIG_SERVERLIST:t}
local replaceFeed=0 addNewFeed=1
local ok returnValue=0
if ! okDatabaseStructure "GROUPS:name+default_cart_type" "${verbose}" ; then
returnValue="${?}"
echo "${0}() (${zsh_eval_context}): This version of ${myName} is not compatible with Rivendell database version '$(rdDatabaseVersion)'. Cannot determine Groups"
read ok\?"Press <Enter> to continue. "
return "${returnValue}"
fi
trap 'trap - ; return ;' 0 2 3
# Make a backup copy of serverlist before we make any changes.
${CP} ${DIR_CONFIG}/${CONFIG_SERVERLIST} ${backupServerlist}
read feedURL\?"Type or paste the RSS feed URL for this podcast: "
if getYesNo "Does this podcast download require a username?" ; then
echo
read feedUser\?"Type or paste the feed username and press <Enter>: "
if getYesNo "Does this URL require a password for the user ${feedUser}?" ; then
echo
read feedPassword\?"Type the password for the user '${feedUser}' and press <Enter>: "
fi
protocol=${feedURL%://*}
hostANDport=${${feedURL#${protocol}://}%%/*}
route=${feedURL#${protocol}://${hostANDport}}
# ${urlWithCredentials} is used below only to try to obtain the feed title.
urlWithCredentials=${protocol}://${feedUser}${feedPassword:+:${feedPassword}}@${hostANDport}/${route}
fi
echo
# Get the RSS feed XML; first with credentials (if supplied).
typeset rssXML="$(${WGET} -q -O - ${urlWithCredentials:-${feedURL}})"
if [[ -z "${rssXML}" ]] ; then
# Try it without credentials.
rssXML=$(${WGET} -q -O - "${feedURL}")
fi
if [[ -z "${rssXML}" ]] ; then
warning "I could not retrieve this feed. Please make sure the URL, username (if needed) and password (if needed) are correct and if necessary, re-run ${myName}."
trap -
return 1
fi
typeset feedTitle="$(print ${rssXML} | ${XMLSTARLET} sel -t -m /rss/channel -v title)"
typeset -r feedEnclosureFileExt=${$(print "${rssXML}" | ${XMLSTARLET} sel -t -m /rss/channel -v item/enclosure/@url)##*.}
##########################################################################################
## Prompt for a name using ${feedTitle} as the default.
##########################################################################################
read name\?"Enter a name for this podcast (${BOLD}Note: I may slightly modify the name${NORM}): ${feedTitle:+[${feedTitle}]} "
[[ -z "${name}" ]] && name="${feedTitle}"
# From the inside out, this parameter substitution does the following:
# converts the characters <Space> <Comma> : ! # * ? < > & $ / ( ) + to a dash ("-")
# deletes single (') and double (") quotes
# deletes a single dash ("-") at the end of the string
# The sed(1) expression replaces two or more dashes ("-") with a single dash.
cleanName=$(echo ${${${name//[: ,\!\?\&\$\/\)\(\#\*\\\>\<\+]/-}//[\"\']/}/%-/} | ${SED} -e 's/--*/-/g')
read ok\?"Using ${cleanName} for the podcast name. Is this OK? [y or n]: "
until [[ "${(L)ok}" =~ ^y(es)*$ ]] ; do
print
read name\?"OK, let's try again. Enter a name for this podcast: "
cleanName=$(echo ${${${name//[: ,\!\?\&\$\/\)\(\#\*\\\>\<\+]/-}//[\"\']/}/%-/} | ${SED} -e 's/--*/-/g')
read ok\?"Using '${cleanName}' for the podcast name. Is this OK? [y or n]: "
done
local -r feedName="${cleanName}"
##########################################################################################
## Get the "category" for this podcast. Use a Rivendell GROUP for the category name.
##########################################################################################
local -r rivendellGroupList="$(doSQL "select NAME from GROUPS where DEFAULT_CART_TYPE=1 order by NAME")"
# List the Groups and prompt them for a Group to use if they asked
# for a list or if they did not name a Group.
if [[ -z "${group}" ]] || [[ "${group}" =~ list ]] ; then
echo "\nCurrent list of GROUPs:"
${COLUMN} -x -c $((COLUMNS > 80 ? 78 : COLUMNS)) <<< ${rivendellGroupList}
read group\?"Type the name of the Rivendell GROUP into which this podcast will be imported: "
fi
##########################################################################################
## Validate the group against the current known list of groups in the
## Rivendell database.
##########################################################################################
until ${GREP} -q "^${group}$" <<< ${rivendellGroupList} ; do
warning "'${group}' is not in the list. Please use a valid GROUP name."
echo "Current list of GROUPs:"
${COLUMN} -x -c $((COLUMNS > 80 ? 78 : COLUMNS)) <<< ${rivendellGroupList}
read group\?"Enter the Rivendell GROUP into which this podcast will be imported: "
done
((verbose)) && warning "${myName} (verbose): ${feedURL} ${group} ${feedName}${feedUser:+' USER:${feedUser}'}${feedPassword:+' PASS:${feedPassword}'}"
echo
##########################################################################################
## Add the feed to CONFIG_SERVERLIST
##########################################################################################
[[ -w "${DIR_CONFIG}/${CONFIG_SERVERLIST}" ]] ||
return "$(error 'Missing access rights to modify the file ${DIR_CONFIG}/${CONFIG_SERVERLIST}')"
local tmpfile
tmpfile=$(${MKTEMP})
trap "${RM} -f ${tmpfile}; trap - ; return ;" 0 2 3
# Same group and name (possibly different URL?).
if ${GREP} -P -q "^[^#].*\s+${group}\s+${feedName}\s*" ${DIR_CONFIG}/${CONFIG_SERVERLIST} ; then
addNewFeed=0
if getYesNo "${feedName} already exists in group ${group}. Replace?" ; then
${GREP} -P -v "^[^#].*\s+${group}\s+${feedName}\s*" ${DIR_CONFIG}/${CONFIG_SERVERLIST} > ${tmpfile}
replaceFeed=1
fi
# Same name, different group.
elif ${GREP} -P -q "^[^#].*\s+${feedName}\s*" ${DIR_CONFIG}/${CONFIG_SERVERLIST} ; then
addNewFeed=0
if getYesNo "${feedName} already exists in a different group. Change to group '${group}'?" ; then
${GREP} -P -v "^[^#].*\s+${feedName}\s*" ${DIR_CONFIG}/${CONFIG_SERVERLIST} > ${tmpfile}
replaceFeed=1
fi
fi
if ((addNewFeed || ! replaceFeed)) ; then
# A new feed.
${CP} ${DIR_CONFIG}/${CONFIG_SERVERLIST} ${tmpfile}
fi
if ((addNewFeed || replaceFeed)) ; then
${CAT} <<EOF >> ${tmpfile}
${feedURL} ${group} ${feedName}${feedUser:+" USER:${feedUser}"}${feedPassword:+" PASS:${feedPassword}"}
EOF
fi
if [[ -s ${tmpfile} ]] ; then
# There should be no more than two lines of difference between the
# original and the edited file.
if (($(${DIFF} --side-by-side --suppress-common-lines ${DIR_CONFIG}/${CONFIG_SERVERLIST} ${tmpfile} | ${WC} -l) <= 2)) ; then
# We made a tmpfile, so replace serverlist with its contents.
${MV} ${tmpfile} ${DIR_CONFIG}/${CONFIG_SERVERLIST} ||
return "$(error 'Could not replace ${DIR_CONFIG}/${CONFIG_SERVERLIST}.')"
${CHMOD} 644 ${DIR_CONFIG}/${CONFIG_SERVERLIST}
${MKDIR} -p ${DIR_LIBRARY}/${group}/${feedName} ||
warning "Failed to create new podcast directory ${DIR_LIBRARY}/${group}/${feedName} (${?}). You may have to create this yourself."
echo
##########################################################################################
## Offer to create a Rivendell dropbox if we are making changes
## to this podcast (new or replace).
##########################################################################################
if addRDDropbox ${myName} ${DIR_LIBRARY} ${feedName} "${feedEnclosureFileExt}" ${group} ${verbose} ; then
# Second arg indicates we are calling rdDropboxStatus interactively.
rdDropboxStatus ${myName} 1 ${verbose}
##########################################################################################
## Also offer to create a Rivendell Event.
##########################################################################################
if getYesNo "Do you want to also create an new Event for this feed?" ; then
echo
if ! addSimpleEvent ${myName} "${feedName}" ${verbose} ; then
printf "Sorry. I could not create a new event for %s\n" "${feedName}"
fi
fi
fi
read ok\?"Podcast $( ((replaceFeed)) && echo replaced || echo added). Press <Enter> to continue. "
else
returnValue=$(error "Found an unexpected error in the new podcast feed file while attempting to add '${feedName}'")
echo "Restoring backup. Please notify the authorities!"
((verbose)) && { echo "${myName} (verbose):" ; ${DIFF} --side-by-side --suppress-common-lines ${DIR_CONFIG}/${CONFIG_SERVERLIST} ${tmpfile} ; }
${MV} ${backupServerlist} ${DIR_CONFIG}/${CONFIG_SERVERLIST}
read ok\?"Press <Enter> to continue. "
fi
else
returnValue=$(error "Found an empty podcast feed file while attempting to add feed '${feedName}'")
echo "Restoring backup. Please notify the authorities!"
${MV} ${backupServerlist} ${DIR_CONFIG}/${CONFIG_SERVERLIST}
read ok\?"Press <Enter> to continue. "
fi
trap -
}
function enableFeed() {
local -r myName=${1} ; shift
local -r verbose=${1}
local feedList feedNameEntered feedName group feedURL tmpfile
local urlWithCredentials rssXML configLine feedUser feedPass
trap 'trap - 0 2 3 ; return ;' 0 2 3
feedList=$(${GREP} '^#DISABLED#' ${DIR_CONFIG}/${CONFIG_SERVERLIST} | ${AWK} '{print $3}')
# Try to enable feeds only if there actually are any disabled ones.
if [[ -n "${feedList}" ]] ; then
if (($(${WC} -l <<<${feedList}) > 1)) ; then
echo "Current list of disabled podcast feeds:"
${COLUMN} -x -c $((COLUMNS > 80 ? 78 : COLUMNS)) <<< ${feedList}
read feedNameEntered\?"Type or paste the name of the podcast you want to enable and press <Enter>: "
# Allow '*'-style wildcards in the feedName, will expand it below.
until feedName=$(${GREP} -i "^${feedNameEntered//\*/.*}$" <<< ${feedList}) ; do
warning "'${feedNameEntered}' is not in the list. Please use a valid feed name."
echo "Current list of disabled podcast feeds:"
${COLUMN} -x -c $((COLUMNS > 80 ? 78 : COLUMNS)) <<< ${feedList}
read feedNameEntered\?"Type or paste the name of the podcast you want to enable: "
done
else
# There is only one feed to enable, so prompt to enable it.
feedName=${feedList}
read ok\?"Press 'y' to enable the feed '${feedName}', or any other key to cancel: "
if [[ "${ok}" != 'y' ]] ; then
trap -
return
fi
echo
fi
echo "Enabling '${feedName}' in the feed list... \c"
trap "${RM} -f ${DIR_CONFIG}/${CONFIG_SERVERLIST}.bak ; trap - ; return ;" 0 2 3
${SED} -i.bak -e "/^#DISABLED#.*[[:space:]]${feedName}[[:space:]]*/s/^#DISABLED#//" ${DIR_CONFIG}/${CONFIG_SERVERLIST}
# The sed command *should* result in exactly one line of
# difference between the original and the edited file.
if (($(${DIFF} --side-by-side --suppress-common-lines ${DIR_CONFIG}/${CONFIG_SERVERLIST}.bak ${DIR_CONFIG}/${CONFIG_SERVERLIST} | ${WC} -l) == 1)) ; then
${RM} -f ${DIR_CONFIG}/${CONFIG_SERVERLIST}.bak
configLine=$(${GREP} "[[:space:]]${feedName}[[:space:]]*" ${DIR_CONFIG}/${CONFIG_SERVERLIST})
group=$(print "${configLine}" | ${AWK} '{print $2}')
if ! [[ -d ${DIR_LIBRARY}/${group}/${feedName} ]] ; then
${MKDIR} -p ${DIR_LIBRARY}/${group}/${feedName} ||
warning "Failed to create new podcast directory ${DIR_LIBRARY}/${group}/${feedName} (${?}). You may have to create this yourself."
fi
feedURL="${configLine%% *}"
if [[ "${configLine}" =~ .*USER:.* ]] ; then
feedUser=$(print "${configLine}" | ${AWK} '{print $4}')
fi
if [[ "${configLine}" =~ .*PASS:.* ]] ; then
feedPass=$(print "${configLine}" | ${AWK} '{print $5}')
fi
# Splice the credentials into the feed URL.
if [[ -n "${feedUser}" ]] && [[ -n "${feedPass}" ]] ; then
urlWithCredentials="${feedURL%%:*}://${feedUser}:${feedPass}@${feedURL#*://}"
fi
# Get the RSS feed XML; first with credentials (if supplied).
if ! rssXML=$(${WGET} -q -O - "${urlWithCredentials:-${feedURL}}") ; then
warning "wget(1) returned with exit status '${?}'."
if [[ -n "${feedUser}" ]] ; then
warning "Will attempt without credentials."
fi
fi
if [[ -z "${rssXML}" ]] ; then
# Try it without credentials.
if ! rssXML=$(${WGET} -q -O - "${feedURL}") ; then
warning "wget(1) returned with exit status '${?}'. I will be unable to discern the download file type."
fi
fi
if [[ -z "${rssXML}" ]] ; then
warning "I could not retrieve this feed. Please make sure the URL, username (if needed) and password (if needed) are correct and try again."
else
typeset feedTitle=$(echo "${rssXML}" | ${XMLSTARLET} sel -t -m /rss/channel -v title)
## BUG ALERT: this "algorithm" for determining the download
## file extension is not foolproof. More work to be done.
typeset -r firstFeedEnclosure=$(echo "${rssXML}" | ${XMLSTARLET} sel -t -m /rss/channel -v item/enclosure/@url --nl | ${HEAD} -n 1)
typeset -r feedEnclosureFileExt=${${firstFeedEnclosure%%\?*}##*.}
fi
# Offer to create a Rivendell dropbox if we are making changes
# to this podcast (new or replace).
if addRDDropbox ${myName} ${DIR_LIBRARY} ${feedName} "${feedEnclosureFileExt}" ${group} ${verbose} ; then
# Second arg indicates we are calling rdDropboxStatus interactively.
rdDropboxStatus ${myName} 1 ${verbose}
fi
echo "Done."
else
warning "Could not properly enable the disabled podcast feed '${feedName}'.
Please fix the file '${DIR_CONFIG}/${CONFIG_SERVERLIST}' manually."
${RM} -f ${DIR_CONFIG}/${CONFIG_SERVERLIST}.bak
fi
read ok\?"Press <Enter> to continue. "
else
read ok\?"There are no disabled feeds available. Press <Enter> to continue. "
fi
trap -
}
function deleteFeed() {
local -r myName=${1} ; shift
local -r verbose=${1}
local feedList feedNameEntered feedName deleteOrDisable tmpfile group
trap 'trap - ; return ;' 0 2 3
feedList=$(${GREP} -v '^#' ${DIR_CONFIG}/${CONFIG_SERVERLIST} | ${AWK} '{print $3}' | ${SORT})
# Delete feeds only if there actually are any available.
if [[ -z "${feedList}" ]] ; then
read ok\?"There are no feeds available to delete. Press <Enter> to continue. "
trap -
return
fi
# Prompt for a feed to delete only if there is more than one in
# the list.
if (($(${WC} -l <<<${feedList}) > 1)) ; then
echo "Current list of podcast feeds:"
${COLUMN} -x -c $((COLUMNS > 80 ? 78 : COLUMNS)) <<< ${feedList}
read feedNameEntered\?"Enter the name of the podcast ('*' wildcard OK) you want to delete or disable (and press <Enter>): "
until feedName=$(${GREP} "^${feedNameEntered//\*/.*}$" <<< ${feedList}) ; do
warning "'${feedNameEntered}' is not in the list. Please use a valid feed name."
echo "Current list of podcast feeds:"
${COLUMN} -x -c $((COLUMNS > 80 ? 78 : COLUMNS)) <<< ${feedList}
read feedNameEntered\?"Enter the name of the podcast ('*' wildcard OK) you want to delete or disable: "
done
else
# Only one feed, so offer it for deletion.
feedName=${feedList}
fi
group=$(${AWK} "/[[:space:]]${feedName}[[:space:]]*/{print \$2}" ${DIR_CONFIG}/${CONFIG_SERVERLIST})
((verbose)) && warning "${myName} (verbose): deleting '${feedName}' from '${group}'."
read deleteOrDisable\?"Do you want to disable (d) or delete (D) '${feedName}'? "
until [[ "${deleteOrDisable}" =~ [Dd] ]] ; do
echo
read deleteOrDisable\?"Please type a lower case 'd' for 'disable' or an upper case 'D' for 'delete' and press <Enter>"
done
echo
if [[ "${deleteOrDisable}" = 'd' ]] ; then
echo "Disabling '${feedName}' in the feed list... \c"
trap "${RM} -f ${DIR_CONFIG}/${CONFIG_SERVERLIST}.bak ; trap - ; return ;" 0 2 3
${SED} -i.bak -e "/[[:space:]]${feedName}[[:space:]]*/s/^/#DISABLED#/" "${DIR_CONFIG}/${CONFIG_SERVERLIST}"
# The sed command *should* result in exactly one line of
# difference between the original and the edited file.
if (($(${DIFF} --side-by-side --suppress-common-lines ${DIR_CONFIG}/${CONFIG_SERVERLIST}.bak ${DIR_CONFIG}/${CONFIG_SERVERLIST} | ${WC} -l) != 1)) ; then
warning "Could not properly disable the podcast feed '${feedName}'. Please fix the file '${DIR_CONFIG}/${CONFIG_SERVERLIST}' manually."
fi
${RM} -f ${DIR_CONFIG}/${CONFIG_SERVERLIST}.bak
trap 'trap - ; return ;' 0 2 3
elif [[ "${deleteOrDisable}" = 'D' ]] ; then
echo "Deleting feed '${feedName}' from the feed list... \c"
tmpfile=$(${MKTEMP})
trap "${RM} -f ${tmpfile}; trap - ; return ;" 0 2 3
${GREP} -v "[[:space:]]${feedName}[[:space:]]*" ${DIR_CONFIG}/${CONFIG_SERVERLIST} > ${tmpfile}
if [[ -s ${tmpfile} ]] ; then
if ${MV} ${tmpfile} ${DIR_CONFIG}/${CONFIG_SERVERLIST} ; then
echo "Done."
if getYesNo "Do you want to delete the dropbox for this feed too?" ; then
echo
if cleanupFeed ${myName} ${group} ${feedName} ${verbose} ; then
if deleteRDDropbox ${myName} ${DIR_LIBRARY}/${group}/${feedName} ${verbose} ; then
echo "Purged dropbox for feed '${feedName}'."
else
warning "Unable to successfully delete the dropbox for feed '${feedName}'. Please consult a professional."
fi
else
warning "Unable to successfully clean up the cruft lying about for feed '${feedName}' (${?}). Please report this number to the authorities."
fi
else
echo "\nOK. Not deleting the dropbox for feed '${feedName}'."
fi
else
warning "Could not replace '${DIR_CONFIG}/${CONFIG_SERVERLIST}' with the deleted podcast feed. Do you have the access rights to replace this file? Please fix the file '${DIR_CONFIG}/${CONFIG_SERVERLIST}' manually."
fi
else
warning "Unable to find '${feedName}' in ${DIR_CONFIG}/${CONFIG_SERVERLIST}. Please fix the file ${DIR_CONFIG}/${CONFIG_SERVERLIST} manually."
fi
else
echo "\nWTF? How did you get past the prompt without entering a 'd' or a 'D'?"
fi
read ok\?"Press <Enter> to continue. "
trap -
}
function showFeeds() {
local -r myName=${1} ; shift
local -r verbose=${1}
local activeCount=0 disabledCount=0
activeCount=$(${GREP} -c -Ev '^\s*(#|$)' ${DIR_CONFIG}/${CONFIG_SERVERLIST})
disabledCount=$(${SED} -e '1,/^# ---------/d' < ${DIR_CONFIG}/${CONFIG_SERVERLIST} | ${GREP} -c '^#DISABLED#')
trap 'trap - ; return ;' 0 2 3
(
# The header.
reportTitleText="${activeCount} RDFetch Podcasts ($( ((disabledCount > 0)) && echo ${RED})${disabledCount} Disabled${NORM})"
reportTitle="$(printf ' %.0s' {1..$(((terminfo[cols] - ${#reportTitleText}) / 2))})${BOLD}${reportTitleText}${NORM}"
printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print
print "${reportTitle}"
printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print
printf '%-46s %-16s %-48s\n' "Title" "Group" "Credentials"
printf '-%.0s' {1..46}; printf '-%.0s' {1..16}; printf '-%.0s' {1..48}; print
# The content: remove the boilerplate prefix and empty lines from
# the file, sort the list by feed title (field 3), then group
# (field 2).
${SED} -e '1,/^# ---------/d' < ${DIR_CONFIG}/${CONFIG_SERVERLIST} |
${GREP} -v '^ *$' |
${SORT} --ignore-case --key=3,3 --key=2,2 |
while read url group title rest ; do
if [[ ${url} =~ ^#DISABLED#.* ]] ; then
rdDropBoxPath="${RED}DISABLED:${NORM} RD dropbox: ${DIR_LIBRARY}/${group}/${title}/*.mp3"
title="${RED}DISABLED:${NORM} ${title}"
url="${RED}DISABLED:${NORM} ${url/\#DISABLED#/}"
else
rdDropBoxPath="RD dropbox: ${DIR_LIBRARY}/${group}/${title}/*.mp3"
fi
printf '%-46s %-16s %-48s\n%-80s\n%-80s\n\n' ${title} ${group} ${rest:-""} ${url} ${rdDropBoxPath}
done
# The footer.
printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print
) | ${LESS} -RCiP "Viewing podcast feeds?e (End of Output).\. Press <q> to quit, <PgDown> and <PgUP> to scroll, <g> to -Beginning-, <G> to -End-\."
trap -
}
function showLastStatus() {
local -r myName=${1} ; shift
local -r type=${1} ; shift
local -r verbose=${1}
local statusFile="${STATUS_FILE:-/var/tmp/podget-wrapper.${type}}"
local fileTime
trap 'trap - ; return ;' 0 2 3
case ${type} in
out) OUTPUT="output results" ;;
err) OUTPUT="diagnostic output" ;;
*) { print "${myName}: showLastStatus(): need to specify a file type." ; trap - ; return ; } ;;
esac
if [[ -f ${statusFile} ]] ; then
if [[ -r ${statusFile} ]] ; then
if zstat -H statusStat ${statusFile} ; then
fileTime=$(strftime "%A, %B %d, %Y at %T" ${statusStat[mtime]})
(
# The header.
reportTitleText="Latest RDFetch 'podget' ${(C)OUTPUT}"
if [[ -n "${fileTime}" ]] ; then
reportTitleText="${reportTitleText} as of ${fileTime}"
fi
# Center the title on the display.
reportTitle="$(printf ' %.0s' {1..$(((terminfo[cols] - ${#reportTitleText} ) / 2))})${BOLD}${reportTitleText}${NORM}"
printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print
print "${reportTitle}"
printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print
# The data.
${CAT} ${statusFile}
# The footer.
printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print
) | ${LESS} -RCiP "Viewing the latest podget ${OUTPUT}?e (End of Output).\. Press <q> to quit, <PgDown> and <PgUP> to scroll, <g> to -Beginning-, <G> to -End-\."
else
warning "Could not determine the time of last access of '${statusFile}' (${?}). Please seek professional help."
read ok\?"Press <Enter> to continue. "
fi
else
warning "RDFetch status file '${statusFile}' exists, but is not readable. Please seek professional help."
read ok\?"Press <Enter> to continue. "
fi
else
warning "Missing status file '${statusFile}'. Maybe RDFetch has not been run yet?"
read ok\?"Press <Enter> to continue. "
fi
trap -
}
# Gather and display all the rdimport.log files we can find.
function showRDimportLogs() {
local -r myName=${1} ; shift
local -r verbose=${1}
local returnValue=0
local -a logFiles
trap 'trap - ; return ;' 0 2 3
# Ignore recommendations to use "`mapfile` or `read -a`"
# when setting array variable
# shellcheck disable=SC2207
logFiles=( $(${FIND} ${DIR_LIBRARY} -name rdimport.log -print | ${SORT}) )
if [[ -n "${logFiles[*]}" ]] ; then
for logfile in ${logFiles[*]} ; do
if zstat -H logfileStat ${logfile} ; then
fileTime=$(strftime "%A, %B %d, %Y at %T" ${logfileStat[mtime]})
else
fileTime=$(strftime "%A, %B %d, %Y at %T (unable to stat ${logfile})" ${EPOCHSECONDS})
fi
titleText="${logfile} as of ${fileTime}"
# Center the title on the display.
reportTitle="$(printf ' %.0s' {1..$(((terminfo[cols] - ${#titleText} ) / 2))})${BOLD}${titleText}${NORM}"
{ printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print; }
print "${reportTitle}"
{ printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print; }
# The data (and make it pretty, please).
if ((logfileStat[size])) ; then
${SED} -r \
-e "s/^(..-..-.... - ..:..:..)/${BOLD}\1${NORM}/" \
-e "s/(error|skipping)/${BOLD}${RED}\1${NORM}/gi" \
< ${logfile}
else
echo "\n\t'${logfile}' is ${BOLD}${RED}EMPTY${NORM}.\n"
fi
# The footer.
{ printf ' '; printf '=%.0s' {1..$((terminfo[cols] - 2))} ; print; }
done | ${LESS} -RCiP "Viewing rdimport logs?e (End of Output).\. <q> to quit, <PgDown> and <PgUP> to scroll, <g> to -Beginning-, <G> to -End-\."
else
warning "Could not find ANY log files in '${DIR_LIBRARY}' named 'rdimport.log'."
read ok\?"Press <Enter> to continue. "
returnValue=1
fi
trap -
return "${returnValue}"
}
# Zero out (delete the contents of) the specified rdimport log file.
function clearRDimportLog() {
local -r myName=${1} ; shift
local -r verbose=${1} ; shift
local -r clear_all=${1}
local returnValue=0
local -a logFiles
local logfileIndex chosenFile
trap 'trap - ; return ;' 0 2 3
# Ignore recommendations to use "`mapfile` or `read -a`"
# when setting array variable
# shellcheck disable=SC2207
logFiles=( $(${FIND} ${DIR_LIBRARY} -name rdimport.log -size +1 -printf '%p:%s\n' | ${SORT}) )
# Clear *all* the log files if so desired.
if [[ -n "${clear_all}" ]] ; then
echo "Clearing ALL dropbox log files \c"
local -i c=1
for f in ${logFiles[*]} ; do
[[ -w "${f%:*}" ]] || { echo "Cannot write to log File '${f%:*}'." ; continue ; }
${CP} /dev/null "${f%:*}"
printf "."
((c++ % 50 == 0)) && echo
done
echo "\nDone. \c"
read -q foo\?"Press <Enter> to return to the menu. "
trap -
return "${returnValue}"
fi
if [[ -n "${logFiles[*]}" ]] ; then
echo "\nHere are all the rdimport log files I could find in '${DIR_LIBRARY}':"
${FMT} <<<${logFiles[*]} | ${SED} -r -e 's,^(.*/rdimport.log):([[:digit:]]+)$,(\2 bytes) \1,' | ${NL}
read logfileIndex\?"Type the number of the log file you want to clear and press <Enter>: "
until ((logfileIndex)) ; do
warning "You need to type a number between 1 and ${#logFiles}."
read logfileIndex\?"Please type the number of the log file you want to clear and press <Enter>: "
done
chosenFile=${logFiles[${logfileIndex}]%:*}
if [[ -w ${chosenFile} ]] ; then
if read -q proceed\?"About to clear '${chosenFile}'. Press 'y' to continue, any other key to cancel " ; then
if ${CP} /dev/null ${chosenFile} ; then
echo "\nCleared ${chosenFile}. "
else
warning "Hmmmm... I encountered an error while trying to clear '${chosenFile}' (${?}). Please pass this number and message on to a professional."
returnValue=2
fi
else
echo "\nDid NOT clear '${chosenFile}'. \c"
fi
else
warning "No permission to clear '${chosenFile}'. Please contact the authorities."
returnValue=1
fi
else
warning "Found NO rdimport log files containing data in '${DIR_LIBRARY}'."
fi
read proceed\?"Press <Enter> to continue. "
trap -
return "${returnValue}"
}
# Add a simple Event with the specified Cart number as the sole
# Pre-Import item.
function addSimpleEvent() {
local -r my_name=${1} ; shift
local -r feed_name="${1}" ; shift
local -r verbose=${1}
local -r oIFS="${IFS}"
local -i returnValue
local cart_number cart_title
local query
if ! okDatabaseStructure "EVENTS:name,EVENT_LINES:event_name+type+count+event_type+trans_type+cart_number,CART:number+title" ; then
returnValue=${?}
error "${0}() (${zsh_eval_context}): This version of ${my_name} is not compatible with Rivendell database version $(rdDatabaseVersion). You need to manually add an Event."
read ok\?"Press <Enter> to continue. "
return "${returnValue}"
fi
# The Cart title will be the same as feed_name if they added a
# dropbox.
if ! cart_number="$(rdCartNumberFromTitle ${feed_name})" ; then
warning "Unable to get the Cart number for '${feed_name}'."
return 2
trap -
fi
if [[ -z "${cart_number}" ]] ; then
warning "No Cart number with title '${feed_name}'."
return 3
fi
# The two SQL INSERT statements want to be as atomic as
# possible. Ignore these signals.
trap '' 0 1 2 3
# Step 1: create the barebones event.
if ! doSQL "insert into EVENTS (NAME) values ('${feed_name}')" ; then
warning "Unable to create new Event named '${feed_name}' (${?})."
trap -
return 4
fi
if ! event_name=$(doSQL "select NAME from EVENTS where NAME = '${feed_name}'") ; then
warning "Unable to find new Event named '${feed_name}' (${?})."
trap -
return 5
fi
if [[ -z "${event_name}" ]] ; then
warning "New Event named ${feed_name} is missing its Event Name?? Please seek professional help."
trap -
return 6
fi
# Step 2: create an EVENT_LINES row with the Cart number as its sole
# item. TYPE is 0 for the Pre-Import item, COUNT is 0 for the first
# item in Pre-Imports, EVENT_TYPE is 0 for "Cart", TRANS_TYPE is 0
# for "Play".
query="insert into EVENT_LINES (EVENT_NAME, TYPE, COUNT, EVENT_TYPE, TRANS_TYPE, CART_NUMBER)"
query="${query} values"
query="${query} ('${event_name}', 0, 0, 0, 0, ${cart_number})"
if ! doSQL "${query}" ; then
warning "Unable to create new Pre-Import item with Cart number ${cart_number} for Event '${cart_title}' (${?})."
# Avoid leaving an orphaned Event lying around.
doSQL "delete from EVENTS where NAME = '${event_name}'"
trap -
return 7
fi
trap -
IFS=$'\t' # Just a <Tab>.
# SC2046: This read is going to be word-split, but I am dealing with it.
# shellcheck disable=SC2046
if ! read -r cart_number event_name <<<$(doSQL "select CART_NUMBER, NAME from EVENTS join EVENT_LINES on NAME = EVENT_NAME where NAME = '${event_name}'") ; then
warning "Unable to find newly created Event for '${feed_name}' (${?})."
IFS="${oIFS}"
return 8
fi
IFS="${oIFS}"
logit "${my_name}" 1 "Added new Event '${event_name}' choosing ${cart_number} as Pre-Import item."
}
# Delete the Event event_name and its associated entries in
# EVENT_LINES.
function deleteSimpleEvent() {
local -r my_name=${1} ; shift
local -r event_name="${1}" ; shift
local -r verbose=${1}
if ! okDatabaseStructure "EVENTS:name,EVENT_LINES:event_name" ; then
error "${0}() (${zsh_eval_context}): This version of ${my_name} is not compatible with Rivendell database version $(rdDatabaseVersion). Please manually delete this Event."
read ok\?"Press <Enter> to continue. "
return 1
fi
# The two SQL DELETE statements want to be as atomic as
# possible. Ignore these signals.
trap '' 0 1 2 3
if ! doSQL "delete from EVENT_LINES where EVENT_NAME = '${event_name}'" ; then
warning "Trouble deleting Pre-Import items for Event '${event_name}'"
fi
if ! doSQL "delete from EVENTS where NAME = '${event_name}'" ; then
warning "Trouble deleting Event '${event_name}'. Please check this out."
trap -
return 2
fi
trap -
logit "${my_name}" 1 "Deleted Event '${event_name}'."
}
function editSchedule() {
local -r myName=${1} ; shift
local -r verbose=${1}
local minute oMinute hour oHour crontab ok
trap 'trap - ; return ;' 0 2 3
# Snag the current crontab for later processing.
# The variable CRONTAB actually *is* assigned.
# shellcheck disable=SC2153
crontab=$(${CRONTAB} -l)
# Give them the opportunity to change the existing schedule.
if ${GREP} -q 'podget-wrapper' <<<"${crontab:-X}" ; then
${FMT} <<EOF
The current schedule for downloading podcasts is as follows. This is the entire crontab entry. '${BOLD}pmw-podget-wraper${NORM}' is the tool used to launch and track '${BOLD}podget${NORM}', the ${myName} downloader app.
${BOLD}$(${GREP} 'podget-wrapper' <<<${crontab})${NORM}
EOF
if ! getYesNo "Do you want to change the schedule?" ; then
echo "\nLeaving the download schedule as it is."
read ok\?"Press <Enter> to continue. "
trap -
return
fi
# Pre-fill the vailues we will later prompt for.
minute=$(${AWK} '/^[^#].*podget-wrapper/{print $1}' <<<${crontab})
hour=$(${AWK} '/^[^#].*podget-wrapper/{print $2}' <<<${crontab})
fi
${FMT} <<EOF
${(C)myName} runs the 'podget-wrapper' back-end periodically in order to check for new episodes of podcasts. podget-wrapper checks all podcasts each time, downloading new episodes for each podcast as they appear.
Typically, 'podget-wrapper' runs from the system job scheduler once an hour every day. I'll assume you want to do that. You will need to update the cron job manually (using the 'crontab' command) only if you want a different schedule.
Valid hours are 0 - 23 and '*' (every hour).
EOF
unset ok
until [[ "${ok}" =~ y ]] ; do
oHour=${hour}
read hour\?"Type the hour(s) you want ${myName} to check for new podcasts (enter '*' for every hour): ${hour:+[${hour}] }"
[[ -z "${hour}" ]] && hour=${oHour}
until [[ "${hour}" = '*' ]] || [[ "${hour}" =~ [[:digit:],]+ ]] ; do
echo "You need to enter either an asterisk ('*'), or some combination of hour numbers and commas."
read hour\?"Type the hour(s) you want ${myName} to check for new podcasts (enter '*' for every hour): "
done
${FMT} <<EOF
Now I need to know how many times an hour you want to check for new podcasts. You can enter a single "minute" representing that minute of each hour, or you can enter multiple minutes separated with commas (','). Valid minutes are 0 - 59.
EOF
oMinute=${minute}
read minute\?"Enter the minute(s) of the hour(s) ('${hour}') you want to check for podcasts: ${minute:+[${minute}] }"
[[ -z "${minute}" ]] && minute=${oMinute}
# Note: we explicitely DO NOT permit 'every minute' here.
until [[ "${minute}" =~ ^[[:digit:],]+$ ]] ; do
echo "You need to enter combination of minute numbers and commas."
read minute\?"Type the minute(s) of the hour(s) ('${hour}') you want to check for podcasts: "
done
echo "Using 'hour: ${hour}' and 'minute: ${minute}' for the podcast download schedule."
if ! getYesNo "Press 'y' to commit this schedule, or 'n' to cancel" ; then
echo "Canceling this schedule change. Please try your call again later."
read ok\?"Press <Enter> to continue. "
trap -
return
fi
ok=y
done
(
${GREP} -v 'podget-wrapper' <<<${crontab}
echo "${minute} ${hour} * * * zsh @bindir@/podget-wrapper"
) | ${CRONTAB} -
${CAT} <<EOF
Here is the complete cron entry for downloading podcasts:
$(${CRONTAB} -l | ${GREP} --perl-regexp '^(#|.*podget-wrapper)')
EOF
read ok\?"Press <Enter> to continue. "
trap -
}
function editFile() {
local -r myName=${1} ; shift
local -r filename=${1} ; shift
local -r verbose=${1}
trap 'trap - ; return ;' 0 2 3
${VISUAL:-${EDITOR:-nano}} ${filename}
trap -
}
function cronEdit() {
local -r myName=${1} ; shift
local -r verbose=${1}
trap 'trap - ; return ;' 0 2 3
((verbose)) && echo "${myName}: directly editing crontab."
EDITOR=${VISUAL:-${EDITOR:-nano}} ${CRONTAB} -e
trap -
return
}
function addRDDropbox() {
local -r myName=${1} ; shift
local -r dirLibrary=${1} ; shift
local -r feedName=${1} ; shift
local -r feedEnclosureFileExt=${1} ; shift
local -r feedGroup=${1} ; shift
local -r verbose=${1}
local -r oIFS="${IFS}"
local createANewDropbox=0
local returnValue=1
local desiredNumber dropboxCartNumber
if ! okDatabaseStructure DROPBOXES:id+path+to_cart+group_name "${verbose}" ; then
returnValue="${?}"
error "${0}() (${zsh_eval_context}): This version of ${myName} is not compatible with Rivendell database version $(rdDatabaseVersion). You need to create a dropbox manually."
read ok\?"Press <Enter> to continue. "
return "${returnValue}"
fi
##########################################################################################
## See whether there is a dropbox with a matching pathname.
##########################################################################################
query="select d.ID,d.PATH,d.TO_CART,d.GROUP_NAME from DROPBOXES d where d.PATH like '${DIR_LIBRARY}/${feedGroup}/${feedName}/%'"
IFS=$'\t' # Just a <Tab>
# ShellCheck is a bit too aggressive in its quoting suggestions.
# shellcheck disable=SC2046
read dropboxID dropboxPATH dropboxCARTNUM dropboxGROUP <<<$(doSQL "${query}")
IFS="${oIFS}"
if ((dropboxID)) ; then
# We *want* the quotes to be treated literally.
# shellcheck disable=SC2089
info="It appears as if Rivendell dropbox '${dropboxID}' watches for files at '${dropboxPATH}'."
if ((dropboxCARTNUM)) ; then
cartTITLE="$(rdCartTitleFromNumber ${dropboxCARTNUM} ${verbose})"
info="${info} The dropbox uses the CART '${cartTITLE}' (number ${dropboxCARTNUM})."
${FMT} <<<"${info}"
else
info="${info} This dropbox assigns new carts for each podcast episode in Group '${dropboxGROUP}'."
${FMT} <<<"${info}"
fi
if getYesNo "Do you want to use this dropbox for the feed '${feedName}'?" ; then
echo "OK, using existing dropbox."
returnValue=0
else
echo "OK, creating a new dropbox."
createANewDropbox=1