Debian Codegraph @

podget

raw symbols SCIP
1 #!/usr/bin/env bash
2
3 # ----------------------------------------------------------------------------------------------------------------------------------
4 # Filename: podget {{{
5 # Maintainer: Dave Vehrs (dvehrs on Github.com)
6 # Copyright: (c) 2005-2025 Dave Vehrs
7 #
8 # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
9 # License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any
10 # later version.
11 #
12 # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
13 # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 # details.
15 #
16 # Description: Podget is a simple bash script to automate the downloading and
17 # organizing of podcast content.
18 # Dependencies: bash, coreutils, findutils, grep, gawk or mawk, libc-bin (for iconv), sed, and wget.
19 # Installation: cp podget.sh /usr/local/bin
20 # chmod 755 /usr/local/bin/podget.sh }}}
21 # ----------------------------------------------------------------------------------------------------------------------------------
22 # Debug and Info messages {{{
23
24 # To enable debugging or informational messages, add option to command line:
25 #
26 # $ INFO= podget : Enable only Podget INFO messages.
27 # $ DEBUG=1 podget : Enable Podget INFO and DEBUG messages.
28 # $ DEBUG=2 podget : Enable Podget INFO and DEBUG messages with Bash shell option for xtrace.
29 # $ DEBUG=3 podget : Enable Podget INFO and DEBUG messages with Bash shell options for xtrace, and verbose.
30 # $ DEBUG=4 podget : Enable Podget INFO and DEBUG messages with Bash shell options for xtrace, functrace and a debug trap.
31 #
32 # NOTE: The output of the Bash shell options for verbose and the debug trap (as we have it configured) are effectively so similar
33 # that enabling both at the same time can be redundant and confusing.
34
35 # Default DEBUG Disabled (Deletion of temporary files allowed), configured
36 # to allow its setting to be overridden from the command line.
37 DEBUG=${DEBUG:-0}
38
39 # Default DEBUG string leader. This will be used until the user's configuration file (generally podgetrc) is read then if they have
40 # a custom string leader defined it will be used.
41 DEBUG_LEADER="DEBUG --"
42
43 # Default INFO string leader.
44 # If you want to customize this string, add its declaration to your user configuration file (generally podgetrc) like the one
45 # for DEBUG_LEADER
46 INFO_LEADER="INFO --"
47
48 # Function: __MSG_DEBUG {{{
49 # Display additional informational messages to user.
50 # General rules for use:
51 # - For one part messages, the message to user should be less than 72 characters long to fit on one 80 character line.
52 # - For two part messages, the first part can be up to 17 characters long and the second part can be up to 55 characters long to fit.
53 # - These are very general rules because printf will not overlap sections when they are longer than they should be. So you can
54 # have a longer first part when the second is shorter and still fit on an 80 character line. However things will line up best if
55 # you follow these guidelines.
56 # ARGUMENTS:
57 # ${1} == One part message.
58 # ${2} == Second part of two part message.
59 __MSG_DEBUG() {
60 local PART1="${1}"
61 local PART2="${2:-UNConfigured}"
62 # This looks a bit unusual but allows us to have a local variable that inherits it's value from when it is called. Technically
63 # the second part is the global value for the variable of name "DEBUG_LEADER" being assigned to local variable of the same name.
64 local DEBUG_LEADER="${DEBUG_LEADER}"
65 local DEBUG="${DEBUG}"
66
67 # Test if INFO is set (may be empty string).
68 if [[ "${DEBUG}" -gt 0 ]]; then
69 if [[ "${PART2}" == "UNConfigured" ]]; then
70 printf '%s %s\n' "${DEBUG_LEADER}" "${PART1}"
71 else
72 printf '%s %-20s : %s\n' "${DEBUG_LEADER}" "${PART1}" "${PART2}"
73 fi
74 fi
75 }
76 # }}}
77
78 # Function: __MSG_INFO {{{
79 # Display additional informational messages to user. Each message should be less that 57 Characters so that the whole line averages
80 # less than 80 characters (this limit is especially important for two part messages.
81 # ARGUMENTS:
82 # ${1} == One part message.
83 # ${2} == Second part of two part message.
84 __MSG_INFO() {
85 local PART1="${1}"
86 local PART2="${2:-UNConfigured}"
87 # This looks a bit unusual but allows us to have a local variable that inherits it's value from when it is called. Technically
88 # the second part is the global value for the variable of name "INFO_LEADER" being assigned to local variable of the same name.
89 local INFO_LEADER="${INFO_LEADER}"
90
91 # Test if INFO is set (may be empty string).
92 if [[ -n "${INFO+set}" ]]; then
93 if [[ "${PART2}" == "UNConfigured" ]]; then
94 printf '%s %s\n' "${INFO_LEADER}" "${PART1}"
95 else
96 printf '%s %-20s : %s\n' "${INFO_LEADER}" "${PART1}" "${PART2}"
97 fi
98 fi
99 }
100 # }}}
101
102 # NOTE: We could use a simple test for if DEBUG is set or not, even without a value assigned but unfortunately we previously
103 # used the values of 0 for disabled and 1 for enabled for other tests. To keep backwards compatibility, we are going to
104 # keep 0 as the default disabled value. Therefore once we confirm DEBUG is set, we then need to test for values to know
105 # which modes to enable.
106
107 if [[ -n "${DEBUG+set}" ]]; then
108 if (( DEBUG >= 1 )); then
109 echo "${DEBUG_LEADER} Level ${DEBUG} debugging enabled."
110 INFO=1
111 if (( DEBUG >= 2 )); then
112 set -o xtrace
113 if (( DEBUG == 3 )); then
114 set -o verbose
115 elif (( DEBUG >= 4 )); then
116 # Enable functrace so that DEBUG and RETURN traps are inherited by functions.
117 set -o functrace
118 # NOTE: Debug trap sends it's output to STDERR (2) so that it does not
119 # cause errors during command substitutions ( $(..) or `..` ).
120 # This can happen when functrace is enabled.
121 trap 'echo "DEBUG LINE ${LINENO}: ${BASH_COMMAND}" >&2' DEBUG
122
123 fi
124 fi
125 fi
126 fi
127
128 #
129 # }}}
130 # ----------------------------------------------------------------------------------------------------------------------------------
131 # Global Variables {{{
132
133 # Default VERBOSITY
134 # 0 == silent
135 # 1 == Warning messages only.
136 # 2 == Progress and Warning messages.
137 # 3 == Debug, Progress and Warning messages.
138 # 4 == All messages and wget set to maximum VERBOSITY.
139 # NOTE: Verbosity is not a local option because it is needed before and after core function runs. This is the global default but it
140 # can be changed from within podgetcore generally by command line options.
141 VERBOSITY=2
142
143 # }}}
144 # ----------------------------------------------------------------------------------------------------------------------------------
145 # Early Functions {{{
146 # Note: These are functions that may be called by bash traps or other things that are configured sooner than the section for other
147 # functions. This should be kept as lean as possible.
148
149 # Function: CleanupAndExit {{{
150 # Closes session and removes lock file (if it exists)
151 # ARGUMENTS:
152 # ${1} == Exit Status to report.
153 CleanupAndExit() {
154 local EXITSTATUS=${1}
155 local VERBOSITY="${VERBOSITY}"
156
157 if (( VERBOSITY >= 2 )) ; then
158 #echo -en "\nClosing session"
159 printf '\n%s' "Closing session"
160 fi
161 if [[ -n ${DIR_SESSION+set} && -f ${DIR_SESSION}/podget.$$ ]]; then
162 if (( DEBUG == 0 )); then
163 if (( VERBOSITY >= 2 )) ; then
164 printf '%s' " and removing lock file"
165 fi
166 if (( VERBOSITY >= 4 )) ; then
167 echo
168 rm -fv "${DIR_SESSION}"/podget.$$
169 else
170 rm -f "${DIR_SESSION}"/podget.$$
171 fi
172 else
173 __MSG_DEBUG "Not deleting ${DIR_SESSION}/podget.$$"
174 fi
175 fi
176 if (( (VERBOSITY >= 2) && (VERBOSITY <= 3) )); then
177 printf '%s\n' "."
178 elif (( (VERBOSITY == 1) || (VERBOSITY > 3) )); then
179 echo
180 fi
181
182 exit "${EXITSTATUS}"
183 }
184 # }}}
185
186 # Function: ExitOnError {{{
187 # The commands of this function will trigger Shellcheck SC2317 (Command appears to be unreachable)
188 # because the function is called from a trap so we can ignore this message.
189 # ARGUMENTS:
190 # ${1} == Line number the error happened on
191 # ${2} == Exit status of the error
192 # ${3} == If the error occurred in a function, the name of the function.
193 # shellcheck disable=SC2317
194 ExitOnError() {
195 # Name of script
196 local JOB_NAME
197 JOB_NAME=$(basename "$0")
198 # The following three variables are configured with a default value in case
199 # the function is called without options set.
200 local LINENUM="${1:-"Unconfigured"}" # Line with error
201 local EXITSTATUS="${2:-"Unconfigured"}" # exit status of error
202 local FUNCTION="${3:-"Unconfigured"}" # If error occurred in a function, its name will be listed.
203
204 printf '\n%s\n %-15s %s\n' "Error:" "Script:" "${JOB_NAME}"
205
206 # Function line only appears if it has been set to value other than the
207 # default. Works on the assumption that "Unconfigured" is not likely to be
208 # chosen as a function name.
209 if [[ ${FUNCTION} != "Unconfigured" ]]; then
210 printf ' %-15s %s\n' "Function:" "${FUNCTION}"
211 fi
212
213 printf ' %-15s %s\n %-15s %s\n' "At line:" "${LINENUM}" "Exit Status:" "${EXITSTATUS}"
214
215 printf '\n%s\n' "Context:"
216 # Test is awk installed, if so use it. If not, then use tools from coreutils.
217 if hash awk 2>/dev/null; then
218 # This line works and adds a ">>>" to designate the offending line but adds
219 # awk as a script dependency.
220 awk 'NR>L-4 && NR<L+4 { printf "%-5d%3s%s\n",NR,(NR==L?">>>":""),$0 }' L="${LINENUM}" "${0}"
221 else
222 # This line works and only depends on coreutils
223 pr -tn "${0}" | tail -n+$((LINENUM - 3)) | head -n7
224 fi
225
226 CleanupAndExit 1
227 }
228 # }}}
229
230 # }}}
231 # ----------------------------------------------------------------------------------------------------------------------------------
232 # Exit Codes {{{
233
234 # "Reserved" Exit codes
235 # 1 General Error
236 # 2 Misuse of shell built-ins
237 # 126 Command invoked cannot execute
238 # 127 Command not found
239 # 128+n Invalid argument to exit
240 # 130 Script terminated by Control-C (128+2)
241 # 143 Script terminated by TERM signal (128+15)
242
243 # "Our" Exit codes
244
245 # Display Help (set to '0' because it is an valid exit condition, not an error.)
246 ERR_DISPLAYHELP=0
247
248 # Library directory not defined.
249 ERR_LIBNOTDEF=50
250
251 # Library directory available space below limit
252 ERR_LIBLOWSPACE=51
253
254 # Libc6 not installed. Cannot convert UTF16 feeds.
255 ERR_LIBC6NOTINSTALLED=60
256
257 # Another running session already exists.
258 ERR_RUNNINGSESSION=70
259
260 # OPML import error.
261 ERR_IMPORTOPML=80
262
263 # OPML export error.
264 ERR_EXPORTOPML=90
265
266 # }}}
267 # ----------------------------------------------------------------------------------------------------------------------------------
268 # Traps {{{
269
270 # FUNCNAME is declared with a default value in case the trap is triggered while
271 # outside a function.
272 trap 'ExitOnError ${LINENO} ${?} ${FUNCNAME:-Unconfigured}' ERR
273
274 # trap to run CLEANUP function if program receives a TERM (kill) or INT (ctrl-c) signal
275 # - CLEANUP called in line for other normal exits.
276 trap 'CleanupAndExit 143' TERM
277 trap 'CleanupAndExit 130' INT
278
279 # }}}
280 # ----------------------------------------------------------------------------------------------------------------------------------
281 # Set Shell Options {{{
282
283 set -o errexit
284 set -o nounset
285 set -o pipefail
286
287 # Enable errtrace so that the ERR trap is inherited by functions
288 set -o errtrace
289
290 # Enabling inheritance of errexit by command substitution subshells, this was added in Bash 4.4
291 # NOTE: Test command is run within a subshell where pipefail is disabled.
292 if (set +o pipefail && shopt inherit_errexit 2>&1 | grep -q invalid) ; then
293 echo "Bash added the 'inherit_errexit' shell option in version 4.4, please upgrade."
294 exit 1
295 fi
296 shopt -s inherit_errexit
297
298 # Enable extended glob matches.
299 shopt -s extglob
300
301 # Note: Limits on errexit functionality.
302 #
303 # Important to remember that there are occasions that a script will not immediately exit when a command exits with a
304 # non-zero status. These conditions mostly make sense but can have an unexpected effect when there is an error in a function
305 # that is called from an if statement. For Podget, this was found working with a simulated error within the ArrayContains
306 # function so even though the function inherited the errexit setting, it was ignored for reasons laid out in the man page.
307 # For this reason, we should keep in mind that functions that are to be used in the ways that may cause errexit to be ignored
308 # should be kept as concise and pithy as possible to reduce the opportunity for errors.
309 #
310 # For functions with a command that may exit with a non-zero status that cannot be avoided then it may be necessary to add
311 # manual checking for exit status after the command runs to determine if the script should stop or not.
312 #
313 # Example of handling such a command:
314 # Command-To-Run
315 # if [ $? -ne 0 ]; then echo "ERROR"; exit 1; fi
316 #
317 # From Bash Man page on the set option for errexit (-e):
318 # -e Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command
319 # (see SHELL GRAMMAR above), exits with a non-zero status. The shell does not exit if the command that fails is part of
320 # the command list immediately following a while or until keyword, part of the test following the if or elif reserved
321 # words, part of any command executed in a && or || list except the command following the final && or ||, any command
322 # in a pipeline but the last, or if the command's return value is being inverted with !. If a compound command other
323 # than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit.
324 # A trap on ERR, if set, is executed before the shell exits. This option applies to the shell environment and each
325 # subshell environment separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before
326 # executing all the commands in the subshell.
327 #
328 # If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed
329 # within the compound command or function body will be affected by the -e setting, even if -e is set and a command
330 # returns a failure status. If a compound command or shell function sets -e while executing in a context where -e is
331 # ignored, that setting will not have any effect until the compound command or the command containing the function
332 # call completes.
333 # }}}
334 # ----------------------------------------------------------------------------------------------------------------------------------
335 # Text for command line help option {{{
336
337 : << HELP_STEXT
338 -c --config <FILE> Name of configuration file to use.
339 --create-config <FILE> Exit immediately after creating configuration file.
340 -C --cleanup Skip downloading and only run cleanup loop.
341 --cleanup_simulate Skip downloading and simulate running
342 cleanup loop.
343 Display files to be deleted.
344 --cleanup_days <COUNT> Number of days to retain files. Anything
345 older will be removed.
346 -d --dir_config <DIRECTORY> Directory that configuration files are
347 stored in.
348 --dir_session <DIRECTORY> Directory that session files are stored in.
349 -f --force Force download of items from each feed even
350 if they have already been downloaded.
351 --import_opml <FILE or URL> Import servers from OPML file or
352 HTTP/FTP URL.
353 --export_opml <FILE> Export serverlist to OPML file.
354 --import_pcast <FILE or URL> Import servers from iTunes PCAST file or
355 HTTP/FTP URL.
356 -l --library <DIRECTORY> Directory to store downloaded files in.
357 -n --no-playlist Do not create M3U playlist of new items.
358 -p --playlist-asx In addition to the default M3U playlist,
359 create an ASX Playlist. M3U playlist must be
360 created to convert to ASX.
361 --playlist-per-podcast Create playlist of new items for each podcast feed.
362 -r --recent <COUNT> Download only the <count> newest items from
363 each feed.
364 --serverlist <LIST> Serverlist to use.
365 -s --silent Run silently (for cron jobs).
366 --verbosity <LEVEL> Set verbosity level (0-4).
367 -v Set verbosity to level 1.
368 -vv Set verbosity to level 2.
369 -vvv Set verbosity to level 3.
370 -vvvv Set verbosity to level 4.
371 -h --help Display help.
372 HELP_STEXT
373
374 # }}}
375 # ----------------------------------------------------------------------------------------------------------------------------------
376 # Text for default configuration files {{{
377
378 : << TEXT_DEFAULT_CONFIG
379 # ----------------------------------------------------------------------------------------------------------------------------------
380 # Podget configuration file created by version @VERSION@
381 # [ NOTE: Do not delete version line as it will be used by future versions to
382 # to test if configuration files have been updated with any required changes.
383 # ----------------------------------------------------------------------------------------------------------------------------------
384 # File name and location configuration:
385
386 # Name of Server List configuration file
387 CONFIG_SERVERLIST=@SERVERLIST@
388
389 # Directory to store session files
390 # If this option is not configured then by default podget will place the session files in the directory defined by TMPDIR/podget or
391 # if it is not defined in the users shell then the session files will be placed in the directory /tmp/podget.
392 # If you prefer a different location, then configure this variable.
393 # DIR_SESSION=@HOME@/tmp/podget
394
395 # Directory where to store downloaded files
396 DIR_LIBRARY=@HOME@/POD
397
398 # Directory to store logs in
399 # By default, logs are stored in DIR_LIBRARY/.LOG
400 # If you prefer a different location, then configure this variable.
401 # DIR_LOG=@HOME@/POD/LOG
402
403 # Set logging file names
404 LOG_FAIL=errors
405 LOG_COMPLETE=done
406
407 # ----------------------------------------------------------------------------------------------------------------------------------
408 # Download Options:
409
410 # Wget base options
411 # Commonly used options:
412 # -c Continue interupted downloads - While this flag is commonly used there are feeds that it can
413 # cause "403 Forbidden" errors.
414 # -nH No host directories (overrides .wgetrc defaults if necessary)
415 # --proxy=off To disable proxy set by environmental variable http_proxy
416 # --no-check-certificate To disable HTTPS certificate checks. Useful for sites that may be using self-signed cerficates
417 # and not those from a trusted service authority.
418 # --prefer-family=IPv4/IPv6 When DNS provides a choice of addresses to connect to a host, attempt to connect to the specified
419 # address family first. If all addresses of the given family fail then the other family will be
420 # tried. If set to 'none' then the addresses will be tried in the order provided by the server
421 # regardless of which family they are in (this is effectively the default option).
422 #
423 # If you wish to force the use of IPv4 addresses only then you can use the "-4" or "--inet4-only"
424 # options. Conversely, if you want to force the use of IPv6 addresses then you can set the "-6"
425 # or "--inet6-only" options.
426 # --content-disposition [EXPERIMENTAL FEATURE] Wget will look for and use "Content-Disposition" headers received from the
427 # server. This can result in extra round-trips to the server for a "HEAD" request. This option
428 # is useful for servers that use the "Content-Disposition" header to hold the filename of the
429 # downloaded file rather than appending it to the URL. This has the potential to make some of
430 # Podget's FILENAME_FORMATFIX options unneeded.
431 #
432 # WARNING: Enabling this flag disables any download progress information from being passed on to
433 # the user. To debug errors that may occur during sessions with this flag enabled, it may be
434 # necessary to enable DEBUG and then examine the temporary files that are not deleted in
435 # DIR_SESSION.
436 #
437 # NOTE: This can be enable globally for all feeds here or if you want to enable it for only a few
438 # specific feeds, you can add "OPT_CONTENT_DISPOSITION" to their line in your serverlist.
439 # --user-agent=<string> By default Podget will identify itself as "Podget". If that does not work or you want to
440 # specify a custom user agent you can do so here. If the agent is a single word then it does not
441 # need to be quoted. If it is a longer string with spaces then it will need to be quoted and have
442 # it's quotes double escaped.
443 # Examples:
444 # --user-agent=Mozilla
445 # --user-agent=Chrome
446 # --user-agent=\\\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\\\"
447 # --user-agent=\\\"Agent 007\\\"
448 # --user-agent=\\\"Dread Pirate Roberts\\\"
449 #
450 # Wget options that include spaces need to be surrounded in quotes.
451 #
452 # WGET_BASEOPTS="-c -nH --user-agent=\\\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\\\""
453 # WGET_BASEOPTS="-c -nH --user-agent=Mozilla"
454 # WGET_BASEOPTS="-c --proxy=off --no-check-certificate"
455 # WGET_BASEOPTS="-nH --proxy=off --content-disposition"
456 # WGET_BASEOPTS="-c --prefer-family=IPv4"
457 # WGET_BASEOPTS="-c --prefer-family=IPv6"
458 WGET_BASEOPTS="-c -nH"
459
460 # Most Recent
461 # 0 == download all new items.
462 # 1+ == download only the <count> most recent
463 MOST_RECENT=0
464
465 # Force
466 # 0 == Only download new material.
467 # 1 == Force download all items even those you've downloaded before.
468 FORCE=0
469
470 # Autocleanup of old playlists and the files they list.
471 # 0 == disabled
472 # 1 == delete any old content
473 CLEANUP=0
474
475 # Number of days to keep files. Cleanup will remove anything
476 # older than this.
477 CLEANUP_DAYS=7
478
479 # Stop downloading if available space on the partition drops below value (in KB)
480 # default: 614400 (600MB)
481 MIN_SPACE=614400
482
483 # ----------------------------------------------------------------------------------------------------------------------------------
484 # Playlist Options:
485
486 # Disable playlist creation [ No need to comment out other playlist variables ]
487 # 0 == create
488 # 1 == do not create
489 NO_PLAYLIST=0
490
491 # Build playlists (comment out or set to a blank string to accept default format: New-).
492 PLAYLIST_NAMEBASE=New-
493
494 # Date format for new playlist names
495 # +%F = YYYY-MM-DD like 2014-01-15 (DEFAULT)
496 # +%m-%d-%Y = MM-DD-YYYY like 01-15-2014
497 # For other options 'man date'
498 #
499 # Date options that include spaces need to be surrounded in quotes.
500 #
501 DATE_FORMAT=+%F
502
503 # ASX Playlists for Windows Media Player
504 # 0 == do not create
505 # 1 == create
506 ASX_PLAYLIST=0
507
508 # ----------------------------------------------------------------------------------------------------------------------------------
509 # Filename Suffix:
510
511 # Add suffix to the filename of every file downloaded to allow for subsequent scripts to detect the newly downloaded files and work
512 # on them. Examples of this would be scripts to run id3v2 to force a standard genre for all MP3 files downloaded or to use mp3gain
513 # to normalize files to have the same volume.
514 #
515 # A period (.) will automatically be added between the filename and tag like so:
516 # filename.mp3.newtag
517 #
518 # Tags will not be added to filenames as they are added to the playlists. It will be necessary for any script that you run to
519 # process the files remove the tag for the playlists to work.
520 #
521 # If this variable is undefined or commented out, then by default no suffix will be added.
522
523 # FILENAME_SUFFIX="newtag"
524
525 # ----------------------------------------------------------------------------------------------------------------------------------
526 # Downloaded Filename Cleanup Options:
527 #
528 # These options are for the filenames downloaded from the feeds. We will try to clean then up rather than interrupting the script
529 # execution.
530
531 # Filename Cleanup: For FAT32 filename compatability (Feature Request #1378956)
532 # Tested with the following characters: !@#$%^&*()_-+=||{[}]:;"'<,>.?/
533 #
534 # The \`, \" and \\ characters need to be escaped with a leading backslash.
535 #
536 # Bad Character definitions need to be surrounded in quotes.
537 #
538 # NOTE: FILENAME_BADCHARS is also used to test for characters that commonly cause errors in directory names. This can cause
539 # FILENAME_BADCHARS to be reported as part of an error for configuration issues with DIR_SESSION, DIR_LOG, DIR_LIBRARY and podcast
540 # FEED_NAME and FEED_CATEGORY.
541 FILENAME_BADCHARS="\`~!#$^&=+{}*[]:;\"'<>?|\\"
542
543 # Filename Replace Character: Character to use to replace any/all
544 # bad characters found.
545 FILENAME_REPLACECHAR=_
546
547 # When you run podget at a VERBOSITY of 3 or 4, it may appear that the filename format fixes are done out of order. That is because
548 # they are named as they are created and as new fixes have been developed, those with more detailed exclusionary conditions have had
549 # to be done before those with more generic conditions. Looking for improvements to fix this issue.
550
551 # Filename Cleanup 2: Some RSS Feeds (like the BBC World News Bulletin)
552 # download files with names like filename.mp3?1234567. Enable this mode
553 # to fix the format to filename1234567.mp3.
554 # 0 == disabled
555 # 1 == enabled (default)
556 FILENAME_FORMATFIX=1
557
558 # Filename Cleanup 3: Filenames of feeds hosted by LBC Plus corrupted.
559 # Fixed per MoonUnit's feature request (#1660764)
560 #
561 # Takes an URL that looks like: http://lbc.audioagain.com/shared/audio/stream.mp3?guid=2007-03/14<...snip>
562 # <snip...>a7766e8ad2748269fd347eaee2b2e3f8&amp;source=podcast.php&amp;channel_id=88
563 #
564 # Which normally creates a file named: a7766e8ad2748269fd347eaee2b2e3f8&amp;source=podcast.php&amp;channel_id=88
565 #
566 # This fix extracts the date of the episode and changes the filename to 2007-03-14.mp3
567 # 0 == disabled
568 # 1 == enabled (default)
569 FILENAME_FORMATFIX2=1
570
571 # Filename Cleanup 4: Filenames of feeds hosted by CatRadio.cat need fixing.
572 # Fixed per Oriol Rius's Bug Report (#1744705)
573 #
574 # Downloaded filenames look like: 1189153569775.mp3?programa=El+mat%ED+de+Catalunya+R%E0dio&amp;podcast=y
575 # This fix removes everything after the .mp3
576 #
577 # NOTE: Testing in 2017 reveals changes in CatRadio's URL format that hampers this fix.
578 #
579 # Downloaded filenames now look like: 1487257264030.mp3&programa=Bon+dia%2C+malparits%21&var10=Neix+%2BCatR%E0dio%2C+el+dial+digital+de+Catalunya+R%E0dio&var11=video&var15=1783&var20=Podcast&var29=Audio&var3=951439&var14=951439&v25=Catalunya+R%E0dio&var19=16/02/17&var12=Tall&var18=45194
580 #
581 # Two changes cause issues:
582 # 1. Change of '?' to '&' for designating options.
583 # 2. Use of forward slashes in date (var19) mess up some of our other filename extraction.
584 #
585 # However the fix for these podcasts is now simpler. If in our serverlist, we use either
586 # the OPT_FILENAME_LOCATION or OPT_CONTENT_DISPOSTION option for these feedlists then the
587 # filename will be correctly extracted. This leaves us with a long number as the filename,
588 # however if we also enable the OPT_FILENAME_RENAME_MDATE option then the filename is prefixed
589 # with the last modification date of the file which helps list the files in an order that
590 # makes sense.
591 #
592 # 0 == disabled (default)
593 # 1 == enabled
594 FILENAME_FORMATFIX3=0
595
596 # Filename Cleanup 5: When the filename is part of the URL and the actual filename stays the same for
597 # all items listed.
598 #
599 # Download URLs look like: http://feeds.theonion.com/~r/theonion/radionews/~5/213589629/podcast_redirect.mp3
600 # Where 213589629 is the unique filename.
601 #
602 # This filename change is disabled by default because it may cause unintended changes to the filename.
603 #
604 # 0 == disabled (default)
605 # 1 == enabled
606 FILENAME_FORMATFIX4=0
607
608 # Filename Cleanup 6: Remove "?referrer=rss" from the end of filenames as included in some feeds like
609 # those from Vimcasts.org. Setup to work for MP3, M4V, OGG and OGV files.
610 #
611 # Feed URLs: http://vimcasts.org/feeds/ogg
612 # http://vimcasts.org/feeds/quicktime
613 #
614 # In the feed, enclosure URLs look like: http://media.vimcasts.org/videos/1/show_invisibles.ogv?referrer=rss
615 #
616 # 0 == disabled
617 # 1 == enabled (default)
618 FILENAME_FORMATFIX5=1
619
620 # Filename Cleanup 7: Removes the trailing part of the filename after the '?'.
621 # Fixed at the request of Joerg Schiermeier
622 #
623 # For dealing with enclosures like those formatted in the ZDF podcast.
624 # Feed URL: http://www.zdf.de/ZDFmediathek/podcast/1193018?view=podcast
625 # Example enclosure:
626 # http://podfiles.zdf.de/podcast/zdf_podcasts/101103_backstage_afo_p.mp4?2010-11-03+06-42
627 #
628 # 0 == disabled
629 # 1 == enabled (default)
630 FILENAME_FORMATFIX6=1
631
632 # Filename Cleanup 8:
633 # This fix is for feeds that assign the same filename to be downloaded for each
634 # enclosure and then embedded the actual filename of the object to be saved in
635 # the media_url= parameter. This fix extracts that name and uses it for the
636 # saved file.
637 #
638 # 0 == disabled
639 # 1 == enabled (default)
640 FILENAME_FORMATFIX7=1
641
642 # Filename Cleanup 9:
643 # This fix is for feeds like Smodcast. It removes the "?client_id=<string>"
644 # from the end of each enclosure url in the feed.
645 #
646 # NOTE: To fully fix the filenames on feeds like Smodcast, this fix should
647 # be used in conjunction with FILENAME_FORMATFIX4.
648 #
649 # Example URL: http://api.soundcloud.com/tracks/62837276/stream.mp3?client_id=a427c512429c9c90e58de7955257879c
650 # Fixed filename: 62837276_stream.mp3
651 #
652 # 0 == disabled
653 # 1 == enabled (default)
654 FILENAME_FORMATFIX8=1
655
656 # Filename Cleanup 10:
657 #
658 # This is a fix for podcast feeds formatted like those for Audioboo. Removes everything after the ?
659 # in the filename. Attempted to make this fix generic enough to work with a variety of feeds of mp3, mp4,
660 # ogg and ogv files.
661 #
662 # Feed URL: http://audioboo.fm/users/39903/boos.rss
663 # Example URL: http://audioboo.fm/boos/1273271-mw-123-es-wird-fruhling.mp3?keyed=true&amp;source=rss
664 # Fixed Filename: 1273271-mw-123-es-wird-fruhling.mp3
665 #
666 # NOTE: On Aug 30 2018, this fix was updated to also fix feeds formated like those from viertausendhertz.de.
667 #
668 # Feed URL: http://viertausendhertz.de/feed/podcast/systemfehler
669 # Example URL: https://viertausendhertz.de/podcast-download/1538/sf04.mp3?v=1470947681&#038;source=feed
670 # Fixed Filename: sf04.mp3
671 #
672 # 0 == disabled
673 # 1 == enabled (default)
674 FILENAME_FORMATFIX9=1
675
676 # Filename Cleanup 11:
677 #
678 # This is an attempt to fix feeds hosted on Apple ITunes. The enclosure URL from these feeds defines the
679 # the filename as a long string of numbers and letter. It's not very descriptive. However, after the
680 # filename and a '?', in the information passed down to the application as part of the URL, we can
681 # extract the episode name for each podcast. It is that name that this fix will use for the filename,
682 # with a few character replacements to insure good filenames.
683 #
684 # 0 == disabled
685 # 1 == enabled (default)
686 FILENAME_FORMATFIX10=1
687
688 # ----------------------------------------------------------------------------------------------------------------------------------
689 # DEBUG
690 #
691 # Enabling debug will:
692 # 1. Stop podget from automatically deleting some temporary files in DIR_SESSION.
693 # 2. Enable additional messages to track progress.
694 #
695 # 0 == disabled (default)
696 # 1 == enabled
697 # ${DEBUG:-0} == Sets DEBUG to disabled if it is not already set. This allows the user to enabled it
698 # from the command line with "DEBUG=1 podget"
699 #
700 #DEBUG=${DEBUG:-0}
701
702 # ----------------------------------------------------------------------------------------------------------------------------------
703 TEXT_DEFAULT_CONFIG
704
705 : << TEXT_DEFAULT_SERVERLIST
706 # Default Server List for podget
707 #
708 # Default format with category and name:
709 # <url> <category> <name>
710 #
711 # Alternate Formats:
712 # 1. With a category but no name.
713 # <url> <category>
714 # 2. With a name but no category (2 ways).
715 # <url> No_Category <name>
716 # <url> . <name>
717 # 3. With neither a category or name.
718 # <url>
719 #
720 # For additional formating documentation, please refer to 'man podget'.
721 #
722 #FEEDS:
723 # ----------------------------------------------------------------------------------------------------------------------------------
724 # Using TITLES from Feed:
725 http://thelinuxlink.net/tllts/tllts.rss LINUX The Linux Link OPT_FILENAME_RENAME_TITLETAG
726
727 TEXT_DEFAULT_SERVERLIST
728
729 : << TEXT_ASX_BEGINNING
730 <ASX version = "3.0">
731 <PARAM NAME = "Encoding" VALUE = "UTF-8" />
732 <PARAM NAME = "Custom Playlist Version" VALUE = "V1.0 WMP8 for CE" />
733 TEXT_ASX_BEGINNING
734
735 : << TEXT_ASX_END
736 </ASX>
737 TEXT_ASX_END
738
739 # }}}
740 # ----------------------------------------------------------------------------------------------------------------------------------
741 # Functions {{{
742 # NOTE: For consistency, function names should be in what is called Pascal Case. This is a variation of Camel Case but the first
743 # letter of the first word is also capitalized.
744
745 # Function: ArrayContains {{{
746 # Test if Array contains element.
747 # Returns 0 if found, or 1 if not found.
748 # ARGUMENTS:
749 # ${1} == String to search for
750 # ${2} == Array to search within (also called ${@:2})
751 # NOTE: ArrayContains will not respect the errexit shell option because it is generally called from an if statement. So best to
752 # keep functions like this pithy.
753 ArrayContains() {
754 local element
755 for element in "${@:2}"; do [[ "${element}" =~ ^"${1}".* ]] && return 0; done
756 return 1
757 }
758 # }}}
759
760 # Function: CompareStringInString {{{
761 # The commands of this function will trigger Shellcheck SC2317 (command appears to be unreachable)
762 # because I never actually use this function but keep it here for historical reasons.
763 # ARGUMENTS:
764 # ${1} == String to compare to
765 # ${2} == Substring to look for in first string
766 # shellcheck disable=SC2317
767 CompareStringInString() {
768 echo "Enter Compare ..."
769 echo "1 == ${1}"
770 echo "2 == ${2}"
771 case "${2}" in
772 *"${1}" )
773 echo "Found!"
774 return 0
775 ;;
776 esac
777 return 1
778 }
779 # }}}
780
781 # Function: DisplayShortHelp {{{
782 # Displays general message with command line options.
783 # ARGUMENTS: <none>
784 DisplayShortHelp() {
785 echo; echo "Usage $0 [options]"; echo
786 sed --silent -e '/HELP_STEXT$/,/^HELP_STEXT/p' "$0" | sed -e '/HELP_STEXT/d'
787 }
788 # }}}
789
790 # Function: DirectoryCheck {{{
791 # Simple function to verify that unsafe characters are not used in directory names.
792 # ARGUMENTS:
793 # ${1} == Name of Variable to be tested
794 DirectoryCheck() {
795 # Variables have a default value of 'UNCONFigured' because this word and combination
796 # of capitalization is unlikely to be used. This allows us to catch improperly
797 # formated calls to DirectoryCheck.
798 #
799 # Uses variable indirection, The '!' introduces indirection which can be read
800 # to say "Get the value of the variable named this".
801 local TEST_STRING=${!1:-"UNCONFigured"}
802 # The second use simply reports the name of the variable to be tested.
803 local TEST_VARIABLE=${1:-"UNCONFigured"}
804 local TEST_FAIL=0
805 local OFFENDING_CHARS=""
806
807 if [[ ${TEST_STRING} == "UNCONFigured" ]]; then
808 echo "Improperly formated call to DirectoryCheck."
809 return 1
810 fi
811
812 # Test if FILENAME_BADCHARS is configured, if it is then check filenames to
813 # prevent the use of disallowed characters.
814 if [[ -n ${FILENAME_BADCHARS+set} ]]; then
815 for (( i=0; i<${#FILENAME_BADCHARS}; i++ )); do
816 local TEST_CHAR=${FILENAME_BADCHARS:$i:1}
817
818 # Grep looks for --fixed-strings so that certain characters are not
819 # interpreted as regular expressions (like ^ $ or /)
820 if grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${TEST_STRING}"; then
821 OFFENDING_CHARS="${OFFENDING_CHARS}${TEST_CHAR}"
822 # This test must come first because it will set TEST_FAIL to 1 regardless
823 # of how many offending characters are found. Given that this test can be
824 # reported multiple times, we do not want it to cause additional suggestions
825 # to be given to the user below.
826 TEST_FAIL=1
827 fi
828 done
829
830 unset -v i
831 fi
832
833 # consult Shellcheck SC2076 for why I choose this construct rather than using regex (=~) checks
834 if [[ ${TEST_STRING} = *"../"* ]]; then
835 TEST_FAIL=$((TEST_FAIL+2))
836 fi
837
838 if [[ ${TEST_STRING} = *"*"* ]]; then
839 TEST_FAIL=$((TEST_FAIL+4))
840 fi
841
842 # This test will create duplicate suggestions as the back-slash character also appears in
843 # the default FILENAME_BADCHARS.
844 if [[ ${TEST_STRING} = *"\\000"* ]]; then
845 TEST_FAIL=$((TEST_FAIL+8))
846 fi
847
848 if (( TEST_FAIL != 0 )); then
849 echo "DIRECTORY CHECK ERROR: ${TEST_VARIABLE} = ${TEST_STRING}"
850
851 echo
852 echo "Suggestion(s):"
853 local COUNT=0
854 while (( TEST_FAIL != 0 )); do
855 if (( (8<=TEST_FAIL) && (TEST_FAIL<=150) )); then
856 COUNT=$((COUNT+1))
857 # Shellcheck does not like the backslash being escaped here as part of an echo statement (SC2028)
858 # There is an open issue on github for it but some people think it is appropriate as "info".
859 # (https://github.com/koalaman/shellcheck/issues/2486)
860 #
861 # Attempting to use printf here as recommended by Shellcheck. Seems unnecessary but that's how
862 # the game is played.
863 printf " %s. '\\000' cannot be used in directory names as mkdir expects\n" "${COUNT}"
864 # echo " ${COUNT}. '\\000' cannot be used in directory names as mkdir expects"
865 printf " to get a null terminated string and '\\000' is considered 'end of string'.\n"
866 # echo " to get a null terminated string and '\\000' is considered 'end of string'."
867
868 if (( TEST_FAIL >= 8 )); then
869 TEST_FAIL=$((TEST_FAIL-8))
870 fi
871 elif (( (4<=TEST_FAIL) && (TEST_FAIL<=7) )); then
872 COUNT=$((COUNT+1))
873 echo " ${COUNT}. The asterisk should not be used in directories as they are commonly used"
874 echo " to designate a wild card for expansion in Bash variables."
875 if (( TEST_FAIL >= 4 )); then
876 TEST_FAIL=$((TEST_FAIL-4))
877 fi
878 elif (( (2<=TEST_FAIL) && (TEST_FAIL<=3) )); then
879 COUNT=$((COUNT+1))
880 echo " ${COUNT}. Directories should not contain two periods and a slash in conjunction."
881 echo " If you need to save certain files outside of the Podcast Library directory,"
882 echo " defined by this podgetrc, the proper solution is to create a second podgetrc"
883 echo " with the new library location defined and to run podget with the --config"
884 echo " command line option to designate the podgetrc file to use."
885 if (( TEST_FAIL >= 2 )); then
886 TEST_FAIL=$((TEST_FAIL-2))
887 fi
888 elif ((1==TEST_FAIL)); then
889 COUNT=$((COUNT+1))
890 echo " ${COUNT}. Attempts to use characters disallowed by FILENAME_BADCHARS."
891 echo " Either remove the offending characters from the configured directory"
892 echo " or FILENAME_BADCHARS."
893 echo " Configured characters not allowed: ${FILENAME_BADCHARS}"
894 echo " Offending character(s): ${OFFENDING_CHARS}"
895 if (( TEST_FAIL >= 1 )); then
896 TEST_FAIL=$((TEST_FAIL-1))
897 fi
898 fi
899 done
900 if [[ ${TEST_VARIABLE} == "FEED_NAME" || ${TEST_VARIABLE} == "FEED_CATEGORY" ]]; then
901 return 1
902 else
903 CleanupAndExit 1
904 fi
905 fi
906
907 }
908 # }}}
909
910 # Function: FilenameCheck {{{
911 # This function tests the filenames used by podget locally for various configuration and log files. While these checks have
912 # some similarity to those applied to downloaded files the major difference is that violations of these rules will interrupt
913 # the execution of podget and podget will attempt to fix the other filenames but many not always succeed.
914 # Arguments:
915 # {1} == Name of Variable to be tested
916 FilenameCheck() {
917 # Variables have a default value of 'UNCONFigured' because this word and combination
918 # of capitalization is unlikely to be used. This allows us to catch improperly
919 # formated calls to FilenameCheck.
920 #
921 # Uses variable indirection, The '!' introduces indirection which can be read
922 # to say "Get the value of the variable named this".
923 local TEST_STRING=${!1:-"UNCONFigured"}
924 # The second use simply reports the name of the variable to be tested.
925 local TEST_VARIABLE=${1:-"UNCONFigured"}
926 local TEST_FAIL=0
927 local OFFENDING_CHARS=""
928
929 if [[ ${TEST_STRING} == "UNCONFigured" ]]; then
930 echo "Improperly formated call to FilenameCheck."
931 return 1
932 fi
933
934 # Test if FILENAME_BADCHARS is configured, if it is then check filenames to
935 # prevent the use of disallowed characters.
936 if [[ -n ${FILENAME_BADCHARS+set} ]]; then
937 for (( i=0; i<${#FILENAME_BADCHARS}; i++ )); do
938 local TEST_CHAR=${FILENAME_BADCHARS:$i:1}
939
940 # Grep looks for --fixed-strings so that certain characters are not
941 # interpreted as regular expressions (like ^ $ or /)
942 if grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${TEST_STRING}"; then
943 OFFENDING_CHARS="${OFFENDING_CHARS}${TEST_CHAR}"
944 # This test must come first because it will set TEST_FAIL to 1 regardless
945 # of how many offending characters are found. Given that this test can be
946 # reported multiple times, we do not want it to cause additional suggestions
947 # to be given to the user below.
948 TEST_FAIL=1
949 fi
950 done
951
952 unset -v i
953 fi
954
955 if [[ -z ${TEST_STRING##*/*} ]]; then
956 # First test remove PATH from TEST_FILENAME variable.
957 local TEST_DIRECTORY="${TEST_STRING%/*}"
958 local TEST_FILENAME="${TEST_STRING##*/}"
959
960 if [[ -n "${TEST_DIRECTORY}" ]]; then
961 TEST_FAIL=$((TEST_FAIL+2))
962 fi
963
964 # Remove directory from string to be tested for following tests.
965 TEST_STRING=${TEST_FILENAME}
966 fi
967
968 # Configuration files should not be hidden by leading periods and trailing periods can cause issues on some file systems or
969 # operating systems. Test if filename begins or ends with a period (.)
970 if [[ ${TEST_STRING:0:1} == "." || ${TEST_STRING:(-1):1} == "." ]]; then
971 TEST_FAIL=$((TEST_FAIL+4))
972 fi
973
974
975 if (( TEST_FAIL != 0 )); then
976 echo
977
978 case "${TEST_VARIABLE}" in
979 "CONFIG_CORE" )
980 echo "Configuration filename specified by -c or --create-config violates the following rules..."
981 ;;
982 "CMDL_SERVERLIST" )
983 echo "Serverlist filename specified by --serverlist violates the following rules..."
984 ;;
985 "CONFIG_SERVERLIST" )
986 echo "Default Serverlist filename violates the following rules..."
987 ;;
988 "LOG_FAIL" )
989 echo "LOG_FAIL defined in ${CONFIG_CORE} violates the following rules..."
990 ;;
991 "LOG_COMPLETE" )
992 echo "LOG_COMPLETE defined in ${CONFIG_CORE} violates the following rules..."
993 ;;
994 * )
995 echo "${TEST_VARIABLE} violates the following rules..."
996 ;;
997 esac
998
999 echo
1000 echo "Suggestion(s):"
1001 COUNT=0
1002 while (( TEST_FAIL != 0 )); do
1003 case ${TEST_FAIL} in
1004 # Included as an example of how other errors could be added with
1005 # a binary progression for the values they add to TEST_FAIL.
1006 [4-7])
1007 COUNT=$((COUNT+1))
1008 echo " ${COUNT}. Remove leading or trailing period from ${TEST_STRING}"
1009 if (( TEST_FAIL > 1 )); then
1010 TEST_FAIL=$((TEST_FAIL-4))
1011 fi
1012 ;;
1013 [2-3])
1014 COUNT=$((COUNT+1))
1015 echo " ${COUNT}. Filenames should not include any directory configuration."
1016 echo " Remove the directory configuration."
1017 case "${TEST_VARIABLE}" in
1018 "CONFIG_CORE" | "CMDL_SERVERLIST" | "CONFIG_SERVERLIST" )
1019 echo " If you need to specify a directory other than the default,"
1020 echo " use the -d or --dir_config command line options."
1021 ;;
1022 "LOG_FAIL" | "LOG_COMPLETE" )
1023 echo " If you wish to specify another location to store the logs,"
1024 echo " then configure the DIR_LOG variable in your ${CONFIG_CORE}"
1025 ;;
1026 esac
1027
1028 if (( TEST_FAIL >= 2 )); then
1029 TEST_FAIL=$((TEST_FAIL-2))
1030 fi
1031 ;;
1032 1)
1033 COUNT=$((COUNT+1))
1034 echo " ${COUNT}. Attempts to use characters disallowed by FILENAME_BADCHARS."
1035 echo " Either remove the offending characters from the configured directory"
1036 echo " or FILENAME_BADCHARS."
1037 echo " Configured characters not allowed: ${FILENAME_BADCHARS}"
1038 echo " Offending character(s): ${OFFENDING_CHARS}"
1039 if (( TEST_FAIL >= 1 )); then
1040 TEST_FAIL=$((TEST_FAIL-1))
1041 fi
1042 ;;
1043 esac
1044 done
1045
1046 CleanupAndExit 1
1047 fi
1048 }
1049 # }}}
1050
1051 # Function: FilenameFixFormat {{{
1052 # Cleans up filenames in several ways. Each method can be enabled or disabled individually in podgetrc file.
1053 # Arguments:
1054 # ${1} == name of variable to hold return string
1055 # ${2} == string to fix the format of
1056 FilenameFixFormat() {
1057 # variable to hold returned value.
1058 local VAR_RETURN=${1}
1059
1060 # Filename to be modified.
1061 # Set original value for filename format fixes and character substitutions.
1062 # Set according to what is passed as the second argument to function.
1063 local MODIFIED_FILENAME=${2}
1064
1065 # ORIGINAL and MODIFIED start out the same.
1066 local ORIGINAL_FILENAME="${MODIFIED_FILENAME}"
1067
1068
1069 if [[ -n ${FILENAME_FORMATFIX+set} || -n ${FILENAME_FORMATFIX2+set} || -n ${FILENAME_FORMATFIX3+set} ||
1070 -n ${FILENAME_FORMATFIX4+set} || -n ${FILENAME_FORMATFIX5+set} || -n ${FILENAME_FORMATFIX6+set} ||
1071 -n ${FILENAME_FORMATFIX7+set} || -n ${FILENAME_FORMATFIX8+set} || -n ${FILENAME_FORMATFIX9+set} ||
1072 -n ${FILENAME_FORMATFIX10+set} ]]; then
1073 __MSG_INFO "ORIGINAL FILENAME" "${ORIGINAL_FILENAME}"
1074 fi
1075
1076 # Note: Filename format fixes that have more specific conditions come first. More generic last. This is
1077 # because a fix with too liberal a condition can prevent a more specific fix from running. Fixes are named in
1078 # the order they were created, so it may appear that they are out of order. By changing the order that they are
1079 # executed in, it is possible to have more enabled by default.
1080 #
1081 # TODO: Create exclusionary conditions for the fixes that are out of order to restore sanity to this list.
1082 #
1083 # FILENAME_FORMATFIX has been moved to the end of the order.
1084 #
1085 # FILENAME_FORMATFIX4 is not part of this function and is called immediately after this function ends.
1086
1087 # Filename format fix for podcasts hosted on http://lbc.audioagain.com.
1088 if [[ -n ${FILENAME_FORMATFIX2+set} ]] && (( FILENAME_FORMATFIX2 > 0 )); then
1089 if [[ "${MODIFIED_FILENAME}" =~ [0-9a-zA-Z]+[\&]amp\;source=podcast.php[\&]amp\;channel_id=[0-9]+$ ]]; then
1090 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/.*stream.mp3[?]guid=\([0-9]\+\)-\([0-9]\+\)\/\([0-9]\+\)\/.*/\1-\2-\3.mp3/')
1091 __MSG_INFO "FILENAME FORMAT(2) FIXED: ${MODIFIED_FILENAME}"
1092 fi
1093 fi
1094
1095
1096 # Filename format fix for podcasts hosted on http://www.catradio.cat
1097 if [[ -n ${FILENAME_FORMATFIX3+set} ]] && (( FILENAME_FORMATFIX3 > 0 )); then
1098 if [[ "${MODIFIED_FILENAME}" =~ [0-9]+\.mp3[?][\&]programa=[0-9a-Z+-=%\&\;]+$ ]]; then
1099 # shellcheck disable=SC2001
1100 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/\(.*\)\.mp3\(.*\)/\1\.mp3/g')
1101 __MSG_INFO "FILENAME FORMAT(3) FIXED: ${MODIFIED_FILENAME}"
1102 fi
1103 fi
1104
1105 # Remove "?referrer=rss" from filename as included with some feeds like Vimcasts.org
1106 if [[ -n ${FILENAME_FORMATFIX5+set} ]] && (( FILENAME_FORMATFIX5 > 0 )); then
1107 if [[ "${MODIFIED_FILENAME}" =~ [0-9a-zA-Z_]+\.[agmopv34]+[?]referrer=rss$ ]]; then
1108 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -r 's/([-A-Za-z0-9_]+.[agmopv34]+)[?]referrer=rss/\1/g')
1109 __MSG_INFO "FILENAME FORMAT(5) FIXED: ${MODIFIED_FILENAME}"
1110 fi
1111 fi
1112
1113 # ZDF podcast filename fix
1114 if [[ -n ${FILENAME_FORMATFIX6+set} ]] && (( FILENAME_FORMATFIX6 > 0 )); then
1115 if [[ "${MODIFIED_FILENAME}" =~ [-_0-9a-zA-Z]+\.[agmopv34]+[?][-_+0-9]+$ ]]; then
1116 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/([-_A-Za-z0-9]+.[agmopv34]+)[?][-+0-9]*/\1/g')
1117 __MSG_INFO "FILENAME FORMAT(6) FIXED: ${MODIFIED_FILENAME}"
1118 fi
1119 fi
1120
1121 # media_url cleanup
1122 # This fix was inspired by the Radio France podcast feed. Each enclosure URL in the feed had the same filename
1123 # specified to be downloaded, and the actual filename of the MP3 file was appended in the media_url variable.
1124 # This fix extracts that filename and uses it for the downloaded file.
1125 #
1126 # Filename consists of: numbers, letters, dashes, underscore, plus, percent, equals, question mark, ampersand, and period
1127 # with extended regex and buffers limited
1128 # wget -O - http://radiofrance-podcast.net/podcast09/rss_12036.xml | grep enclosure | sed -ru 's/.*(media_url=.*[.][gmopv34]+)"\ .*/\1/' | sed -ru 's/.*%2F([-0-9A-Za-z_.]+[.][gmopv34]+)/\1/'
1129 if [[ -n ${FILENAME_FORMATFIX7+set} ]] && (( FILENAME_FORMATFIX7 > 0 )); then
1130 if [[ "${MODIFIED_FILENAME}" =~ [+_%\&=?.0-9a-zA-Z]*media_url=http ]]; then
1131 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/.*(media_url=http.*[.][agmopv34]+)"\ .*/\1/' | sed -ru 's/.*%2F([-0-9A-Za-z_.]+[.][agmopv34]+)/\1/')
1132 __MSG_INFO "FILENAME FORMAT(7) FIXED: ${MODIFIED_FILENAME}"
1133 fi
1134 fi
1135
1136 # SMODCAST cleanup
1137 # Remove "?client_id=<string>" from filename.
1138 #
1139 # Note: This is only the first part of the cleanup needed for the SMODCAST feeds. These removes the trailing portion of the
1140 # enclosure URL but every filename is left as "stream.mp3". The distinguishing part of each URL is held one segment before the
1141 # filename and so FILENAME_FORMATFIX4 must also be enabled. This can potentially affect other feeds and so it may be desirable
1142 # to separate these feeds to their own configuration and serverlist files. They can then be loaded by using the -c and
1143 # --serverlist flags on the command line.
1144 if [[ -n ${FILENAME_FORMATFIX8+set} ]] && (( FILENAME_FORMATFIX8 > 0 )); then
1145 if [[ "${MODIFIED_FILENAME}" =~ stream\.mp3[?]client_id=[0-9a-zA-Z]\\+ ]]; then
1146 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/(stream[.]mp3)[?]client_id=[0-9A-Za-z]+/\1/')
1147 __MSG_INFO "FILENAME FORMAT(8) FIXED: ${MODIFIED_FILENAME}"
1148 fi
1149 fi
1150
1151 # Audioboo Filename Cleanup.
1152 # Enclosure URLs have "?keyed=true&amp;source=rss" appended to them. This fix removes that string.
1153 # It should work for Audioboo podcasts and others with similar formating.
1154 if [[ -n ${FILENAME_FORMATFIX9+set} ]] && (( FILENAME_FORMATFIX9 > 0 )); then
1155 if [[ "${MODIFIED_FILENAME}" =~ [-_0-9a-zA-Z]+[.][agmopv34]+[?][_%\&\;=0-9a-zA-Z]+ ]]; then
1156 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/([-_A-Za-z0-9]+[.][agmopv34]+)[?][-_%&#;=A-Za-z0-9]+/\1/g')
1157 __MSG_INFO "FILENAME FORMAT(9) FIXED: ${MODIFIED_FILENAME}"
1158 fi
1159 fi
1160
1161 # MP3 on Apple ITunes
1162 # Filenames are generally long strings of numbers and letters, with the actual episode name being defined after the '?'
1163 # This extracts the episode name and uses it for the filename.
1164 if [[ -n ${FILENAME_FORMATFIX10+set} ]] && (( FILENAME_FORMATFIX10 > 0 )); then
1165 if [[ "${MODIFIED_FILENAME}" =~ [-0-9A-Za-z_]+[.][MmPp3]+[?][-0-9A-Za-z%=]+%26episodeName%3D[-0-9A-Za-z%.*]+%26episodeKind%3D ]]; then
1166 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/.*%26episodeName%3D([-._%A-Za-z0-9*]+)%26episodeKind[-%&;=A-Za-z0-9]+/\1.mp3/g' | sed -ru 's/%2B/_/g;s/%25[0-9ACF]{2}//g;s/[*]//g')
1167 __MSG_INFO "FILENAME FORMAT(10) FIXED: ${MODIFIED_FILENAME}"
1168 fi
1169 fi
1170
1171 # Fix improperly formated filenames (fixes filename.mp3?123456 to filename123456.mp3)
1172 if [[ -n ${FILENAME_FORMATFIX+set} ]] && (( FILENAME_FORMATFIX > 0 )); then
1173 if [[ "${MODIFIED_FILENAME}" =~ .*\.mp3[?].*$ ]]; then
1174 # shellcheck disable=SC2001
1175 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/\.mp3\(.*\)/\1.mp3/')
1176 __MSG_INFO "FILENAME FORMAT FIXED: ${MODIFIED_FILENAME}"
1177 fi
1178 fi
1179
1180 # Test if BADCHARS set by variable
1181 if [[ -n ${FILENAME_BADCHARS+set} ]] ; then
1182 # Test for BADCHARS in MODIFIED_FILENAME
1183 if [[ ${MODIFIED_FILENAME} =~ ["${FILENAME_BADCHARS}"] ]]; then
1184 # Two step process. First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
1185 # down to a single time.
1186 MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
1187 __MSG_INFO "FILENAME FORMAT FIXED: ${MODIFIED_FILENAME}"
1188 fi
1189 fi
1190
1191 if [[ "${ORIGINAL_FILENAME}" != "${MODIFIED_FILENAME}" ]]; then
1192 __MSG_INFO "MODIFIED FILENAME" "${MODIFIED_FILENAME}"
1193 fi
1194
1195 # Pass the modified filename back to the calling variable.
1196 # eval "${VAR_RETURN}=${MODIFIED_FILENAME@Q}"
1197 printf -v "${VAR_RETURN}" '%s' "${MODIFIED_FILENAME}"
1198
1199 # close without error
1200 return 0
1201 }
1202 # }}}
1203
1204 # Function: FilterOptions {{{
1205 # This takes each feed from a serverlist and selectively enables options specific to it. Used for Feed Categories and Names.
1206 # Arguments:
1207 # ${1} == name of variable to filter on (either FEED_CATEGORY or FEED_NAME)
1208 FilterOptions() {
1209 local FILTER_ITEM="${1}"
1210
1211 # NOTE: The regex expressions in the following checks were updated so that
1212 # they played nice on FreeBSD 12.1 with Bash 5.0.17.
1213 #
1214 # Previously the regexes included: (.*[[:space:]]|)
1215 #
1216 # This would either look for the pattern after other parts or
1217 # immediately at the beginning of the string. It was the second part
1218 # that caused issues, the part after the or but before the closing
1219 # parenthesis. The blank part worked on Linux but not on FreeBSD.
1220 #
1221 # To fix it, we changed to this: (.+[[:space:]]|[[:space:]]?)
1222
1223 # Extract Password from FILTER_ITEM if found.
1224 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(PASS:)([^[:space:]]+).*$ ]]; then
1225 URL_PASSWORD="${BASH_REMATCH[3]}"
1226 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/PASS:+([^[:space:]])}"
1227 fi
1228
1229 # Extract USERNAME from FILTER_ITEM if found.
1230 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(USER:)([^[:space:]]+).*$ ]]; then
1231 URL_USERNAME="${BASH_REMATCH[3]}"
1232 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/USER:+([^[:space:]])}"
1233 fi
1234
1235 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_CONTENT_DISPOSITION.*$ ]]; then
1236 WGET_OPTION_DISPOSITION=1
1237 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_CONTENT_DISPOSITION}"
1238 fi
1239
1240 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_DISPOSITION_FAIL.*$ ]]; then
1241 WGET_OPTION_DISPOSITION_FAIL=1
1242 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_DISPOSITION_FAIL}"
1243 fi
1244
1245 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_NO_CERT_CHECK.*$ ]]; then
1246 WGET_OPTION_NO_CHECK_CERIFICATE=1
1247 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_NO_CERT_CHECK}"
1248 fi
1249
1250 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_PREFER_IP[vV]4.*$ ]]; then
1251 WGET_OPTION_PREFER_IP_TYPE=4
1252 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM//OPT_PREFER_IP[vV]4}"
1253 fi
1254
1255 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_PREFER_IP[vV]6.*$ ]]; then
1256 WGET_OPTION_PREFER_IP_TYPE=6
1257 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM//OPT_PREFER_IP[vV]6}"
1258 fi
1259
1260 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FEED_ORDER_ASCENDING.*$ ]]; then
1261 FEED_SORT_ORDER="ASCENDING"
1262 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FEED_ORDER_ASCENDING}"
1263 fi
1264
1265 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FEED_PLAYLIST_NEWFIRST.*$ ]]; then
1266 FEED_FULL_PLAYLIST=1
1267 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FEED_PLAYLIST_NEWFIRST}"
1268 fi
1269
1270 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FEED_PLAYLIST_OLDFIRST.*$ ]]; then
1271 FEED_FULL_PLAYLIST=2
1272 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FEED_PLAYLIST_OLDFIRST}"
1273 fi
1274
1275 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_WGET_DEFUSERAGENT.*$ ]]; then
1276 WGET_OPTION_DEFAULT_USERAGENT=1
1277 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_WGET_DEFUSERAGENT}"
1278 fi
1279
1280 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_RSS_MEDIACONTENT.*$ ]]; then
1281 WGET_OPTION_RSS_MEDIACONTENT=1
1282 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_RSS_MEDIACONTENT}"
1283 fi
1284
1285 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_LOCATION.*$ ]]; then
1286 WGET_OPTION_FILENAME_LOCATION=1
1287 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_LOCATION}"
1288 fi
1289
1290 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_RENAME_MDATE.*$ ]]; then
1291 POST_WGET_RENAME_MDATE=1
1292 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_RENAME_MDATE}"
1293 fi
1294
1295 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_RENAME_TITLETAG.*$ ]]; then
1296 POST_WGET_RENAME_TITLETAG=1
1297 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_RENAME_TITLETAG}"
1298 fi
1299
1300 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_RENAME_REVTITLETAG.*$ ]]; then
1301 POST_WGET_RENAME_REVTITLETAG=1
1302 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_RENAME_REVTITLETAG}"
1303 fi
1304
1305 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)ATOM_FILTER_SIMPLE.*$ ]]; then
1306 ATOM_FILTER_SIMPLE=1
1307 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/ATOM_FILTER_SIMPLE}"
1308 fi
1309
1310 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(ATOM_FILTER_TYPE=\"?)([^\" ]+).*$ ]]; then
1311 ATOM_FILTER_TYPE="${BASH_REMATCH[3]}"
1312 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/ATOM_FILTER_TYPE=+([^[:space:]])}"
1313 fi
1314
1315 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(ATOM_FILTER_LANG=\"?)([^\" ]+).*$ ]]; then
1316 ATOM_FILTER_LANG="${BASH_REMATCH[3]}"
1317 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/ATOM_FILTER_LANG=+([^[:space:]])}"
1318 fi
1319
1320 # Remove repeated spaces
1321 printf -v "${FILTER_ITEM}" '%s' "$(tr -s ' ' <<< "${!FILTER_ITEM}")"
1322
1323 # Remove any residual leading whitespace from ${!FILTER_ITEM}
1324 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM#"${!FILTER_ITEM%%[![:space:]]*}"}"
1325
1326 # Remove any residual trailing whitespace from ${!FILTER_ITEM}
1327 printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM%"${!FILTER_ITEM##*[![:space:]]}"}"
1328
1329 # No_Category, or blank item handling.
1330 if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)No_Category.*$ || -z "${!FILTER_ITEM-empty}" ]]; then
1331 # Set to single period which is a bashism for current directory.
1332 printf -v "${FILTER_ITEM}" '%s' '.'
1333 fi
1334
1335 if [[ "${!FILTER_ITEM}" =~ ^.*%(YY|MM|DD)%.*$ ]]; then
1336 printf -v "${FILTER_ITEM}" '%s' "$(sed -e "s#%YY%#$(date +%Y)#" -e "s#%MM%#$(date +%m)#" -e "s#%DD%#$(date +%d)#" <<< "${!FILTER_ITEM}")"
1337 fi
1338
1339 }
1340 # }}}
1341
1342 # Function: PlaylistConvertToASX {{{
1343 # This function converts a M3U playlist to ASX format.
1344 # ARGUMENTS:
1345 # ${1} == Directory that libraries are stored in
1346 # ${2} == M3U Playlist name to convert
1347 PlaylistConvertToASX() {
1348 local DIR_LIBRARY=${1}
1349 local M3U_PLAYLISTNAME=${2}
1350 ASX_LOCATION="\\SD Card\\POD\\"
1351 ASX_PLAYLISTNAME=$(basename "${DIR_LIBRARY}"/"${M3U_PLAYLISTNAME}" .m3u).asx
1352 sed --silent -e '/TEXT_ASX_BEGINNING$/,/^TEXT_ASX_BEGINNING/p' "$0" |
1353 sed -e '/TEXT_ASX_BEGINNING/d' > "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"
1354
1355 while read -r line ; do
1356 local FIXED_ENTRY="${line//\//\\}"
1357 {
1358 echo ' <ENTRY>'
1359 echo " <ref href = \"${ASX_LOCATION}${FIXED_ENTRY}\" />"
1360 echo " <ref href = \".\\${FIXED_ENTRY}\" />"
1361 echo ' </ENTRY>'
1362 } >> "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"
1363 done < "${DIR_LIBRARY}"/"${M3U_PLAYLISTNAME}"
1364
1365 sed --silent -e '/TEXT_ASX_END$/,/^TEXT_ASX_END/p' "$0" |
1366 sed -e '/TEXT_ASX_END/d' >> "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"
1367
1368 # Removing unix2dos dependency. Converting to sed statement with in-place editing of the file in question.
1369 # ctrl-v ctrl-m for windows line end.
1370 sed -i 's/$/ /' "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"
1371 }
1372 # }}}
1373
1374 # Function: PlaylistSort {{{
1375 # ARGUMENTS:
1376 # ${1} == Library directory that files are stored in.
1377 # ${2} == M3U Playlist to sort.
1378 PlaylistSort() {
1379 local -r DIR_LIBRARY=${1}
1380 local -r M3U_PLAYLISTNAME=${2}
1381 local REALPLAYLISTNAME="${DIR_LIBRARY}/$M3U_PLAYLISTNAME"
1382
1383 # Sort Playlist
1384 unset -v TEMPPLAYLISTNAME
1385 local TEMPPLAYLISTNAME
1386 if hash mktemp >&2; then
1387 TEMPPLAYLISTNAME=$(mktemp 2>/dev/null)
1388 elif hash tempfile >&2; then
1389 # NOTE: The shellcheck warning for tempfile being depreciated is
1390 # disabled here because we are only using it for systems that do not
1391 # already have mktemp. So realistically, it should almost never be called.
1392 # shellcheck disable=SC2186
1393 TEMPPLAYLISTNAME=$(tempfile 2>/dev/null)
1394 else
1395 echo "Error: Neither mktemp or tempfile found. Unable to sort playlist."
1396 unset -v REALPLAYLISTNAME TEMPPLAYLISTNAME
1397 return
1398 fi
1399
1400 # Convert Sort --output= option to -o for compatibility with NetBSD
1401 cp -p "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && sort -o "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && rm "$TEMPPLAYLISTNAME"
1402 # cp -p "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && sort --output="$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && rm "$TEMPPLAYLISTNAME"
1403
1404 unset -v REALPLAYLISTNAME TEMPPLAYLISTNAME
1405 }
1406 # }}}
1407
1408 # Function: PodgetBuildFeedPlaylist {{{
1409 # Build M3U playlist for a single feed if it is configured to get them in the serverlist file.
1410 # ARGUMENTS: <none>
1411 PodgetBuildFeedPlaylist() {
1412 # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
1413 local -r DIR_CONFIG="${DIR_CONFIG}"
1414 local -r CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"
1415 local -r VERBOSITY="${VERBOSITY}"
1416
1417 # Test if any feeds are configured to require individual playlists. If none are configured to require them, skip this
1418 # section.
1419 # NOTE: filename globbing for the grep command is somewhat clunky because expansion does not happen within quotes. Might be
1420 # nice to find a more elegant way to state this.
1421 if grep --files-with-match --quiet --no-messages "OPT_FEED_PLAYLIST_\\(NEW\\|OLD\\)FIRST" "${DIR_CONFIG}/${CONFIG_SERVERLIST}"{.utf16,}; then
1422 __MSG_DEBUG "============================================================"
1423 __MSG_INFO "Build OPT_FEED_PLAYLISTs"
1424 # Set header to not be displayed unless active feed configured to require one.
1425 local FEED_PLAYLIST_HEADER=0
1426
1427 local FILETYPE
1428 for FILETYPE in utf8 utf16 ; do
1429 if (( DEBUG >= 1 )) ; then echo; fi
1430 case ${FILETYPE} in
1431 'utf8')
1432 __MSG_DEBUG "UTF-8 Loop running." ;;
1433 'utf16')
1434 __MSG_DEBUG "UTF-16 Loop running." ;;
1435 esac
1436 local CURRENT_SERVERLIST
1437 case ${FILETYPE} in
1438 'utf8')
1439 CURRENT_SERVERLIST="${DIR_CONFIG}"/"${CONFIG_SERVERLIST}" ;;
1440 'utf16')
1441 CURRENT_SERVERLIST="${DIR_CONFIG}/${CONFIG_SERVERLIST}.utf16" ;;
1442 *)
1443 echo "Unknown Filetype: ${FILETYPE}"
1444 esac
1445
1446 if [[ ! -f ${CURRENT_SERVERLIST} ]]; then
1447 __MSG_DEBUG "No config file found, exiting loop."
1448 continue
1449 fi
1450
1451 ### TODO: Need to find a way to shrink this.
1452 local FEED_URL
1453 local FEED_CATEGORY
1454 local FEED_NAME
1455 while read -r FEED_URL FEED_CATEGORY FEED_NAME ; do
1456 local FEED_FULL_PLAYLIST=0
1457
1458 if [[ "${FEED_URL:0:1}" == "#" || -z "${FEED_URL-empty}" ]] ; then
1459 __MSG_DEBUG "Discarding (comment or blank line)."
1460 __MSG_DEBUG "Clear Loop vars"
1461 unset -v FEED_URL
1462 unset -v FEED_CATEGORY
1463 unset -v FEED_NAME
1464 unset -v FEED_FULL_PLAYLIST
1465 continue
1466 fi
1467
1468 # ---------------------
1469 # Read Podcast configuration - loop to run same filters on FEED_CATEGORY and FEED_NAME
1470
1471 unset -v FILTER_TARGET
1472 local FILTER_TARGET
1473 for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
1474 FilterOptions "${FILTER_TARGET}"
1475 done
1476
1477 # Unset options that are not required in this while loop
1478 unset -v URL_PASSWORD
1479 unset -v URL_USERNAME
1480 unset -v WGET_OPTION_DEFAULT_USERAGENT
1481 unset -v WGET_OPTION_DISPOSITION
1482 unset -v WGET_OPTION_DISPOSITION_FAIL
1483 unset -v WGET_OPTION_NO_CHECK_CERIFICATE
1484 unset -v WGET_OPTION_PREFER_IP_TYPE
1485 unset -v WGET_OPTION_FILENAME_LOCATION
1486 unset -v WGET_OPTION_RSS_MEDIACONTENT
1487 unset -v FEED_SORT_ORDER
1488 unset -v POST_WGET_RENAME_MDATE
1489 unset -v ATOM_FILTER_SIMPLE
1490 unset -v ATOM_FILTER_TYPE
1491 unset -v ATOM_FILTER_LANG
1492
1493 if (( FEED_FULL_PLAYLIST >= 1 )) ; then
1494 if (( FEED_PLAYLIST_HEADER == 0 )); then
1495 if (( VERBOSITY == 1 )) ; then
1496 printf '\n%s\n' "Build OPT_FEED_PLAYLISTs"
1497 fi
1498 if (( VERBOSITY >= 2 )) ; then
1499 printf '\n%s\n%s\n' "-------------------------------------------------" "Build OPT_FEED_PLAYLISTs"
1500 fi
1501 # Increment header variable so it only displays once.
1502 # NOTE: If we attempt to post-increment our variable, it will cause an error because of the way that '(('
1503 # evaluates the expression. When the result is zero, it exits with '1' triggering errexit, however if
1504 # we pre-increment then the error does not happen.
1505 # More examples: https://en.wikipedia.org/wiki/Increment_and_decrement_operators
1506 (( ++FEED_PLAYLIST_HEADER ))
1507 fi
1508 if [ "${FEED_NAME}" == "." ]; then
1509 if (( VERBOSITY >= 1 )); then
1510 printf '%-30s %-50s\n' "" "No FEED_NAME, unable to create playlist for:"
1511 printf '%-30s %-50s\n' "" " ${FEED_URL}"
1512 else
1513 echo "No FEED_NAME, unable to create playlist for:"
1514 echo " ${FEED_URL}"
1515 fi
1516 continue
1517 fi
1518
1519 # Date Substitutions
1520 FEED_CATEGORY=$(echo "${FEED_CATEGORY}" | sed -e "s#%YY%#$(date +%Y)#" -e "s#%MM%#$(date +%m)#" -e "s#%DD%#$(date +%d)#" )
1521
1522 if (( VERBOSITY >= 2 )) ; then
1523 printf '\n%s\n' "-------------------------------------------------"
1524 fi
1525 if (( VERBOSITY >= 1 )) ; then
1526 if [ "${FEED_CATEGORY}" == "." ]; then
1527 printf '%-30s %-50s\n' "Category: NONE" "Name: ${FEED_NAME}"
1528 else
1529 printf '%-30s %-50s\n' "Category: ${FEED_CATEGORY}" "Name: ${FEED_NAME}"
1530 fi
1531 fi
1532
1533 # Replace spaces with underscores and then pipe through tr to limit repetitions.
1534 local FULL_PLAYLIST_NAME
1535 FULL_PLAYLIST_NAME=$(echo "PLAYLIST_${FEED_NAME//[[:space:]]/_}.m3u" | tr -s _)
1536 # Remove old full playlist.
1537 if [ -f "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}" ]; then
1538 if (( VERBOSITY >= 2 )) ; then
1539 echo "Remove old playlist: ${FULL_PLAYLIST_NAME}"
1540 rm "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
1541 else
1542 __MSG_INFO "Remove old playlist" "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
1543 rm -f "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
1544 fi
1545 fi
1546 if [[ -d "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}" ]]; then
1547 # Build new full playlist.
1548 if (( VERBOSITY >= 2 )); then
1549 echo "Build new ${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
1550 else
1551 __MSG_INFO "Build new playlist" "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
1552 fi
1553 local FEED_ITEMS
1554 if (( FEED_FULL_PLAYLIST == 1 )); then
1555 # Get list in order of newest to oldest
1556 FEED_ITEMS=$(ls -1t "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/")
1557 else
1558 # Get list in order of oldest to newest
1559 FEED_ITEMS=$(ls -1tr "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/")
1560 fi
1561 if [ -n "${FEED_ITEMS}" ]; then
1562 local ITEM
1563 while read -r ITEM; do
1564 __MSG_DEBUG "FEED Full Playist add ${ITEM}"
1565 # Added Sed statement to remove "./" (current directory) from each item added as necessary
1566 echo "${FEED_CATEGORY}/${FEED_NAME}/${ITEM}" | sed -e 's|[.]/||g' >> "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
1567 done <<< "${FEED_ITEMS}"
1568 unset -v FEED_ITEMS
1569 unset -v ITEM
1570 else
1571 if (( VERBOSITY >= 1 )); then
1572 printf '%-30s %-50s\n' "" "No files, no playlist"
1573 fi
1574 fi
1575 else
1576 if (( VERBOSITY >= 1 )); then
1577 printf '%-30s %-50s\n' "" "No directory, no playlist"
1578 fi
1579 fi
1580
1581 fi
1582
1583 unset -v FEED_URL
1584 unset -v FEED_CATEGORY
1585 unset -v FEED_NAME
1586 unset -v FEED_FULL_PLAYLIST
1587 done < "${CURRENT_SERVERLIST}"
1588 done
1589 fi
1590 }
1591 # }}}
1592
1593 # Function: PodgetCleanup {{{
1594 # Cleanup loop for PodgetCore function. This loop removes any downloaded files older than CLEANUP_DAYS
1595 # ARGUMENTS: <none>
1596 PodgetCleanup() {
1597 # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
1598 local -r VERBOSITY="${VERBOSITY}"
1599 local -r CLEANUP_SIMULATE="${CLEANUP_SIMULATE}"
1600 local -r DIR_LIBRARY="${DIR_LIBRARY}"
1601 local -r PLAYLIST_NAMEBASE="${PLAYLIST_NAMEBASE}"
1602 if (( VERBOSITY >= 2 )) ; then
1603 if (( CLEANUP_SIMULATE > 0 )); then
1604 echo "Simulating cleanup, the following files will be removed when you run cleanup."
1605 else
1606 printf '\n%s\n%s\n' "-------------------------------------------------" "Cleanup old tracks."
1607 fi
1608 else
1609 __MSG_DEBUG "============================================================"
1610 __MSG_INFO "Cleanup Old Tracks"
1611 fi
1612 FILELIST=$(find "${DIR_LIBRARY}"/ -maxdepth 1 -type f -name "*.m3u")
1613 # Convert CLEANUP_DAYS to CLEANUP_SECONDS (86400 == seconds in a day)
1614 local CLEANUP_SECONDS=$((CLEANUP_DAYS*86400))
1615 # Convert CLEANUP_SECONDS to date in seconds from unix epoch before midnight last night.
1616 # This works with uniform whole days and isn't subject to when the cleanup is run.
1617 local DATE_CLEAN2=$(($(date +%s --date 0:00)-CLEANUP_SECONDS))
1618 local FILE
1619 while IFS= read -r FILE; do
1620 # Catch for when FILELIST is blank
1621 if [[ -z "${FILE}" ]]; then
1622 continue
1623 fi
1624 if [[ "${FILE##/*/}" =~ ^${PLAYLIST_NAMEBASE}* ]]; then
1625 # Compare global playlist file modification date with DATE_CLEAN2. If file modification date is newer than
1626 # DATE_CLEAN2 then we skip it.
1627 if [ "$(stat --format %Y "${FILE}")" -gt "${DATE_CLEAN2}" ]; then
1628 continue
1629 fi
1630 fi
1631 if (( VERBOSITY >= 2 )) ; then
1632 echo "Deleting tracks from ${FILE}:"
1633 else
1634 __MSG_INFO "Deleting Tracks" "From ${FILE}"
1635 fi
1636 local LINE
1637 while read -r LINE ; do
1638 if [[ -f "${DIR_LIBRARY}/${LINE}" ]]; then
1639 # Compare each file from the playlist with file modification date. If file modification date is older than
1640 # DATE_CLEAN2 then we remove that file
1641 if [ "$(stat --format %Y "${DIR_LIBRARY}/${LINE}")" -lt "${DATE_CLEAN2}" ]; then
1642 if (( CLEANUP_SIMULATE > 0 )); then
1643 echo "File to remove: ${DIR_LIBRARY}/${LINE}"
1644 else
1645 __MSG_INFO "Remove File" "${DIR_LIBRARY}/${LINE}"
1646 rm -f "${DIR_LIBRARY}/${LINE}"
1647 fi
1648 fi
1649 else
1650 if (( CLEANUP_SIMULATE > 0 )) ; then
1651 __MSG_INFO "File not found" "${DIR_LIBRARY}/${LINE}"
1652 fi
1653 fi
1654 done < "${FILE}"
1655 if (( CLEANUP_SIMULATE > 0 )); then
1656 echo "Playlist to remove: ${FILE}"
1657 else
1658 __MSG_INFO "Remove Playlist" "${FILE}"
1659 rm -f "${FILE}"
1660 fi
1661 done <<<"${FILELIST}"
1662 }
1663 # }}}
1664
1665 # Function: PodgetExportOPML {{{
1666 # Displays general message with command line options.
1667 # ARGUMENTS: <none>
1668 PodgetExportOPML() {
1669 # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
1670 local -r EXPORT_OPML="${1}"
1671 local -r VERBOSITY="${VERBOSITY}"
1672 local -r DIR_CONFIG="${DIR_CONFIG}"
1673 local -r CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"
1674 local -r ERR_EXPORTOPML="${ERR_EXPORTOPML}"
1675
1676 if [[ ${EXPORT_OPML} == "NONE" ]]; then
1677 echo
1678 echo "No file configured to export to."
1679 CleanupAndExit 1
1680 fi
1681
1682 if (( VERBOSITY >= 2 )) ; then
1683 printf '\n%s\n' "Export serverlist to OPML file: ${EXPORT_OPML}"
1684 fi
1685
1686 if [[ ! -e ${EXPORT_OPML} ]]; then
1687 printf '%s\n\t%s\n\t%s\n\t%s\n' '<?xml version="1.0" encoding="utf-8" ?>' '<opml version="1.0">' '<head/>' '<body>' > "${EXPORT_OPML}"
1688
1689 local FEED_URL
1690 local FEED_CATEGORY
1691 local FEED_NAME
1692 local FEED_FULL_PLAYLIST
1693 while read -r FEED_URL FEED_CATEGORY FEED_NAME ; do
1694 if [[ "${FEED_URL:0:1}" == "#" || -z "${FEED_URL-empty}" ]] ; then
1695 __MSG_DEBUG "Discarding (comment or blank line)."
1696 __MSG_DEBUG "Clear Loop vars"
1697 unset -v FEED_URL
1698 unset -v FEED_CATEGORY
1699 unset -v FEED_NAME
1700 unset -v FEED_FULL_PLAYLIST
1701 continue
1702 fi
1703
1704 # ---------------------
1705 # Read Podcast configuration - loop to run same filters on FEED_CATEGORY and FEED_NAME
1706
1707 unset -v FILTER_TARGET
1708 local FILTER_TARGET
1709 for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
1710 FilterOptions "${FILTER_TARGET}"
1711 done
1712
1713 # Unset options that are not required in this while loop
1714 unset -v URL_PASSWORD
1715 unset -v URL_USERNAME
1716 unset -v WGET_OPTION_DEFAULT_USERAGENT
1717 unset -v WGET_OPTION_DISPOSITION
1718 unset -v WGET_OPTION_DISPOSITION_FAIL
1719 unset -v WGET_OPTION_NO_CHECK_CERIFICATE
1720 unset -v WGET_OPTION_PREFER_IP_TYPE
1721 unset -v WGET_OPTION_FILENAME_LOCATION
1722 unset -v WGET_OPTION_RSS_MEDIACONTENT
1723 unset -v FEED_SORT_ORDER
1724 unset -v POST_WGET_RENAME_MDATE
1725 unset -v ATOM_FILTER_SIMPLE
1726 unset -v ATOM_FILTER_TYPE
1727 unset -v ATOM_FILTER_LANG
1728
1729 if (( VERBOSITY >= 3 )) ; then
1730 echo " Writing out feed ${FEED_NAME} in category ${FEED_CATEGORY} with url ${FEED_URL}"
1731 fi
1732 printf '\t<outline text="%s"><outline text="%s" type="rss" xmlUrl="%s" /></outline>' \
1733 "${FEED_CATEGORY}" "${FEED_NAME}" "${FEED_URL}" >> "${EXPORT_OPML}"
1734 done < "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"
1735
1736 printf '\t%s\n\t%s\n' '</body>' '</opml>' >> "${EXPORT_OPML}"
1737 else
1738 echo "OPML Export Error: ${EXPORT_OPML}" >> "${DIR_LOG}"/"${LOG_FAIL}"
1739 CleanupAndExit ${ERR_EXPORTOPML}
1740 fi
1741 }
1742 # }}}
1743
1744 # Function: PodgetImportOPML {{{
1745 #
1746 # ARGUMENTS:
1747 # ${1} == OPML to import
1748 PodgetImportOPML() {
1749 # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
1750 local -r IMPORT_OPML="${1}"
1751
1752 if [[ ${IMPORT_OPML} == "NONE" ]]; then
1753 echo
1754 echo "unset FILE or URL to import from."
1755 CleanupAndExit 1
1756 fi
1757
1758 if (( VERBOSITY >= 2 )) ; then
1759 printf '\n%s\n' "Import servers from OPML file: ${IMPORT_OPML}"
1760 fi
1761
1762 local new_category
1763 new_category="OPML_Import_$(date ${DATE_FORMAT})"
1764
1765 local opml_list
1766
1767 if [[ ${IMPORT_OPML} == http:* ]] || [[ ${IMPORT_OPML} == ftp:* ]] ; then
1768 if (( VERBOSITY >= 2 )) ; then
1769 echo "Getting opml list."
1770 fi
1771 opml_list=$(wget "${WGET_OPTIONS[@]}" -O - "${IMPORT_OPML}")
1772 else
1773 opml_list=$(cat "${IMPORT_OPML}")
1774 fi
1775
1776 local new_list
1777 new_list=$(echo "${opml_list}" | sed -e 's/\(\/>\)/\1\n/g' | sed -e :a -n -e 's/<outline\([^>]\+\)\/>/\1/Ip;/<outline/{N;s/\n\s*/ /;ba;}')
1778
1779 if [[ -n "$new_list" ]]; then
1780
1781 local OLD_IFS=$IFS
1782 IFS=$'\n'
1783
1784 local data
1785 for data in ${new_list} ; do
1786 if (( VERBOSITY >= 1 )) ; then
1787 printf '\n%s\n' "---------------"
1788 fi
1789
1790 local new_label
1791 new_label=$(echo "${data}" | sed -n -e 's/.*text="\([^"]\+\)".*/\1/Ip' | sed -e 's/^\s*[0-9]\+\.\s\+//' -e "s/[:;'\".,!/?<>\\|]//g")
1792 local new_url
1793 new_url=$(echo "${data}" | sed -n -e 's/.*[xml]*url="\([^"]\+\)".*/\1/Ip' | sed -e 's/ /%20/g')
1794
1795 if (( VERBOSITY >= 3 )) ; then
1796 echo "LABEL: ${new_label}"
1797 echo "URL: ${new_url}"
1798 fi
1799
1800 # Add '|| true' to catch when grep returns a non-zero status for URLs it does not find. This replaces the need to
1801 # disable errexit and the ERR trap.
1802 local test
1803 test=$(grep "${new_url}" "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}") || true
1804
1805 if [[ -z "$test" ]]; then
1806 echo "${new_url} ${new_category} ${new_label}" >> "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"
1807 elif (( VERBOSITY >= 2 )) ; then
1808 echo "Feed ${new_label} is already in the serverlist"
1809 fi
1810 done
1811
1812 IFS=$OLD_IFS
1813 else
1814 if (( VERBOSITY >= 2 )) ; then
1815 echo " OPML Import Error ${IMPORT_OPML}" 1>&2
1816 fi
1817 echo "OPML Import Error: ${IMPORT_OPML}" >> "${DIR_LOG}"/"${LOG_FAIL}"
1818 CleanupAndExit ${ERR_IMPORTOPML}
1819 fi
1820 }
1821 # }}}
1822
1823 # Function: PodgetImportPCAST {{{
1824 #
1825 # ARGUMENTS:
1826 # ${1} == PCAST to import (file or URL)
1827 PodgetImportPCAST() {
1828 # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
1829 local IMPORT_PCAST="${IMPORT_PCAST}"
1830 local VERBOSITY="${VERBOSITY}"
1831 local DIR_CONFIG="${DIR_CONFIG}"
1832 local CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"
1833
1834 if [[ ${IMPORT_PCAST} == "NONE" ]]; then
1835 echo
1836 echo "unset FILE or URL to import from."
1837 CleanupAndExit 1
1838 fi
1839
1840 if (( VERBOSITY >= 2 )) ; then
1841 printf '\n%s\n' "Import server from PCAST file: ${IMPORT_PCAST}"
1842 fi
1843
1844 local pcast_data
1845 if [[ ${IMPORT_PCAST} == http:* ]] || [[ ${IMPORT_PCAST} == ftp:* ]] ; then
1846 if (( VERBOSITY >= 2 )) ; then
1847 echo "Getting pcast file."
1848 fi
1849 pcast_data=$(wget "${WGET_OPTIONS[@]}" -O - "${IMPORT_PCAST}")
1850 else
1851 pcast_data=$(cat "${IMPORT_PCAST}")
1852 fi
1853
1854 local new_link new_category new_title
1855 new_link=$(echo "${pcast_data}" | sed -n -e 's/.*\(href\|url\)="\([^"]\+\)".*/\2/Ip' | sed -e 's/ /%20/g')
1856 new_category=$(echo "${pcast_data}" | sed -n -e 's/.*<category>\([^<]\+\)<.*/\1/Ip' | sed -e 's/ /_/g;s/\&quot;/\&/g;s/\&amp;/\&/g')
1857 new_title=$(echo "${pcast_data}" | sed -n -e 's/.*<title>\([^<]\+\)<.*/\1/Ip')
1858
1859 if (( VERBOSITY >= 2 )) ; then
1860 echo "LINK: ${new_link}"
1861 echo "CATEGORY: ${new_category}"
1862 echo "TITLE: ${new_title}"
1863 fi
1864
1865 # Added '|| true' to catch when grep exits with a non-zero status because the link was not found. This eliminates the need to
1866 # disable errexit and the ERR trap.
1867 local test
1868 test=$(grep "${new_link}" "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}") || true
1869
1870 if [[ -z "$test" ]]; then
1871 echo "${new_link} ${new_category} ${new_title}" >> "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"
1872 elif (( VERBOSITY >= 2 )) ; then
1873 echo "Feed ${new_title} is already in the serverlist"
1874 fi
1875 }
1876 # }}}
1877
1878 # Function: PodgetServerLoop {{{
1879 # Displays general message with command line options.
1880 # ARGUMENTS: <none>
1881 PodgetServerLoop() {
1882 # Set local variables (and get values from global variables as necessary).
1883 # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
1884 local -r VERBOSITY="${VERBOSITY}"
1885 local -r LOG_FAIL="${LOG_FAIL}"
1886 local -r LOG_COMPLETE="${LOG_COMPLETE}"
1887 local -r CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"
1888 local -r NO_PLAYLIST="${NO_PLAYLIST}"
1889 if [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
1890 local -r PLAYLIST_PERPODCAST="${PLAYLIST_PERPODCAST}"
1891 fi
1892 local -r DIR_LOG="${DIR_LOG}"
1893 local SESSION_PLAYLIST_NAME
1894 local -r DIR_CONFIG="${DIR_CONFIG}"
1895 local CURRENT_SERVERLIST
1896 local COUNTER
1897 local FEED_CATEGORY
1898 local FEED_NAME
1899 local FEED_URL
1900
1901 __MSG_DEBUG "Main loop"
1902 __MSG_DEBUG "SERVER LIST FILE" "$CONFIG_SERVERLIST"
1903 __MSG_DEBUG "WGET COMMON OPTIONS" "${WGET_COMMON_OPTIONS}"
1904 if (( NO_PLAYLIST == 0 )); then
1905 __MSG_DEBUG "Playlist Creation Enabled."
1906 else
1907 __MSG_DEBUG "Playlist Creation Disabled."
1908 fi
1909 if [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
1910 __MSG_DEBUG "PLAYLIST_PERPODCAST: ${PLAYLIST_PERPODCAST} (Enabled)"
1911 fi
1912
1913 mkdir -p "${DIR_LOG}"
1914 FilenameCheck LOG_FAIL
1915 FilenameCheck LOG_COMPLETE
1916 touch "${DIR_LOG}"/"${LOG_FAIL}" "${DIR_LOG}"/"${LOG_COMPLETE}"
1917
1918 if (( NO_PLAYLIST == 0 )) && [[ -z ${PLAYLIST_PERPODCAST+set} ]]; then
1919 SESSION_PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT).m3u"
1920
1921 COUNTER=2
1922 while [[ -e ${DIR_LIBRARY}/${SESSION_PLAYLIST_NAME} ]] ; do
1923 SESSION_PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT).r$COUNTER.m3u"
1924 COUNTER=$((COUNTER+1))
1925 done
1926
1927 __MSG_INFO "Session Playlist Name" "${SESSION_PLAYLIST_NAME}"
1928 fi
1929
1930 # UTF-8/16 handling
1931 local FILETYPE
1932 for FILETYPE in utf8 utf16 ; do
1933 case ${FILETYPE} in
1934 'utf8')
1935 __MSG_INFO "UTF-8 Loop running." ;;
1936 'utf16')
1937 __MSG_INFO "UTF-16 Loop running." ;;
1938 esac
1939 case ${FILETYPE} in
1940 'utf8')
1941 CURRENT_SERVERLIST="${DIR_CONFIG}"/"${CONFIG_SERVERLIST}" ;;
1942 'utf16')
1943 # Test if iconv is installed. If it is not, display error.
1944 if ! hash iconv >/dev/null 2>&1; then
1945 echo "Can't find iconv binary, is libc-bin installed?" 1>&2
1946 echo "Exiting UTF16 loop, unable to convert file to UTF8" 1>&2
1947 CleanupAndExit $ERR_LIBC6NOTINSTALLED
1948 fi
1949 CURRENT_SERVERLIST="${DIR_CONFIG}/${CONFIG_SERVERLIST}.utf16" ;;
1950 *)
1951 echo "Unknown Filetype: ${FILETYPE}"
1952 esac
1953 if [[ ! -f ${CURRENT_SERVERLIST} ]]; then
1954 __MSG_INFO "No config file found, exiting loop."
1955 continue
1956 fi
1957
1958 while read -r FEED_URL FEED_CATEGORY FEED_NAME ; do
1959 local URL_USERNAME
1960 local URL_PASSWORD
1961 local FEED_FULL_PLAYLIST
1962 local WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS}"
1963
1964 if (( DEBUG >= 1 )) ; then echo; fi
1965 __MSG_DEBUG "============================================================"
1966 __MSG_DEBUG "Server Loop:"
1967 __MSG_DEBUG "Serverlist Line --> ${FEED_URL:-} ${FEED_CATEGORY:-} ${FEED_NAME:-}"
1968
1969 if [[ "${FEED_URL:0:1}" == "#" || -z "${FEED_URL-empty}" ]] ; then
1970 __MSG_DEBUG "Discarding (comment or blank line)."
1971 __MSG_DEBUG "Clear Server Loop vars"
1972 unset -v FEED_URL
1973 unset -v FEED_CATEGORY
1974 unset -v FEED_NAME
1975 unset -v FEED_FULL_PLAYLIST
1976 unset -v URL_USERNAME
1977 unset -v URL_PASSWORD
1978 continue
1979 fi
1980
1981 if (( DEBUG >= 1 )) ; then echo; fi
1982 __MSG_DEBUG "Reset options to allow loop specific options"
1983 __MSG_DEBUG " WGET_COMMON_OPTIONS: ${WGET_COMMON_OPTIONS}"
1984
1985 unset -v WGET_SUBCHAR
1986 local WGET_SUBCHAR
1987 WGET_NOTCOUNT=0
1988
1989 # In Vim to enter digraphs that are not commonly on the US keyboards,
1990 # we use ctrl-K followed by a two character lookup code.
1991 # Examples:
1992 # !2 - double vertical line ‖
1993 # =2 - double low line ‗
1994 # oo - bullet •
1995 # Db - diamond bullet â—†
1996 # '% - Greek Theta Ï´
1997 # Pd - British Pound symbol £
1998 # Eu - Euro Symbol €
1999 # Ye - Yen symbol ¥
2000 # Pt - Peseta symbol â‚§
2001 # W= - Won symbol â‚©
2002 # Ct - Cent symbol ¢
2003 # Co - Copyright symbol ©
2004 # Rg - Registered Trademark ®
2005 # +- - Plus Minus ±
2006 # Om - Ohm symbol Ω
2007 # AO - Angstrom symbol â„«
2008 # DG - Degree Sign °
2009 # AE - Latin Capital AE Æ
2010 # ae - Latin Small ae æ
2011 # Ca - Caret ‸
2012 # 1R - Roman Numeral One â… 
2013 # 2R - Roman Numeral Two â…¡
2014 # 3R - Roman Numeral Three â…¢
2015 # 4R - Roman Numeral Four â…£
2016 # 5R - Roman Numeral Five â…¤
2017 #
2018 # These are not good to use because they frequently overlap with following
2019 # characters if not followed by a space.
2020 # oC - Degree Celsius ℃
2021 # oF - Degree Fahrenheit ℉
2022 #
2023 # Digraphs may not be included in the locale that you have configured. On my test systems,
2024 # I found that I had one that did not display the correct characters for the digraphs
2025 # but rather replaced them all with an underscore character. The function worked but
2026 # it did not display the characters correctly.
2027 #
2028 # On the systems where it did display correctly, I found that I had the following
2029 # configuration in my /etc/default/locale:
2030 # # File generated by update-locale
2031 # LANG="en_US.UTF-8"
2032 #
2033 # On the one system that did not display correctly, the configuration I had
2034 # in /etc/default/locale was:
2035 # # File generated by update-locale
2036 # LANG="en_US"
2037 #
2038 # This can be updated by modifying the file or by running:
2039 # update-locale LANG="en_US.UTF-8"
2040 #
2041 # This may or may not require a reboot to take effect but I took the easy way out and
2042 # rebooted so I would be sure it displayed as I hoped in the future.
2043 #
2044 # NOTE ON CHARACTERS TO CONSIDER NOT INCLUDING:
2045 # It is probably a good idea to not include any character that has special meaning
2046 # in Bash and needs to be escaped. That is why this string primarily starts with
2047 # digraphs and then includes a few characters that are commonly found on most
2048 # keyboards. I initially wanted to include the $ symbol with the other monetary
2049 # symbols. However I had to escape it or it could cause an "unbound variable"
2050 # error on some systems.
2051 #
2052 # NOTE ON CHARACTERS TO CONSIDER INCLUDING:
2053 # We are using this character to parse the WGET_BASEOPTS string and put it's parts
2054 # into the WGET_OPTIONS array. To make things as easy as possible, we want to use
2055 # characters that are unlikely to be used in any of the WGET options. This can be a
2056 # bit tricky for some options like passwords or user-agent that can take almost
2057 # anything. For that reason, I have included a large selection of digraphs and a
2058 # few characters that do not require escaping because it is very unlikely that
2059 # someone used them all for one of those options and we will be able to safely
2060 # find one to use.
2061 WGET_TEST_STRING="_;‖‗•◆ϴ£€¥₧₩¢ⅠⅡⅢⅣⅤΩÅ©®±°Ææ‸:|<>?~!@#%^"
2062 local INTERVAL
2063 for (( INTERVAL=0; INTERVAL<${#WGET_TEST_STRING}; INTERVAL++ )); do
2064 WGET_TEST_CHAR=${WGET_TEST_STRING:$INTERVAL:1}
2065
2066 # grep looks for --fixed-strings so that certain characters are not
2067 # interpreted as regular expressions.
2068 #
2069 # we're looking for a character that is not found in the string so it is
2070 # ! grep
2071 if ! grep --quiet --fixed-strings "${WGET_TEST_CHAR}" <<<"${WGET_COMMON_OPTIONS}"; then
2072 WGET_SUBCHAR="${WGET_TEST_CHAR}"
2073 break
2074 else
2075 WGET_NOTCOUNT=$((WGET_NOTCOUNT+1))
2076 fi
2077 done
2078
2079 # Done with loop variable, remove it.
2080 unset -v INTERVAL
2081
2082 if [[ -n "${WGET_SUBCHAR+defined}" ]] && [[ "${#WGET_SUBCHAR}" -gt 0 ]]; then
2083 __MSG_DEBUG "WGET Success finding parsing character (${WGET_SUBCHAR})"
2084 __MSG_DEBUG " Test string length: ${#WGET_TEST_STRING}"
2085 __MSG_DEBUG " Characters tested before usable found: ${WGET_NOTCOUNT}"
2086 else
2087 echo
2088 echo "Unable to find character to use as delimiter for WGET_BASEOPTS string."
2089 echo "Every character in our test set was also used somewhere in WGET_BASEOPTS."
2090 echo "Test Set: ${WGET_TEST_STRING}"
2091 echo "WGET_BASEOPTS: ${WGET_BASEOPTS}"
2092 CleanupAndExit 1
2093 fi
2094
2095 WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS// -/${WGET_SUBCHAR}-}"
2096
2097 # clear array and reimport
2098 unset -v WGET_OPTIONS
2099
2100 # Import options from WGET_COMMON_OPTIONS string into WGET_OPTIONS array
2101 IFS="${WGET_SUBCHAR}" read -r -a WGET_OPTIONS <<<"${WGET_COMMON_OPTIONS}"
2102
2103 WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS//${WGET_SUBCHAR}-/ -}"
2104 unset -v WGET_NOTCOUNT
2105 unset -v WGET_SUBCHAR
2106 unset -v WGET_TEST_CHAR
2107 unset -v WGET_TEST_STRING
2108
2109 __MSG_DEBUG "Reset FEED_FULL_PLAYLIST=0"
2110 local FEED_FULL_PLAYLIST=0
2111
2112 __MSG_DEBUG "Reset FEED_SORT_ORDER=DESCENDING"
2113 local FEED_SORT_ORDER="DESCENDING"
2114
2115 __MSG_DEBUG "Reset WGET_OPTION_DEFAULT_USERAGENT"
2116 local WGET_OPTION_DEFAULT_USERAGENT=0
2117
2118 __MSG_DEBUG "Reset WGET_OPTION_FILENAME_LOCATION"
2119 local WGET_OPTION_FILENAME_LOCATION=0
2120
2121 local WGET_OPTION_DISPOSITION
2122 if ArrayContains "--content-disposition" "${WGET_OPTIONS[@]}" ; then
2123 # removing actual --content-disposition option from WGET because it is not used directly
2124 # but rather to set mode. Used for COMMON_OPTIONS to allow ease of use.
2125 for index in "${!WGET_OPTIONS[@]}"; do
2126 if [[ ${WGET_OPTIONS[${index}]} == "--content-disposition" ]]; then
2127 unset -v 'WGET_OPTIONS['"${index}"']'
2128 WGET_OPTION_DISPOSITION=1
2129 __MSG_DEBUG "Reset WGET_OPTION_DISPOSITION to global setting(${WGET_OPTION_DISPOSITION})"
2130 fi
2131 done
2132 else
2133 WGET_OPTION_DISPOSITION=0
2134 __MSG_DEBUG "Reset WGET_OPTION_DISPOSITION to global setting(${WGET_OPTION_DISPOSITION})"
2135 fi
2136
2137 if ArrayContains "--user-agent=" "${WGET_OPTIONS[@]}" ; then
2138 __MSG_DEBUG "Custom Wget User Agent Enabled."
2139 else
2140 WGET_OPTIONS+=("--user-agent=Podget")
2141 __MSG_DEBUG "Default Wget User Agent for Podget Enabled."
2142 fi
2143
2144 __MSG_DEBUG "Reset WGET_OPTION_DISPOSITION_FAIL"
2145 local WGET_OPTION_DISPOSITION_FAIL=0
2146
2147 __MSG_DEBUG "Reset WGET_OPTION_NO_CHECK_CERIFICATE"
2148 local WGET_OPTION_NO_CHECK_CERIFICATE=0
2149
2150 __MSG_DEBUG "Reset WGET_OPTION_PREFER_IP_TYPE"
2151 local WGET_OPTION_PREFER_IP_TYPE=0
2152
2153 __MSG_DEBUG "Reset WGET_OPTION_RSS_MEDIACONTENT"
2154 local WGET_OPTION_RSS_MEDIACONTENT=0
2155
2156 __MSG_DEBUG "Reset POST_WGET_RENAME_MDATE"
2157 local POST_WGET_RENAME_MDATE=0
2158
2159 __MSG_DEBUG "Reset POST_WGET_RENAME_TITLETAG"
2160 local POST_WGET_RENAME_TITLETAG=0
2161
2162 __MSG_DEBUG "Reset POST_WGET_RENAME_REVTITLETAG"
2163 local POST_WGET_RENAME_REVTITLETAG=0
2164
2165 __MSG_DEBUG "Reset ATOM_FILTER_SIMPLE"
2166 local ATOM_FILTER_SIMPLE=0
2167
2168 __MSG_DEBUG "Reset ATOM_FILTER_TYPE"
2169 unset -v ATOM_FILTER_TYPE
2170 local ATOM_FILTER_TYPE
2171
2172 __MSG_DEBUG "Reset ATOM_FILTER_LANG"
2173 unset -v ATOM_FILTER_LANG
2174 local ATOM_FILTER_LANG
2175
2176 # End resets
2177 # -----------------------------------------------------------------
2178 # Read new configuration
2179
2180 # Pass FEED_CATEGORY and FEED_NAME through the option filters. This allows handling of options with blank feed
2181 # categories and names.
2182 unset -v FILTER_TARGET
2183 local FILTER_TARGET
2184 for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
2185 FilterOptions "${FILTER_TARGET}"
2186 done
2187
2188 # Remove variable since it is no longer used.
2189 unset -v FILTER_TARGET
2190
2191 # Unset options that are not required in this while loop
2192
2193 # End setting of FEED_CATEGORY, FEED_NAME, and OPT_items
2194 # -----------------------------------------------------------------
2195
2196 # Add Username and Password to wget options if found.
2197 # Options --user and --password are used for both FTP and HTTP sessions. Using --ftp-user and --http-user would require
2198 # being able to selectively use the correct one based on the URL. Same for --ftp-password and --http-password.
2199 if [[ -n ${URL_USERNAME+set} ]]; then
2200 WGET_OPTIONS+=("--user=${URL_USERNAME}")
2201 fi
2202
2203 if [[ -n ${URL_PASSWORD+set} ]]; then
2204 WGET_OPTIONS+=("--password=${URL_PASSWORD}")
2205 fi
2206
2207 # Reset to default WGET user-agent
2208 if (( WGET_OPTION_DEFAULT_USERAGENT==1 )); then
2209 for index in "${!WGET_OPTIONS[@]}"; do
2210 if [[ ${WGET_OPTIONS[${index}]} =~ ^"--user-agent=".* ]]; then
2211 __MSG_DEBUG "Reset to Default Wget User Agent"
2212 unset -v 'WGET_OPTIONS['"${index}"']'
2213 fi
2214 done
2215 fi
2216
2217 # Add --no-check-certificate to WGET_OPTIONS
2218 if (( WGET_OPTION_NO_CHECK_CERIFICATE==1 )); then
2219 for index in "${!WGET_OPTIONS[@]}"; do
2220 # if --no-check-certificate has been set before, remove it.
2221 if [[ ${WGET_OPTIONS[${index}]} == "--no-check-certificate" ]]; then
2222 unset -v 'WGET_OPTIONS['"${index}"']'
2223 fi
2224 done
2225 WGET_OPTIONS+=("--no-check-certificate")
2226 fi
2227
2228 # Set preferred IP type for WGET_OPTIONS
2229 if (( WGET_OPTION_PREFER_IP_TYPE>0 )); then
2230 for index in "${!WGET_OPTIONS[@]}"; do
2231 # if --prefer-family has been set before, remove it.
2232 if [[ ${WGET_OPTIONS[${index}]} =~ --prefer-family=IPv[46] ]]; then
2233 unset -v 'WGET_OPTIONS['"${index}"']'
2234 fi
2235 done
2236 case "${WGET_OPTION_PREFER_IP_TYPE}" in
2237 4 )
2238 WGET_OPTIONS+=("--prefer-family=IPv4")
2239 ;;
2240 6 )
2241 WGET_OPTIONS+=("--prefer-family=IPv6")
2242 ;;
2243 esac
2244 fi
2245
2246 if (( VERBOSITY >= 2 )) ; then
2247 printf '\n%s\n' "-------------------------------------------------"
2248 fi
2249 if (( VERBOSITY >= 1 )) ; then
2250 local DISPLAY_CATEGORY
2251 local DISPLAY_NAME
2252
2253 if [ "${FEED_CATEGORY}" == "." ]; then
2254 DISPLAY_CATEGORY="None"
2255 else
2256 DISPLAY_CATEGORY="${FEED_CATEGORY}"
2257 fi
2258
2259 if [ "${FEED_NAME}" == "." ]; then
2260 DISPLAY_NAME="None"
2261 else
2262 DISPLAY_NAME="${FEED_NAME}"
2263 fi
2264
2265 printf '%-30s %-50s\n' "Category: ${DISPLAY_CATEGORY}" "Name: ${DISPLAY_NAME}"
2266 fi
2267
2268 __MSG_DEBUG "Loop WGET_OPTIONS" "${WGET_OPTIONS[*]}"
2269
2270 # DirectoryCheck for FEED_NAME and FEED_CATEGORY here prior to using them.
2271 local ITEM
2272 for ITEM in FEED_CATEGORY FEED_NAME; do
2273 # FEED_NAME can be blank, if it is then we skip the DirectoryCheck
2274 if [[ ${ITEM} == "FEED_NAME" && -z "${!ITEM}" ]]; then
2275 # we use continue rather than break here in case the variables are in a different order.
2276 continue
2277 fi
2278
2279 # Moved DirectoryCheck inside an IF statement so that a non-zero exit status would not trigger either the errexit
2280 # or the ERR trap conditions.
2281 if ! DirectoryCheck "${ITEM}"; then
2282 echo
2283 echo "Skipping this feed until corrected, proceeding to next feed listed in ${CURRENT_SERVERLIST}"
2284 echo
2285 # This needs to be 'continue 2' because we are not continuing the immediate for loop but rather the
2286 # loop wrapping it.
2287 continue 2
2288 fi
2289 done
2290 unset -v ITEM
2291
2292 if (( FEED_FULL_PLAYLIST >= 1 )) ; then
2293 PLAYLIST_NAME=$(echo "PLAYLIST_${FEED_NAME//[[:space:]]/_}.m3u" | tr -s _)
2294 elif (( NO_PLAYLIST == 0 )) && [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
2295 # If configured to create individual playlists for each podcast, set playlist name here.
2296 # White-Space in feed name will be converted to underscores and then tr will limit their repetitions.
2297 PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT)-$(echo "${FEED_NAME//[[:space:]]/_}" | tr -s '_').m3u"
2298
2299 COUNTER=2
2300 while [[ -e "${DIR_LIBRARY}/${PLAYLIST_NAME}" ]] ; do
2301 PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT)-$(echo "${FEED_NAME//[[:space:]]/_}" | tr -s '_').r$COUNTER.m3u"
2302 COUNTER=$((COUNTER+1))
2303 done
2304 elif (( NO_PLAYLIST == 0 )) && [[ -z ${PLAYLIST_PERPODCAST+set} ]]; then
2305 PLAYLIST_NAME="${SESSION_PLAYLIST_NAME}"
2306 fi
2307
2308 if [[ -n ${URL_USERNAME+set} ]]; then
2309 __MSG_INFO "Podcast Username" "${URL_USERNAME}"
2310 fi
2311 if [[ -n ${URL_PASSWORD+set} ]]; then
2312 # Password is stored in the serverlist file in plain text so displaying it here is a small risk but can be
2313 # useful for debugging connection issues.
2314 __MSG_DEBUG "Podcast Password" "${URL_PASSWORD}"
2315 fi
2316 __MSG_DEBUG "WGET Options" "${WGET_OPTIONS[*]}"
2317
2318 # We use double brackets here instead of double parentheses for numeric comparisons because it allows us
2319 # to string the three options together. And inside double brackets, the && (and) takes precedence over the
2320 # || (or). So it can be confusing to read but works.
2321 #
2322 # That is why '[[ A && B || C && D ]]' will result in both A and B needing to be true OR both C and D.
2323 if [[ "${NO_PLAYLIST}" -eq 0 && -n ${PLAYLIST_PERPODCAST+set} || "${FEED_FULL_PLAYLIST}" -gt 0 ]]; then
2324 __MSG_INFO "Playlist Name" "${PLAYLIST_NAME} (for single Podcast)"
2325 fi
2326
2327 if (( VERBOSITY >= 2 )) ; then
2328 echo
2329 echo "Downloading feed index from ${FEED_URL}"
2330 fi
2331
2332 case ${FILETYPE} in
2333 'utf8')
2334 INDEXFILE=$(wget "${WGET_OPTIONS[@]}" -O - "${FEED_URL}") && EXITSTATUS=0 || EXITSTATUS=1
2335 ;;
2336 'utf16')
2337 # Slight gymnastics to report the exit status of WGET and not ICONV.
2338 INDEXFILE=$(wget "${WGET_OPTIONS[@]}" -O - "${FEED_URL}" | iconv -f UTF-16 -t UTF-8; exit "${PIPESTATUS[0]}") && EXITSTATUS=0 || EXITSTATUS=1
2339 ;;
2340 esac
2341
2342 if (( EXITSTATUS != 0 )); then
2343 if (( VERBOSITY >= 1 )); then
2344 printf '%-30s %-50s\n' "" "Error Downloading Feed."
2345 else
2346 echo "ERROR Downloading Feed: ${FEED_NAME}"
2347 fi
2348 # if downloaded failed, add URL to LOG_FAIL
2349 echo "${FEED_URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
2350 continue
2351 fi
2352
2353 INDEXFILE=$(echo "${INDEXFILE}" | tr '\n\r' ' ' | sed -e 's/<\([^/]\)/\n<\1/g')
2354
2355 # We will look for either '<rss ' or '<feed ' opening tags within first 9 lines of the INDEXFILE
2356 local TESTLINES
2357 TESTLINES=$(sed -n 1,9p <<< "${INDEXFILE}")
2358
2359 # While most these messages are acceptably controlled for display via __MSG_DEBUG, we add an extra check
2360 # here because the loop in the center would take extra unnecessary time.
2361 if (( DEBUG >= 1 )) ; then
2362 __MSG_DEBUG "------ Check for RSS or Atom feed --------"
2363 local LINE
2364 while IFS= read -r LINE; do
2365 __MSG_DEBUG "${LINE}"
2366 done< <(printf "%s\n" "${TESTLINES}")
2367 unset -v LINE
2368 __MSG_DEBUG "------ ( first 9 lines of feed --------"
2369 __MSG_DEBUG "------ looking for '<rss ' --------"
2370 __MSG_DEBUG "------ or '<feed ' ) --------"
2371 echo
2372 fi
2373
2374 local INDEXFILE_TMP
2375 local INDEXFILE_TMP2
2376
2377 if grep -q '<rss ' <<< "${TESTLINES}" ;then
2378 __MSG_DEBUG "RSS Feed Found"
2379 if (( DEBUG > 1 )) ; then echo; fi
2380 # if file is RSS then we look for '<enclosure '
2381 # To debug a sed command and see how it flows use --debug option.
2382 # NOTES for sed command:
2383 # 1. -n suppress automatic printing of pattern space
2384 # 2. -e :a set label named 'a'
2385 # 3. -e '/<podcast:liveitem.*<\/podcast:liveitem>/Id'
2386 # Look for podcast:liveitem tags. If found, delete.
2387 # Flags:
2388 # I Ignore case while searching
2389 # d Delete pattern space
2390 # 4. -e '/<podcast:liveitem.*/I{N;s/\ *\n/\ /;T;ba}'
2391 # This command reads the next line into patter space when the podcast:liveitem opening and
2392 # closing tags do not occur on same line. Reads line in, removes the newline character and
2393 # returns to label 'a'.
2394 # 5. -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/\1/Ip'
2395 # Look for enclosure and url in pattern space. If found, print the
2396 # url value. This version looks for when the HTML feed uses double quotes around
2397 # the url value.
2398 # Flags:
2399 # I Ignore case while searching
2400 # p Print only substituted line
2401 # 6. -e 't' if last s/// did successful substitution then branch to end of script
2402 # because no label was provided.
2403 # 7. -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/\\1/Ip"
2404 # This command is here to catch when the HTML feed is using single quotes rather than double
2405 # quotes.
2406 # 8. -e 't' if last s/// did successful substitution then branch to end of script
2407 # because no label was provided.
2408 # 9. -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip'
2409 # Looking for <title> tag and grabbing contents.
2410 # 10. -e 't' if last s/// did successful substitution then branch to end of script
2411 # because no label was provided.
2412 # 11. -e '/\(<enclosure\|<title>\).*/I{N;s/\ *\n/\ /;T;ba}'
2413 # this final command is to read the next line of the file into the pattern space.
2414 # We use this for feeds where the url= portion does not appear on the same line as
2415 # the enclosure start tag or when the closing title tag is not on the same line as
2416 # the opening one. After merging, we go back to label 'a'. Might need to add
2417 # an 'I' flag to make it case insensitive for the 'enclosure' bit.
2418 #
2419 # INDEXFILE before adding TITLE bits
2420 # INDEXFILE=$(echo "${INDEXFILE}" | \
2421 # sed -n -e :a -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/\1/Ip' -e 't' \
2422 # -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/\\1/Ip" \
2423 # -e '/<enclosure\s*/{N;s/ *\n/ /;ba;}')
2424 #
2425 # INDEXFILE_TMP before adding bits to delete podcast:liveitem stuff
2426 # INDEXFILE_TMP=$(echo "${INDEXFILE}" | \
2427 # sed -n -e :a -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/URL \1/Ip' -e t \
2428 # -e "s/.*<enclosure.*url\\s*'=\\s*\\([^i]\\+\\)'.*/URL \\1/Ip" -e t \
2429 # -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip' -e t \
2430 # -e '/\(<enclosure\|<title>\).*/I{N;s/\ *\n/\ /;T;ba}')
2431 if (( WGET_OPTION_RSS_MEDIACONTENT < 1 )); then
2432 INDEXFILE_TMP=$(echo "${INDEXFILE}" | \
2433 sed -n -e :a -e '/<podcast:liveitem.*<\/podcast:liveitem>/Id' \
2434 -e '/<podcast:liveitem.*/I{N;s/\ *\n/\ /;T;ba}' \
2435 -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/URL \1/Ip' -e t \
2436 -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\1/Ip" -e t \
2437 -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip' -e t \
2438 -e '/\(<enclosure\|<title>\).*/I{N;s/\ *\n/\ /;T;ba}')
2439 else
2440 # This section adds a couple of tests to look for <media:content ...> tags from the RSS Media Specification.
2441 # This is used in the feeds created by FreshRSS aggregator so it's use is not expected to be common but we may
2442 # find a few users that require it. These tests were added after test 8 above and before test 9.
2443 # 8.1. -e 's/.*<media:content.*type="\(video\|audio\).*url\s*=\s*"\([^"]\+\)".*/URL \2/Ip'
2444 # Look in pattern space for media:content tags that are preceded by TYPE video or audio then
2445 # extract the URL.
2446 # Flags:
2447 # I Ignore case while searching
2448 # p Print only substituted line
2449 # 8.2. -e 't' if last s/// did successful substitution then branch to end of script
2450 # because no label was provided.
2451 # 8.3. -e "s/.*<media:content.*type='\\(video\\|audio\\).*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\2/Ip"
2452 # This command is the sane as 8.1 but to catch when the HTML feed is using single quotes
2453 # rather than double quotes.
2454 # 8.4. -e 't' if last s/// did successful substitution then branch to end of script
2455 # because no label was provided.
2456 # 8.5. -e 's/.*<media:content.*url\s*=\s*"\([^"]\+\)".*type="\(video\|audio\).*/URL \1/Ip'
2457 # This is like 8.1 but TYPE option follows the URL rather than precedes it.
2458 # 8.6. -e 't' if last s/// did successful substitution then branch to end of script
2459 # because no label was provided.
2460 # 8.7. -e "s/.*<media:content.*url\\s*=\\s*'\\([^']\\+\\)'.*type=\\(video\\|audio\\).*/URL \\1/Ip"
2461 # This is like 8.3 but TYPE option follows the URL rather than precedes it.
2462 # 8.8. -e 't' if last s/// did successful substitution then branch to end of script
2463 # because no label was provided.
2464 # Then the final pattern was updated to also look for incomplete media:content tags.
2465 # 11. -e '/\(<enclosure\|<title>\|<media:content\).*/I{N;s/\ *\n/\ /;T;ba}'
2466 # this final command is to read the next line of the file into the pattern space.
2467 # We use this for feeds where the url= portion does not appear on the same line as
2468 # the enclosure start tag or when the closing title tag is not on the same line as
2469 # the opening one. After merging, we go back to label 'a'. Might need to add
2470 # an 'I' flag to make it case insensitive for the 'enclosure' bit.
2471 #
2472 INDEXFILE_TMP=$(echo "${INDEXFILE}" | \
2473 sed -n -e :a -e '/<podcast:liveitem.*<\/podcast:liveitem>/Id' \
2474 -e '/<podcast:liveitem.*/I{N;s/\ *\n/\ /;T;ba}' \
2475 -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/URL \1/Ip' -e t \
2476 -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\1/Ip" -e t \
2477 -e 's/.*<media:content.*type="\(video\|audio\).*url\s*=\s*"\([^"]\+\)".*/URL \2/Ip' -e t \
2478 -e "s/.*<media:content.*type='\\(video\\|audio\\).*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\2/Ip" -e t \
2479 -e 's/.*<media:content.*url\s*=\s*"\([^"]\+\)".*type="\(video\|audio\).*/URL \1/Ip' -e t \
2480 -e "s/.*<media:content.*url\\s*=\\s*'\\([^']\\+\\)'.*type=\\(video\\|audio\\).*/URL \\1/Ip" -e t \
2481 -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip' -e t \
2482 -e '/\(<enclosure\|<title>\|<media:content\).*/I{N;s/\ *\n/\ /;T;ba}')
2483 fi
2484 # If TITLE tag appears after the ENCLOSURE tag in the file, reverse the order of list for parsing.
2485 if (( POST_WGET_RENAME_REVTITLETAG > 0 )); then
2486 INDEXFILE_TMP=$(echo "${INDEXFILE_TMP}" | sed -n '1!G;h;$p')
2487 fi
2488 # Merge TITLE AND URL lines onto single line divided by '<Url-Title>'
2489 INDEXFILE_TMP2=""
2490 while read -r TAG DATA; do
2491 case ${TAG} in
2492 "TITLE" )
2493 ITEM_TITLE="${DATA}"
2494 ;;
2495 "URL" )
2496 # with cleanup for URL (used to be called FINAL below ATOM section)
2497 ITEM_URL=$(echo "${DATA}" | sed -e 's/\s/%20/g' -e "s/'/%27/g" -e 's/\&apos;/%27/g' -e 's/\&amp;/\&/g')
2498 # Enabled handling of unset ITEM_TITLE items by including a dash at the end of the variable name to
2499 # signify that the default is a blank value (or we could specify a value we wanted after the dash).
2500 INDEXFILE_TMP2+="${ITEM_URL}<Url-Title>${ITEM_TITLE-}${NEWLINE}"
2501 unset -v ITEM_TITLE ITEM_URL
2502 ;;
2503 esac
2504 done <<<"${INDEXFILE_TMP}"
2505 if (( POST_WGET_RENAME_REVTITLETAG > 0 )); then
2506 # Return INDEX to its default order
2507 INDEXFILE=$(echo "${INDEXFILE_TMP2}" | sed -n '1!G;h;$p')
2508 else
2509 # INDEX already in correct order.
2510 INDEXFILE="${INDEXFILE_TMP2}"
2511 fi
2512 elif grep -q '<feed ' <<< "${TESTLINES}"; then
2513 __MSG_DEBUG "Atom Feed Found"
2514 if (( DEBUG > 1 )) ; then echo; fi
2515 # if file is Atom then we look for '<link\s.*rel="enclosure" '
2516 # NOTE: there may be a tag between link and rel, therefore we need to add '\s.*'
2517
2518 # Characters unlikely to appear in an XML document. Combination of "invalid" characters and those
2519 # that have worked well for my testing.
2520 TEST_STRING="^{}_~"
2521
2522 # Find suitable TEST_CHAR to use for sed statements below.
2523 for (( i=0; i<${#TEST_STRING}; i++ )); do
2524 TEST_CHAR=${TEST_STRING:$i:1}
2525
2526 # grep looks for --fixed-strings so that certain characters are not
2527 # interpreted as regular expressions (like ^ $ or /)
2528 #
2529 # We're looking for a character NOT found in the INDEXFILE so its ! grep
2530 if ! grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${INDEXFILE}"; then
2531 # When a character is not found in the string that we can use, break out of the loop.
2532 break
2533 fi
2534 done
2535
2536 unset -v i
2537
2538 # Get full enclosure lines to filter on
2539 INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e "\\${TEST_CHAR}<link\\s.*rel=\"enclosure\".*/>${TEST_CHAR}Ip")
2540
2541 # NOTE: I have this section disabled because it has a high potential for confusing
2542 # users. At this stage, there is potential that they will see many enclosures
2543 # in the feed and not understand why the filtering they have selected results
2544 # in fewer or none found. However it is useful during testing so it is
2545 # available.
2546 # if (( DEBUG > 1 )); then
2547 # __MSG_DEBUG "------ Indexfile Contents --------"
2548 # while IFS= read -r LINE; do
2549 # __MSG_DEBUG "${LINE}"
2550 # done< <(printf "%s\n" "${INDEXFILE}")
2551 # __MSG_DEBUG "----------------------------------"
2552 # __MSG_DEBUG "----------------------------------"
2553 # echo
2554 # fi
2555
2556 # SIMPLE FILTERING: filter down to just audio & video types.
2557 if (( ATOM_FILTER_SIMPLE > 0 )); then
2558 INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e "\\${TEST_CHAR}type=\"\\(audio\\|video\\)${TEST_CHAR}p")
2559 fi
2560
2561 if [[ -n ${ATOM_FILTER_TYPE+set} ]]; then
2562 INDEXFILE=$(echo "${INDEXFILE}" | sed -n -r -e "\\${TEST_CHAR}.*type=\"${ATOM_FILTER_TYPE}\".*${TEST_CHAR}p")
2563 fi
2564
2565 TYPECOUNT=$(echo "${INDEXFILE}" | sed -n -e "s${TEST_CHAR}.*type=\"\\([^\"]\\+\\)\".*${TEST_CHAR}\\1${TEST_CHAR}Ip" | sort | uniq -c | awk '{printf "%7s | %s\n",$1,$2}')
2566
2567 if (( VERBOSITY >= 2 )) ; then
2568 # Check if any filtering is already enabled. If it is, assume that is all the user wants so no need to inform
2569 # them that more is possible.
2570 if (( ATOM_FILTER_SIMPLE == 0 )) && [[ -z ${ATOM_FILTER_TYPE+set} ]]; then
2571 if (( $(echo "${TYPECOUNT}" | wc -l) > 1 )); then
2572 echo
2573 echo "This feed supports multiple types. Consider using ATOM_FILTER_SIMPLE or"
2574 echo "ATOM_FILTER_TYPE to narrow your selection."
2575 echo
2576 echo " COUNT | TYPE"
2577 echo " ------+-------------"
2578 echo "${TYPECOUNT}"
2579 echo
2580 fi
2581 fi
2582 fi
2583
2584 if [[ -n "${ATOM_FILTER_LANG+set}" ]]; then
2585 INDEXFILE=$(echo "${INDEXFILE}" | sed -n -r -e "\\${TEST_CHAR}.*xml:lang=\"${ATOM_FILTER_LANG}\".*${TEST_CHAR}p")
2586 fi
2587
2588 LANGCOUNT=$(echo "${INDEXFILE}" | sed -n -e "s${TEST_CHAR}.*xml:lang=\"\\([^\"]\\+\\)\".*${TEST_CHAR}\\1${TEST_CHAR}Ip" | sort | uniq -c | awk '{printf "%7s | %s\n",$1,$2}')
2589
2590 if (( VERBOSITY >= 2 )) ; then
2591 # Check if any filtering is already enabled. If it is, assume that is all the user wants so no need to inform
2592 if [[ -z "${ATOM_FILTER_LANG+set}" ]]; then
2593 if (( $(echo "${LANGCOUNT}" | wc -l) > 1 )); then
2594 echo
2595 echo "This feed supports multiple languages. Consider using ATOM_FILTER_LANG"
2596 echo "to narrow your selection."
2597 echo
2598 echo " COUNT | LANGUAGE"
2599 echo " ------+-------------"
2600 echo "${LANGCOUNT}"
2601 echo
2602 fi
2603 fi
2604 fi
2605
2606 # Get the URLs from each enclosure after filtering.
2607 INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e "s${TEST_CHAR}.*href=\"\\([^\"]\\+\\)\".*${TEST_CHAR}\\1${TEST_CHAR}Ip")
2608 # final INDEXFILE cleanup options
2609 INDEXFILE=$(echo "${INDEXFILE}" | \
2610 sed -e 's/\s/%20/g' -e "s/'/%27/g" -e 's/\&apos;/%27/g' -e 's/\&amp;/\&/g' | \
2611 sed -e ':a;N;$!ba;s/\n/ /g')
2612 # Convert to new one item per line format. Once we figure out the best way to extract
2613 # titles from we can convert or move this section as necessary.
2614 INDEXFILE_TMP2=""
2615 for ITEM_URL in ${INDEXFILE}; do
2616 INDEXFILE_TMP2+="${ITEM_URL}<Url-Title>${NEWLINE}"
2617 done
2618 # Set back to INDEXFILE
2619 INDEXFILE="${INDEXFILE_TMP2}"
2620 else
2621 echo "Feed is neither RSS, or Atom. Skipping to next feed."
2622 # if Feed is neither RSS or Atom, add URL to LOG_FAIL
2623 echo "${FEED_URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
2624 continue
2625 fi
2626
2627 if [[ -n ${INDEXFILE} ]]; then
2628
2629 # Remove any error log entries for the FEED_URL if it failed before
2630 RemoveURL "${FEED_URL}" "${DIR_LOG}"/"${LOG_FAIL}"
2631
2632 if (( MOST_RECENT > 0 )) ; then
2633 local FULLINDEXFILE="${INDEXFILE}"
2634 local SURPLUSINDEX
2635 if [[ "${FEED_SORT_ORDER}" == "ASCENDING" ]]; then
2636 __MSG_DEBUG "FEED SORT ORDER: ASCENDING"
2637 # Adding one to MOST_RECENT because we tend to have one blank line
2638 # at the end of our INDEXFILE
2639 # -- This was needed when using tail. Does not appear necessary when using sed.
2640 # MOST_RECENT=$((MOST_RECENT+1))
2641 # OpenBSD Tail does not support options with two dashes (so no --lines), we have
2642 # to use the single dash option here or force OpenBSD to use GNU Tail. Given this
2643 # is a single use error, it is easier to use BSD compatible syntax even if it can be
2644 # more challenging to debug.
2645 # INDEXFILE=$(echo "${INDEXFILE}" | tail --lines="${MOST_RECENT}")
2646 # INDEXFILE=$(echo "${INDEXFILE}" | tail -n "${MOST_RECENT}")
2647 # This can also be done with sed but MOST_RECENT needs to be incremented by 2 not 1
2648 # MOST_RECENT=$((MOST_RECENT+2))
2649 # INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e ':a' -e '$p;N;'"${MOST_RECENT}"',$D;ba')
2650 local LINE_COUNT
2651 local LINE_BREAK
2652 LINE_COUNT=$(echo "${FULLINDEXFILE}" | sed -n '$=;')
2653 LINE_BREAK=$((LINE_COUNT - MOST_RECENT))
2654 INDEXFILE=$(echo "${FULLINDEXFILE}" | sed -n "${LINE_BREAK},\$ p")
2655 # SURPLUSINDEX holds all the items that are not in INDEXFILE for marking as already downloaded below.
2656 SURPLUSINDEX=$(echo "${FULLINDEXFILE}" | sed -n "${LINE_BREAK},\$ !p")
2657 unset -v LINE_COUNT
2658 unset -v LINE_BREAK
2659 else
2660 __MSG_DEBUG "FEED SORT ORDER: DESCENDING"
2661 # Attempting to use head here results in exit condition 141, but using the sed construct
2662 # below works. Not sure why given that tail works above.
2663 # INDEXFILE=$(echo "${INDEXFILE}" | head --lines="${MOST_RECENT}")
2664 INDEXFILE=$(echo "${INDEXFILE}" | sed -n "1,${MOST_RECENT}p")
2665 # SURPLUSINDEX holds all the items that are not in INDEXFILE for marking as already downloaded below.
2666 SURPLUSINDEX=$(echo "${FULLINDEXFILE}" | sed -n "1,${MOST_RECENT}!p")
2667
2668 fi
2669 fi
2670
2671 if (( DEBUG >= 1 )) ; then
2672 local URLCOUNT
2673 if (( MOST_RECENT > 0 )) ; then
2674 __MSG_DEBUG "Full Index List:"
2675 URLCOUNT=0
2676 while read -r DATA; do
2677 __MSG_DEBUG "${URLCOUNT}. ${DATA}"
2678 URLCOUNT=$((URLCOUNT+1))
2679 done <<<"${FULLINDEXFILE}"
2680 __MSG_DEBUG "Modified Index List:"
2681 URLCOUNT=0
2682 while read -r DATA; do
2683 __MSG_DEBUG "${URLCOUNT}. ${DATA}"
2684 URLCOUNT=$((URLCOUNT+1))
2685 done <<<"${INDEXFILE}"
2686 else
2687 __MSG_DEBUG "Index List:"
2688 URLCOUNT=0
2689 while read -r DATA; do
2690 __MSG_DEBUG "${URLCOUNT}. ${DATA}"
2691 URLCOUNT=$((URLCOUNT+1))
2692 done <<<"${INDEXFILE}"
2693 fi
2694 unset -v URLCOUNT
2695 fi
2696
2697 # End of this while loop is at approximately line 2980
2698 local DATA
2699 while read -r DATA; do
2700 # Check for blank line, if found just proceed to next line.
2701 if [[ -z "${DATA}" ]]; then
2702 continue
2703 fi
2704
2705 # Divide URL and TITLE from DATA
2706 local URL="${DATA%<Url-Title>*}"
2707 local TITLE="${DATA#*<Url-Title>}"
2708
2709 # Safety check: if ${DATA} does not contain '<Url-Title>'
2710 if [[ "${URL}" == "${TITLE}" ]]; then
2711 TITLE=""
2712 fi
2713
2714 if ! grep -F "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}" >/dev/null || (( FORCE != 0 )) ; then
2715
2716 if (( VERBOSITY >= 2 )) ; then
2717 echo
2718 fi
2719
2720 # Without the 'sed' statements.
2721 local URL_FILENAME="${URL##*/}"
2722 local URL_BASE="${URL%/*}"
2723
2724 # replace any whitespace in the filename with underscores.
2725 URL_FILENAME=$(echo "${URL_FILENAME}" | tr '[:blank:]' '_' | tr -s '_')
2726
2727 # Test for available space on library partition
2728 local AVAIL_SPACE
2729 AVAIL_SPACE=$(df -kP "${DIR_LIBRARY}" | tail -n 1 | awk '{print $4}')
2730 if (( AVAIL_SPACE < MIN_SPACE )); then
2731 printf '\n%s\n%s\n' "Available space on Library partition has dropped below allowed." "Stopping Session." 1>&2
2732 CleanupAndExit ${ERR_LIBLOWSPACE}
2733 fi
2734 unset -v AVAIL_SPACE
2735
2736 # Filename format fixes and character substitutions.
2737 # Return value stored in variable ${MOD_FILENAME}, called here as a string to be used as the name of the
2738 # variable.
2739 local MOD_FILENAME
2740 FilenameFixFormat MOD_FILENAME "${URL_FILENAME}"
2741
2742 # Fix where filename part of URI is constant
2743 # This fix is known to cause issues with in filenames when it is not needed. Disabled by default.
2744 if [[ -n ${FILENAME_FORMATFIX4+set} ]] && (( FILENAME_FORMATFIX4 > 0 )); then
2745 if [[ -z ${MOD_FILENAME} ]] ; then
2746 MOD_FILENAME="${URL_FILENAME}"
2747 fi
2748 local MOD_PREFIX="${URL_BASE%%/}"
2749 local MOD_PREFIX="${MOD_PREFIX##*/}"
2750 MOD_FILENAME="${MOD_PREFIX##*/}_${MOD_FILENAME}"
2751 __MSG_DEBUG "FILENAME FORMAT(4) FIXED: ${MOD_FILENAME}"
2752 fi
2753
2754
2755 if (( POST_WGET_RENAME_TITLETAG == 1 ))||(( POST_WGET_RENAME_REVTITLETAG == 1 )); then
2756 # Title format fixes and character substitutions.
2757 # Return value stored in variable ${MOD_TITLE}, called here as a string to be used as the name of the
2758 # variable.
2759 if [[ -n "${TITLE}" ]]; then
2760 local MOD_TITLE
2761 TitleFixFormat MOD_TITLE "${TITLE}"
2762 if [[ -n "${MOD_TITLE}" ]]; then
2763 TITLE="${MOD_TITLE}"
2764 fi
2765 fi
2766 fi
2767
2768 # If directories do not exist, then create them.
2769 if [[ ! -d "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}" ]]; then
2770 mkdir -p "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}"
2771 fi
2772
2773 # If FORCE then remove existing files before download.
2774 if (( FORCE != 0 )); then
2775 if [[ -n ${MOD_FILENAME} ]]; then
2776 if [[ -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}" ]]; then
2777 if (( VERBOSITY == 0 )) ; then
2778 rm -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}"
2779 else
2780 rm -fv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}"
2781 fi
2782 fi
2783 else
2784 if [[ -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" ]]; then
2785 if (( VERBOSITY == 0 )) ; then
2786 rm -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}"
2787 else
2788 rm -fv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}"
2789 fi
2790 fi
2791 fi
2792 fi
2793
2794 if (( VERBOSITY >= 2 )) ; then
2795 if [[ -n ${MOD_FILENAME} ]]; then
2796 echo -e "Downloading ${MOD_FILENAME} from ${URL_BASE}"
2797 else
2798 echo -e "Downloading ${URL_FILENAME} from ${URL_BASE}"
2799 fi
2800 fi
2801
2802 # Added '&& WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1' to each WGET call below so we could remove the disabling
2803 # of errexit and the ERR trap.
2804 if (( (WGET_OPTION_DISPOSITION == 1) || (WGET_OPTION_FILENAME_LOCATION == 1) )); then
2805 if (( VERBOSITY >= 3 )) ; then
2806 if (( WGET_OPTION_DISPOSITION == 1 )); then
2807 echo " [ Progress meters disabled while using 'wget --content-disposition' ]"
2808 fi
2809 if (( WGET_OPTION_FILENAME_LOCATION == 1 )); then
2810 echo " [ Progress meters disabled while using OPT_FILENAME_LOCATION ]"
2811 fi
2812 fi
2813 # This has been moved here to handle long filenames given by some feeds that result in a WGET Error
2814 if [[ -n ${MOD_FILENAME} ]]; then
2815 wget "${WGET_OPTIONS[@]}" -q --server-response -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}" "${URL}" 2> "${DIR_SESSION}/${URL_FILENAME}.servresp" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
2816 else
2817 wget "${WGET_OPTIONS[@]}" -q --server-response -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" "${URL}" 2> "${DIR_SESSION}/${URL_FILENAME}.servresp" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
2818 fi
2819 else
2820 # This has been moved here to handle long filenames given by some feeds that result in a WGET Error
2821 # ( I'm looking at you ITunes..... )
2822 if [[ -n ${MOD_FILENAME} ]]; then
2823 wget "${WGET_OPTIONS[@]}" -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}" "${URL}" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
2824 else
2825 wget "${WGET_OPTIONS[@]}" -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" "${URL}" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
2826 fi
2827 fi
2828
2829 if (( WGET_EXITSTATUS == 0 )); then
2830 # make sure CONTENT_FILENAME hasn't been used before
2831 unset -v CONTENT_FILENAME
2832 unset -v LOCATION_FILENAME
2833 unset -v FINAL_FILENAME
2834
2835 echo "${URL}" >> "${DIR_LOG}"/"${LOG_COMPLETE}"
2836
2837 # Remove any error log entries for the URL if it failed before
2838 RemoveURL "${URL}" "${DIR_LOG}"/"${LOG_FAIL}"
2839
2840 # Make sure FILENAME variables are local.
2841 local CONTENT_FILENAME
2842 local FINAL_FILENAME
2843 local LOCATION_FILENAME
2844
2845 # Before filename changes, set FINAL_FILENAME to URL_FILENAME
2846 # IF MOD_FILENAME has already been used, then set FINAL_FILENAME to MOD_FILENAME
2847 if [[ -n ${MOD_FILENAME} ]]; then
2848 FINAL_FILENAME="${MOD_FILENAME}"
2849 else
2850 FINAL_FILENAME="${URL_FILENAME}"
2851 fi
2852
2853 # if --content-disposition get filename and remove quotes around it.
2854 if (( WGET_OPTION_DISPOSITION == 1 )); then
2855 __MSG_DEBUG "CONTENT-DISPOSITION TESTS"
2856 if [[ -s "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
2857 __MSG_DEBUG "SERVER RESPONSE FILE NONZERO SIZE"
2858
2859 # Added '|| true' to catch when grep exits with a non-zero status because the
2860 # 'Content-Disposition' tag is not found. This eliminates the need to disable errexit and the
2861 # ERR trap.
2862 CONTENT_FILENAME=$(grep "^\\s\\+Content-Disposition:" "${DIR_SESSION}/${URL_FILENAME}.servresp" | grep "filename=" | tail -1 | sed -e 's/.*filename=//' -e 's/"//g') || true
2863
2864 # Test CONTENT_FILENAME is not null or consists solely of whitespace
2865 if [[ -n ${CONTENT_FILENAME} && -n ${CONTENT_FILENAME// } ]]; then
2866 __MSG_DEBUG "CONTENT_FILENAME: '${CONTENT_FILENAME}'"
2867 else
2868 __MSG_DEBUG "SERVER RESPONSE FILE - No Content-Disposition Tag"
2869 # if variable is effectively blank, we can unset it
2870 unset -v CONTENT_FILENAME
2871
2872 if (( WGET_OPTION_DISPOSITION_FAIL > 0 )); then
2873 __MSG_DEBUG " - Removing URL from ${DIR_LOG}/${LOG_COMPLETE} to retry next session."
2874
2875 # Remove any COMPLETE log entries to allow it to retry next session.
2876 RemoveURL "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}"
2877 fi
2878 fi
2879 else
2880 __MSG_DEBUG "SERVER RESPONSE FILE ZERO SIZE - No Tags"
2881 fi
2882
2883 # Do we need a cleanup on CONTENT_FILENAME here?
2884 # Two step process. First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
2885 # down to a single time.
2886 if [[ -n ${CONTENT_FILENAME+set} ]]; then
2887 CONTENT_FILENAME=$(echo "${CONTENT_FILENAME}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
2888 fi
2889 fi
2890
2891 if (( WGET_OPTION_FILENAME_LOCATION > 0 )); then
2892 __MSG_DEBUG "FILENAME LOCATION TESTS"
2893 if [[ -s "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
2894 __MSG_DEBUG "SERVER RESPONSE FILE NONZERO SIZE"
2895
2896 # Added '|| true' to catch when grep exits with non-zero status because the 'Location' tag was
2897 # not found. This eliminates the need to disable errexit and the ERR trap.
2898 LOCATION_FILENAME=$(grep "^\\s*Location:" "${DIR_SESSION}/${URL_FILENAME}.servresp" | tail -1 | sed -e 's/\s*Location:\s//' -e 's/\(.*\)?.*/\1/') || true
2899
2900 LOCATION_FILENAME="${LOCATION_FILENAME##*/}"
2901
2902 if (( VERBOSITY >= 2 )); then
2903 # Test if LOCATION_FILENAME is not null and does not consist solely of spaces.
2904 if [[ -n ${LOCATION_FILENAME} && -n ${LOCATION_FILENAME// } ]]; then
2905 __MSG_DEBUG "LOCATION_FILENAME: '${LOCATION_FILENAME}'"
2906 else
2907 __MSG_DEBUG "SERVER RESPONSE FILE - No Location Tag"
2908 # If LOCATION_FILENAME is effectively blank we can unset it
2909 unset -v LOCATION_FILENAME
2910 fi
2911 fi
2912 else
2913 __MSG_DEBUG "SERVER RESPONSE FILE ZERO SIZE - No Tags"
2914 fi
2915
2916 # Do we need a cleanup on LOCATION_FILENAME here?
2917 # Two step process. First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
2918 # down to a single time.
2919 if [[ -n ${LOCATION_FILENAME+set} ]]; then
2920 LOCATION_FILENAME=$(echo "${LOCATION_FILENAME}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
2921 fi
2922 fi
2923
2924 # Move filename to that provided by content-disposition
2925 if [[ -n ${CONTENT_FILENAME+set} && -n ${CONTENT_FILENAME} ]]; then
2926 if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${CONTENT_FILENAME}" ]]; then
2927 __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${CONTENT_FILENAME}"
2928 mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${CONTENT_FILENAME}"
2929 FINAL_FILENAME="${CONTENT_FILENAME}"
2930 else
2931 if (( FORCE != 0 )); then
2932 if [[ "${FINAL_FILENAME}" == "${CONTENT_FILENAME}" ]]; then
2933 echo "Filename Change Blocked [ Same Filename ]"
2934 else
2935 __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${CONTENT_FILENAME}"
2936 mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${CONTENT_FILENAME}"
2937 FINAL_FILENAME="${CONTENT_FILENAME}"
2938 fi
2939 else
2940 if (( VERBOSITY >= 2 )); then
2941 echo "Filename Change" "Blocked [ ${CONTENT_FILENAME} already exists ]"
2942 fi
2943 fi
2944 fi
2945 fi
2946
2947 # Move filename to that provided by LOCATION_FILENAME
2948 if [[ -n ${LOCATION_FILENAME+set} && -n ${LOCATION_FILENAME} ]]; then
2949 if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${LOCATION_FILENAME}" ]]; then
2950 __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${LOCATION_FILENAME}"
2951 mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${LOCATION_FILENAME}"
2952 FINAL_FILENAME="${LOCATION_FILENAME}"
2953 else
2954 if (( FORCE != 0 )); then
2955 if [[ "${FINAL_FILENAME}" == "${LOCATION_FILENAME}" ]]; then
2956 if (( VERBOSITY >= 2 )); then
2957 echo "Filename Change" "Blocked [ Same Filename ]"
2958 fi
2959 else
2960 __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${LOCATION_FILENAME}"
2961 mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${LOCATION_FILENAME}"
2962 FINAL_FILENAME="${LOCATION_FILENAME}"
2963 fi
2964 else
2965 if (( VERBOSITY >= 2 )); then
2966 echo "Filename Change Blocked [ ${LOCATION_FILENAME} already exists ]"
2967 fi
2968 fi
2969 fi
2970 fi
2971
2972 # Rename a file to title
2973 if (( POST_WGET_RENAME_TITLETAG == 1 ))||(( POST_WGET_RENAME_REVTITLETAG == 1 )); then
2974 if [[ -n "${TITLE}" ]]; then
2975 __MSG_DEBUG "Title with cleanup: ${TITLE}"
2976 # Get extension from downloaded filename
2977 local OLDEXT="${FINAL_FILENAME##*.}"
2978 local TITLEEXT="${TITLE##*.}"
2979 # To protect against hidden filenames that end in a period ('.')
2980 if [[ -z "${TITLEEXT}" ]]; then
2981 TITLEEXT="${TITLE}"
2982 fi
2983
2984 local FINAL_TITLE
2985
2986 # If TITLE already has filename extension then do not add a second time,
2987 # also check that OLDEXT
2988 if [[ "${OLDEXT}" != "${TITLEEXT}" ]] && [[ -n "${OLDEXT}" ]]; then
2989 # With pattern substitution to remove a trailing period from title before
2990 # we add one for the extension.
2991 FINAL_TITLE="${TITLE/%./}.${OLDEXT}"
2992 else
2993 FINAL_TITLE="${TITLE}"
2994 fi
2995 __MSG_DEBUG "Title with extension: ${FINAL_TITLE}"
2996 if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_TITLE}" ]]; then
2997 __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${FINAL_TITLE}"
2998 mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_TITLE}"
2999 FINAL_FILENAME="${FINAL_TITLE}"
3000 else
3001 if (( FORCE != 0 )); then
3002 __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${FINAL_TITLE}"
3003 mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_TITLE}"
3004 FINAL_FILENAME="${FINAL_TITLE}"
3005 else
3006 if (( VERBOSITY >= 2 )); then
3007 echo "Filename Change Blocked [ ${FINAL_TITLE} already exists ]"
3008 fi
3009 fi
3010 fi
3011 else
3012 __MSG_DEBUG "Title not set for this item"
3013 fi
3014 fi
3015
3016
3017 # Rename file to start from modification date
3018 if (( POST_WGET_RENAME_MDATE == 1 )); then
3019 local FILE_MDATE
3020 FILE_MDATE=$(date -r "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" '+%Y%m%d_%Hh%Mm')
3021 local FILENAME_MDATE="${FILE_MDATE}_${FINAL_FILENAME}"
3022 if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FILENAME_MDATE}" ]]; then
3023 __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${FILENAME_MDATE}"
3024 mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FILENAME_MDATE}"
3025 FINAL_FILENAME="${FILENAME_MDATE}"
3026 else
3027 if (( FORCE != 0 )); then
3028 __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${FILENAME_MDATE}"
3029 mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FILENAME_MDATE}"
3030 FINAL_FILENAME="${FILENAME_MDATE}"
3031 else
3032 if (( VERBOSITY >= 2 )); then
3033 echo "Filename Change Blocked [ ${FILENAME_MDATE} already exists ]"
3034 fi
3035 fi
3036 fi
3037 fi
3038
3039 # Add filename.suffix
3040 if [[ -n ${FILENAME_SUFFIX+set} ]]; then
3041 if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}.${FILENAME_SUFFIX}" ]]; then
3042 __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${FINAL_FILENAME}.${FILENAME_SUFFIX}"
3043 mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}.${FILENAME_SUFFIX}"
3044 FINAL_FILENAME="${FINAL_FILENAME}.${FILENAME_SUFFIX}"
3045 else
3046 if (( FORCE != 0 )); then
3047 __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${FINAL_FILENAME}.${FILENAME_SUFFIX}"
3048 mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}.${FILENAME_SUFFIX}"
3049 FINAL_FILENAME="${FINAL_FILENAME}.${FILENAME_SUFFIX}"
3050 else
3051 if (( VERBOSITY >= 2 )); then
3052 echo "Filename Change Blocked [ ${FINAL_FILENAME}.${FILENAME_SUFFIX} already exists ]"
3053 fi
3054 fi
3055 fi
3056 fi
3057
3058 if (( NO_PLAYLIST == 0 )) || (( FEED_FULL_PLAYLIST >= 1 )) ; then
3059 # If creating playlists, then add to file. Added sed command to remove any './' from each item
3060 # added to a playlist or the echo statement.
3061 if [[ -n ${PLAYLIST_NAME+set} ]] ; then
3062 echo "${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" | sed -e 's|[.]/||g' >> "${DIR_LIBRARY}/${PLAYLIST_NAME}"
3063 if (( VERBOSITY >= 2 )); then
3064 echo "PLAYLIST: Adding ${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME} to ${DIR_LIBRARY}/${PLAYLIST_NAME}" | sed -e 's|[.]/||g'
3065 fi
3066 fi
3067 fi
3068
3069 # We're done with CONTENT_FILENAME and FINAL_FILENAME, make sure they are cleared
3070 if [[ -n ${CONTENT_FILENAME+set} ]] ; then
3071 unset -v CONTENT_FILENAME
3072 fi
3073 if [[ -n ${FINAL_FILENAME+set} ]] ; then
3074 unset -v FINAL_FILENAME
3075 fi
3076 else
3077 # if downloaded failed, add URL to LOG_FAIL
3078 if (( VERBOSITY >= 2 )) ; then
3079 echo "Adding URL to error log."
3080 fi
3081 echo "${URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
3082 # If file has zero size then remove it. Files that are larger than zero size are kept so WGET's
3083 # continue function can work on later attempts.
3084 local REMOVE_FILENAME
3085 if [[ -n ${MOD_FILENAME} ]]; then
3086 REMOVE_FILENAME="${MOD_FILENAME}"
3087 else
3088 REMOVE_FILENAME="${URL_FILENAME}"
3089 fi
3090 if [[ -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}" ]]; then
3091 if (( VERBOSITY >= 2 )) ; then
3092 echo "Partial file exists."
3093 fi
3094 if [[ ! -s "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}" ]]; then
3095 if (( VERBOSITY >= 2 )) ; then
3096 echo "- Removing zero size file."
3097 rm -fv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}"
3098 else
3099 rm -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}"
3100 fi
3101 else
3102 if (( VERBOSITY >= 2 )) ; then
3103 echo "- Keeping for later attempts"
3104 fi
3105 fi
3106 else
3107 if (( VERBOSITY >= 2 )) ; then
3108 echo "Partial file does not exist."
3109 fi
3110 fi
3111 fi
3112 else
3113 # Remove any error log entries for the URL if it failed before
3114 RemoveURL "${URL}" "${DIR_LOG}"/"${LOG_FAIL}"
3115
3116 if (( VERBOSITY >= 2 )) ; then
3117 if (( VERBOSITY >= 4 )) ; then echo ; fi
3118 echo "Already downloaded ${URL}."
3119 fi
3120 fi
3121
3122 # Remove server response file as it's no longer needed
3123 if (( DEBUG >= 0 )); then
3124 if [[ -n ${URL_FILENAME+set} && -f "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
3125 rm -f "${DIR_SESSION}/${URL_FILENAME}.servresp"
3126 fi
3127 else
3128 if [[ -n ${URL_FILENAME+set} && -f "${DIR_SESSION}/${URL_FILENAME}.servresp" ]] && (( DEBUG > 1 )) ; then
3129 __MSG_DEBUG "Not deleting ${DIR_SESSION}/${URL_FILENAME}.servresp"
3130 fi
3131 fi
3132
3133 __MSG_DEBUG "Clear File Vars"
3134 unset -v URL_FILENAME
3135 done <<< "${INDEXFILE}"
3136
3137 if (( VERBOSITY >= 3 )) ; then echo; fi
3138
3139 if (( (MOST_RECENT != 0) && (INSTALL_SESSION == 0) )); then
3140 __MSG_DEBUG "Marking additional files in Index as already downloaded (RECENT > 0)."
3141 # for URL in ${FULLINDEXFILE}
3142 # do
3143 while read -r DATA; do
3144 # Check for blank line, if found just proceed to next line.
3145 if [[ -z "${DATA}" ]]; then
3146 continue
3147 fi
3148
3149 # Divide URL and TITLE from DATA
3150 local URL="${DATA%<Url-Title>*}"
3151 local TITLE="${DATA#*<Url-Title>}"
3152
3153 # Safety check: if ${DATA} does not contain '<Url-Title>'
3154 if [[ "${URL}" == "${TITLE}" || "${TITLE}" == "" ]]; then
3155 unset -v TITLE
3156 fi
3157
3158 if ! grep -F "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}" >/dev/null ; then
3159 local URL_FILENAME
3160 URL_FILENAME=$(echo "${URL}" | sed -e 's/.*\/\([^\/]\+\)/\1/' -e 's/%20/ /g')
3161 if (( VERBOSITY >= 2 )) ; then
3162 if (( POST_WGET_RENAME_TITLETAG == 1 ))||(( POST_WGET_RENAME_REVTITLETAG == 1 )); then
3163 if [[ -n "${TITLE}" ]]; then
3164 echo "Marking as already downloaded ${TITLE}."
3165 else
3166 echo "Marking as already downloaded ${URL_FILENAME}."
3167 fi
3168 else
3169 echo "Marking as already downloaded ${URL_FILENAME}."
3170 fi
3171 fi
3172 echo "${URL}" >> "${DIR_LOG}"/"${LOG_COMPLETE}"
3173 fi
3174 done <<< "${SURPLUSINDEX}"
3175 fi
3176
3177 # If doing individual playlists for each podcast Sort new playlist
3178 if (( NO_PLAYLIST == 0 )) && [[ -e "${DIR_LIBRARY}/$PLAYLIST_NAME" && -n "${PLAYLIST_PERPODCAST+set}" ]]; then
3179 PlaylistSort "${DIR_LIBRARY}" "${PLAYLIST_NAME}"
3180
3181 # If doing individual playlists for each podcast, Create ASX Playlist
3182 if (( ASX_PLAYLIST > 0 )); then
3183 PlaylistConvertToASX "${DIR_LIBRARY}" "${PLAYLIST_NAME}"
3184 fi
3185
3186 # Done with playlist, unset name.
3187 unset -v PLAYLIST_NAME
3188 fi
3189 else
3190 if (( VERBOSITY >= 1 )) ; then
3191 echo " No enclosures in feed: ${FEED_URL}"
3192 fi
3193 echo "${FEED_URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
3194 fi
3195
3196
3197 __MSG_DEBUG "Clear Server Loop Vars"
3198 unset -v FEED_URL
3199 unset -v FEED_CATEGORY
3200 unset -v FEED_NAME
3201 unset -v URL_FILENAME
3202 unset -v URL_USERNAME
3203 unset -v URL_PASSWORD
3204 done < "${CURRENT_SERVERLIST}"
3205 done
3206
3207 # If doing one combined playlist for all podcasts, Sort new playlist
3208 if (( NO_PLAYLIST == 0 )) && [[ -n ${PLAYLIST_NAME+set} ]]; then
3209 if [[ -e "${DIR_LIBRARY}/$PLAYLIST_NAME" ]]; then
3210 PlaylistSort "${DIR_LIBRARY}" "${PLAYLIST_NAME}"
3211
3212 # If doing one combined playlist for all podcasts, Create ASX Playlist
3213 if (( ASX_PLAYLIST > 0 )); then
3214 PlaylistConvertToASX "${DIR_LIBRARY}" "${PLAYLIST_NAME}"
3215 fi
3216 fi
3217 fi
3218 }
3219 # }}}
3220
3221 # Function: RemoveURL {{{
3222 # Simple function to cleanup URLs for removal from FILE.
3223 # Arguments:
3224 # ${1} == URL to remove from file
3225 # ${2} == FILE to remove URL from
3226 RemoveURL() {
3227 local -r URL_INPUT=${1}
3228 local -r TARGET_FILE=${2}
3229
3230 # Characters unlikely to appear in an URL that are suitable for use as delimiters in SED statements.
3231 # List has been pruned down to eliminate any characters that need to be escaped themselves.
3232 # Listed as "Unsafe" in RFC 1738
3233 # Source: https://www.ietf.org/rfc/rfc1738.txt
3234 local TEST_STRING="#|^~<>[] "
3235
3236 # Find suitable TEST_CHAR to use for sed statements below.
3237 for (( i=0; i<${#TEST_STRING}; i++ )); do
3238 local TEST_CHAR=${TEST_STRING:$i:1}
3239
3240 # grep looks for --fixed-strings so that certain characters are not
3241 # interpreted as regular expressions (like ^ $ or /)
3242 #
3243 # We're looking for a character NOT found in the string so its ! grep
3244 if ! grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${URL_INPUT}"; then
3245 # When a character is not found in the string that we can use, break out of the loop.
3246 break
3247 fi
3248 done
3249
3250 unset -v i
3251
3252 # Both sed statements below use TEST_CHAR as their delimiter
3253
3254 # Escape any characters in URL that can affect the sed command below, currently: *
3255 local URL_CLEAN
3256 # URL_CLEAN as it was before trying to correct implicit escaping.
3257 # URL_CLEAN=$(echo "${URL_INPUT}" | sed -e "s${TEST_CHAR}\([^\\]\)\*${TEST_CHAR}\1\\\*${TEST_CHAR}g")
3258 # shellcheck disable=SC2001
3259 URL_CLEAN=$(echo "${URL_INPUT}" | sed -e "s${TEST_CHAR}\\([^\\]\\)\\*${TEST_CHAR}\\1\\\\*${TEST_CHAR}g")
3260
3261 sed -i "\\${TEST_CHAR}${URL_CLEAN}${TEST_CHAR}d" "${TARGET_FILE}"
3262 }
3263 # }}}
3264
3265 # Function: TitleFixFormat {{{
3266 # Minor issues in Title strings are fixed so that it is compatible with most filesystems.
3267 # Arguments:
3268 # ${1} == name of variable to hold return string
3269 # ${2} == string to fix the format of
3270 TitleFixFormat() {
3271 # variable to hold returned value.
3272 local -r VAR_RETURN=${1}
3273
3274 # Filename to be modified.
3275 # Set original value for title format fixes and character substitutions.
3276 # Set according to what is passed as the second argument to function.
3277 local MODIFIED_TITLE=${2}
3278
3279 # ORIGINAL and MODIFIED start out the same.
3280 local -r ORIGINAL_TITLE="${MODIFIED_TITLE}"
3281
3282 __MSG_INFO "ORIGINAL TITLE" "${ORIGINAL_TITLE}"
3283
3284 if [[ "${MODIFIED_TITLE}" =~ .*" ".* ]]; then
3285 MODIFIED_TITLE="${MODIFIED_TITLE// /${FILENAME_REPLACECHAR}}"
3286 __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
3287 fi
3288
3289 # Fix for ampersand (&) is interesting because the character will be removed by the default FILENAME_BADCHARS list.
3290 # We include it here for people who remove the & from their FILENAME_BADCHARS.
3291 if [[ "${MODIFIED_TITLE}" =~ .*"&amp;".* ]]; then
3292 MODIFIED_TITLE="${MODIFIED_TITLE//\&amp;/\&}"
3293 __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
3294 fi
3295
3296 # Case insensitive BASH regex test followed by case insensitive replacement by sed.
3297 if [[ "${MODIFIED_TITLE,,}" =~ "<![cdata[".*"]]>" ]]; then
3298 MODIFIED_TITLE=$(echo "${MODIFIED_TITLE}" | sed -n -e 's/<!\[cdata\[\(.*\)]]>/\1/Ip')
3299 __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
3300 fi
3301
3302 # Test if BADCHARS set
3303 if [[ -n ${FILENAME_BADCHARS+set} ]] ; then
3304 # Test for BADCHARS in MODIFIED_TITLE
3305 if [[ ${MODIFIED_TITLE} =~ ["${FILENAME_BADCHARS}"] ]]; then
3306 # Two step process. First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
3307 # down to a single time.
3308 MODIFIED_TITLE=$(echo "${MODIFIED_TITLE}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
3309 __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
3310 fi
3311 fi
3312
3313 if [[ ${MODIFIED_TITLE} =~ [/] ]]; then
3314 # Replace forward slashes in titles with dash as the using a forward slash in a name is not POSIX compliant
3315 MODIFIED_TITLE="${MODIFIED_TITLE//\//-}"
3316 __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
3317 fi
3318
3319 # After replacing characters, strings may look ugly because they start or end with the FILENAME_REPLACECHAR or a dash.
3320 # Therefore we remove those here.
3321 if [[ ${MODIFIED_TITLE:0:1} =~ ["${FILENAME_REPLACECHAR}"-] ]]; then
3322 MODIFIED_TITLE="${MODIFIED_TITLE:1}"
3323 __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
3324 fi
3325 # Negative indices from the trailing end of the string require a space before the dash.
3326 if [[ ${MODIFIED_TITLE: -1} =~ ["${FILENAME_REPLACECHAR}"-] ]]; then
3327 MODIFIED_TITLE="${MODIFIED_TITLE:: -1}"
3328 __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
3329 fi
3330
3331 if [[ "${ORIGINAL_TITLE}" != "${MODIFIED_TITLE}" ]]; then
3332 __MSG_INFO "MODIFIED TITLE" "${MODIFIED_TITLE}"
3333 fi
3334
3335 # Pass the modified filename back to the calling variable.
3336 printf -v "${VAR_RETURN}" '%s' "${MODIFIED_TITLE}"
3337
3338 # close without error
3339 return 0
3340 }
3341 # }}}
3342
3343 # }}}
3344 # ----------------------------------------------------------------------------------------------------------------------------------
3345 # Portability tests for OS other than Linux {{{
3346 # A few tests to allow Podget to run on Mac OSX, FreeBSD, NetBSD and OpenBSD.
3347
3348 uname=$(uname)
3349 case "$uname" in
3350 "Linux") :;;
3351 "Darwin")
3352 DARWIN_EXIT=0
3353
3354 if ! hash gsed >/dev/null 2>&1; then
3355 echo "GNU Sed Required."
3356 echo "Try 'brew install gnu-sed' (see https://brew.sh for details)"
3357 DARWIN_EXIT=1
3358 else
3359 hash -p "$(hash -t gsed)" sed
3360 fi
3361 if ! hash gtr >/dev/null 2>&1; then
3362 echo "GNU tr Required."
3363 echo "Try 'brew install coreutils' (see https://brew.sh for details)"
3364 DARWIN_EXIT=1
3365 else
3366 hash -p "$(hash -t gtr)" tr
3367 fi
3368 if ! hash gdate >/dev/null 2>&1; then
3369 echo "GNU Date Required."
3370 echo "Try 'brew install gdate' (see https://brew.sh for details)"
3371 DARWIN_EXIT=1
3372 else
3373 hash -p "$(hash -t gdate)" date
3374 fi
3375 if ! hash gstat >/dev/null 2>&1; then
3376 echo "GNU Stat Required."
3377 echo "Try 'brew install gstat' (see https://brew.sh for details)"
3378 DARWIN_EXIT=1
3379 else
3380 hash -p "$(hash -t gstat)" stat
3381 fi
3382 if (( DARWIN_EXIT > 0 )); then
3383 CleanupAndExit 1
3384 fi
3385 unset -v DARWIN_EXIT
3386 ;;
3387 "OpenBSD"|"NetBSD"|"FreeBSD")
3388 missing_counter=0
3389 needed_commands=( gsed gdate gtr )
3390 if [[ $uname == FreeBSD ]]; then
3391 needed_commands+=(gnustat)
3392 else
3393 needed_commands+=(gstat)
3394 fi
3395
3396 for needed_command in "${needed_commands[@]}"; do
3397 if ! hash "$needed_command" >/dev/null 2>&1; then
3398 printf "Command not found in PATH: %s\n" "$needed_command" >&2
3399 ((++missing_counter))
3400 else
3401 hash -p "$(hash -t "$needed_command")" "${needed_command##@(g|gnu)}"
3402 fi
3403 done
3404 if (( missing_counter > 0 )); then
3405 CleanupAndExit 1
3406 fi
3407 unset -v needed_command{,s} missing_counter
3408 ;;
3409 esac
3410
3411 # }}}
3412 # ----------------------------------------------------------------------------------------------------------------------------------
3413 # Podget Body Function {{{
3414
3415 PodgetCore() {
3416 # ------------------------------------------------------------------------------------------------------------------------------
3417 # Version (Update with changes!) {{{
3418
3419 local VERSION=1.0.0
3420 local REPORT_VERSION=0
3421
3422 # }}}
3423 # ------------------------------------------------------------------------------------------------------------------------------
3424 # Defaults {{{
3425
3426 #########################################################################################################################
3427 ## Do not configure here. Run podget once to install default user configuration files and edit there. ##
3428 #########################################################################################################################
3429
3430 # Set DIR_LIBRARY, DIR_SESSION, and DIR_LOG in config file.
3431 local CONFIG_CORE="podgetrc"
3432 local CONFIG_SERVERLIST="serverlist"
3433
3434 # Configuration Directory:
3435 # This used to be stored by default in the base of the users home directory.
3436 #local DIR_CONFIG="${HOME}/.podget"
3437 #
3438 # However we've update Podget to use three possible locations to help reduce clutter in the home directory.
3439 # For locations are:
3440 # 1. ${HOME}/.podget
3441 # 2. ${XDG_CONFIG_HOME}/podget
3442 # 3. ${HOME}/.config/podget
3443 # For existing users, when Podget runs it will test all three in that order. The first one it finds will become the
3444 # default configuration directory.
3445 #
3446 # For new users, Podget will attempt to use XDG_CONFIG_HOME but if that is not set will fallback to ${HOME}/.config/podget
3447 #
3448 # To use default configuration directory, set DIR_CONFIG to "UNSET-use-DEFAULT"
3449 # Or you can configure it to use any directory you want by configuring it here.
3450 local DIR_CONFIG="UNSET-use-DEFAULT"
3451
3452 # DEFAULT FILENAME_BADCHARS used to test the configuration filenames and then unset. The value used later in the script may be
3453 # set in the configuration file. If you have a genuine need to use one of these characters in the filenames of the serverlist
3454 # or core configuration file then you may need to remove it from this definition. For all other uses, modify the setting in
3455 # your configuration file (by default in podgetrc).
3456 #
3457 # This is a subset of the FILENAME_BADCHARS set in the default configuration file. Many of the symbols that have been removed
3458 # are because they will cause other errors when used on the command line that prevent these checks from working.
3459 local FILENAME_BADCHARS="~#^=+{}[]:\"'?\\"
3460
3461 # Filename Replace Character: Character to use to replace any/all
3462 # bad characters found.
3463 local FILENAME_REPLACECHAR=_
3464
3465 # Auto-Cleanup.
3466 # 0 == disabled
3467 # 1 == delete any old content
3468 local CLEANUP=0
3469
3470 # Skip downloading and just run cleanup
3471 # 0 == disable
3472 local CLEANUP_ONLY=0
3473
3474 # Simulate cleanup
3475 local CLEANUP_SIMULATE=0
3476
3477 # Number of days to keep files. Cleanup will remove anything
3478 # older than this.
3479 local CLEANUP_DAYS=7
3480
3481 # Most Recent
3482 # 0 == download all new items.
3483 # 1+ == download only the <count> most recent
3484 local MOST_RECENT=0
3485
3486 # Force
3487 # 0 == Only download new material.
3488 # 1 == Force download all items even those you've downloaded before.
3489 local FORCE=0
3490
3491 # Install session. This gets called when script is first installed.
3492 local INSTALL_SESSION=0
3493
3494 # Stop downloads if available space drops below
3495 local MIN_SPACE=10000
3496
3497 # Date format for new playlist names
3498 local DATE_FORMAT=+%F
3499
3500 # ASX Playlists for Windows Media Player
3501 # 0 == do not create
3502 # 1 == create
3503 local ASX_PLAYLIST=0
3504
3505 # Enable playlist creation
3506 local NO_PLAYLIST=0
3507
3508 # Default Wget no options
3509 local WGET_BASEOPTS=""
3510
3511 # Order that items appear in feed.
3512 # Default: DESCENDING - Newest items appear first, oldest last.
3513 local FEED_SORT_ORDER="DESCENDING"
3514
3515 # Create or update full playlist for each feed of all available items.
3516 # 0 == Enable
3517 # 1 == Disable
3518 local FEED_FULL_PLAYLIST=0
3519
3520 #########################################################################################################################
3521 ## Do not configure here. Run podget once to install default user configuration files ($HOME/.podget) and edit there. ##
3522 #########################################################################################################################
3523
3524 # Internal script defaults
3525 local NEWLINE=$'\n'
3526
3527 # }}}
3528 # ------------------------------------------------------------------------------------------------------------------------------
3529 # Parse command line {{{
3530
3531 # Set defaults for command line options so variables do not conflict with 'set -o nounset' by being undeclared.
3532 local CMDL_CLEANUP_SIMULATE=0
3533 local CMDL_FORCE=0
3534
3535 while (( $# >= 1 )); do
3536 case ${1} in
3537 -c | --config ) local CONFIG_CORE=${2:-NONE} ; shift ; shift || : ;;
3538 --create-config ) local CONFIG_CORE=${2:-NONE}; local CMDL_CREATECONFIG=1 ; shift ; shift || : ;;
3539 -C | --cleanup ) local CLEANUP_ONLY=1 ; local CLEANUP=1 ; shift ;;
3540 --cleanup_days ) local CMDL_CLEANUP_DAYS=${2:-NONE} ; shift ; shift || : ;;
3541 --cleanup_simulate ) local CMDL_CLEANUP_SIMULATE=1 ; local CLEANUP_ONLY=1 ; local CLEANUP=1 ; shift ;;
3542 -d | --dir_config ) local DIR_CONFIG=${2:-NONE} ; shift ; shift || : ;;
3543 --dir_session ) local CMDL_SESSION=${2:-NONE} ; shift ; shift || : ;;
3544 -f | --force ) local CMDL_FORCE=1 ; shift ;;
3545 --import_opml ) local IMPORT_OPML=${2:-NONE} ; shift ; shift || : ;;
3546 --export_opml ) local EXPORT_OPML=${2:-NONE} ; shift ; shift || : ;;
3547 --import_pcast ) local IMPORT_PCAST=${2:-NONE} ; shift ; shift || : ;;
3548 -l | --library ) local CMDL_LIBRARY=${2:-NONE} ; shift ; shift || : ;;
3549 -n | --no-playlist ) local CMDL_NOPLAYLIST=1 ; shift ;;
3550 -p | --playlist-asx ) local CMDL_ASX=1 ; shift ;;
3551 --playlist-per-podcast ) local CMDL_PLAYLISTPERPODCAST=1 ; shift ;;
3552 -r | --recent ) local CMDL_MOSTRECENT=${2:-NONE} ; shift ; shift || : ;;
3553 --serverlist ) local CMDL_SERVERLIST=${2:-NONE} ; shift ; shift || : ;;
3554 -s | --silent ) VERBOSITY=0 ; shift ;;
3555 -V | --version ) VERBOSITY=2 ; REPORT_VERSION=1 ; shift ;;
3556 -v ) VERBOSITY=1 ; shift ;;
3557 -vv ) VERBOSITY=2 ; shift ;;
3558 -vvv ) VERBOSITY=3 ; shift ;;
3559 -vvvv ) VERBOSITY=4 ; shift ;;
3560 --verbosity ) VERBOSITY=${2:-NONE} ; shift ; shift || : ;;
3561 * ) DisplayShortHelp ; CleanupAndExit ${ERR_DISPLAYHELP} ;;
3562 esac
3563 done
3564
3565 if [[ -n ${VERBOSITY+set} ]] ; then
3566 if [[ -z ${VERBOSITY##*[!0-9]*} ]]; then
3567 echo "Verbosity is not a supported integer value"
3568 exit 1
3569 fi
3570 fi
3571
3572 if [[ -n ${CMDL_SERVERLIST+set} ]] ; then
3573 if [[ ${CMDL_SERVERLIST} == "NONE" ]]; then
3574 echo "Unset filename for server list"
3575 CleanupAndExit 1
3576 fi
3577 CONFIG_SERVERLIST=${CMDL_SERVERLIST}
3578 fi
3579
3580 if (( VERBOSITY >= 2 )) ; then
3581 echo "podget"
3582 echo
3583 fi
3584
3585 if (( REPORT_VERSION == 1 )); then
3586 echo "Version: ${VERSION}"
3587 CleanupAndExit 0
3588 fi
3589
3590 if [[ ${CONFIG_CORE} == "NONE" ]]; then
3591 echo "Unset filename for configuration"
3592 CleanupAndExit 1
3593 fi
3594
3595 if [[ ${DIR_CONFIG} == "NONE" ]]; then
3596 echo "Unset directory to store configuration"
3597 CleanupAndExit 1
3598 fi
3599
3600 __MSG_INFO "Parsing Config file." ""
3601 __MSG_INFO "Config directory:" "${DIR_CONFIG}"
3602 __MSG_INFO "Config file:" "${CONFIG_CORE}"
3603 __MSG_INFO "Server List:" "${CONFIG_SERVERLIST}"
3604
3605 if [[ -n ${CMDL_NOPLAYLIST+set} ]]; then
3606 if [[ -n ${CMDL_ASX+set} ]]; then
3607 printf '%-30s %s' "Error:" "Conflicting playlist options."
3608 CleanupAndExit 1
3609 fi
3610 fi
3611
3612 # for testing
3613 #echo "Verbosity: ${VERBOSITY}"
3614 #CleanupAndExit 0
3615
3616 # Test filename for CONFIG_CORE, CMDL/CONFIG_SERVERLIST and directory for DIR_CONFIG
3617 __MSG_DEBUG "Loading temporary FILENAME_BADCHARS to test base configuration file and directory names."
3618
3619 FilenameCheck CONFIG_CORE
3620 if [[ -n ${CMDL_SERVERLIST+set} ]] ; then
3621 FilenameCheck CMDL_SERVERLIST
3622 else
3623 FilenameCheck CONFIG_SERVERLIST
3624 fi
3625
3626 DirectoryCheck DIR_CONFIG
3627
3628 __MSG_DEBUG "Clearing temporary FILENAME_BADCHARS, will read configured version from ${CONFIG_CORE}"
3629 unset -v FILENAME_BADCHARS
3630
3631 # }}}
3632 # ------------------------------------------------------------------------------------------------------------------------------
3633 # CONFIG TEST PART 1 of 4: Test for existing DIR_CONFIG, if missing create it and install CONFIG_CORE {{{
3634
3635 if [[ "${DIR_CONFIG}" == "UNSET-use-DEFAULT" ]]; then
3636 __MSG_DEBUG "DIR_CONFIG is not configured, checking for other possible locations"
3637 DIR_CONFIG_NAME="podget"
3638
3639 if [[ -d "${HOME}/.${DIR_CONFIG_NAME}" ]]; then
3640 __MSG_DEBUG "HOME/.${DIR_CONFIG_NAME} exists!"
3641 DIR_CONFIG="${HOME}/.${DIR_CONFIG_NAME}"
3642 elif [[ -n ${XDG_CONFIG_HOME+set} && -d "${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}" ]]; then
3643 __MSG_DEBUG "XDG_CONFIG_HOME is set and '${DIR_CONFIG_NAME}' exists within it"
3644 DIR_CONFIG="${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
3645 elif [[ -d "${HOME}/.config" && -d "${HOME}/.config/${DIR_CONFIG_NAME}" ]]; then
3646 __MSG_DEBUG "HOME/.config exists and '${DIR_CONFIG_NAME}' exists within it"
3647 DIR_CONFIG="${HOME}/.config/${DIR_CONFIG_NAME}"
3648 else
3649 __MSG_DEBUG "'${DIR_CONFIG_NAME}' directory does not exist in any of the likely locations."
3650 if [[ -n ${XDG_CONFIG_HOME+set} ]]; then
3651 if [[ -d "${XDG_CONFIG_HOME}" ]]; then
3652 mkdir "${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
3653 EXITSTATUS=$?
3654 if (( EXITSTATUS != 0 )); then
3655 printf '%-30s %s' "Error:" "Error creating directory: ${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
3656 CleanupAndExit 1
3657 fi
3658 DIR_CONFIG="${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
3659 else
3660 printf '%-30s %s' "Error:" "Error: XDG_CONFIG_HOME directory does not exist ('${XDG_CONFIG_HOME}')"
3661 CleanupAndExit 1
3662 fi
3663 else
3664 if [[ ! -d "${HOME}/.config/${DIR_CONFIG_NAME}" ]]; then
3665 mkdir -p "${HOME}/.config/${DIR_CONFIG_NAME}"
3666 EXITSTATUS=$?
3667 if (( EXITSTATUS != 0 )); then
3668 printf '%-30s %s' "Error:" "Error creating directory: ${HOME}/.config/${DIR_CONFIG_NAME}"
3669 CleanupAndExit 1
3670 fi
3671 DIR_CONFIG="${HOME}/.config/${DIR_CONFIG_NAME}"
3672 fi
3673 fi
3674 INSTALL_SESSION=1
3675 fi
3676 else
3677 if [[ ! -d "${DIR_CONFIG}" ]]; then
3678 mkdir -p "${DIR_CONFIG}"
3679 EXITSTATUS=$?
3680 if (( EXITSTATUS != 0 )); then
3681 printf '%-30s %s' "Error:" "Error creating directory: ${DIR_CONFIG}"
3682 CleanupAndExit 1
3683 fi
3684 INSTALL_SESSION=1
3685 fi
3686 fi
3687
3688 # Exit if set to --create-config
3689 if [[ -n ${CMDL_CREATECONFIG+set} ]]; then
3690 if (( CMDL_CREATECONFIG == 1 )); then
3691 if [[ -f "${DIR_CONFIG}/${CONFIG_CORE}" ]]; then
3692 echo " Configuration file ${DIR_CONFIG}/${CONFIG_CORE} already exists."
3693 echo " If you would like to reuse this name, then the old file needs"
3694 echo " to be deleted first. Or you need to pick a new name."
3695 CleanupAndExit 1
3696 fi
3697 fi
3698 fi
3699
3700 # }}}
3701 # ------------------------------------------------------------------------------------------------------------------------------
3702 # CONFIG TEST PART 2 of 4: Test for existing CONFIG_CORE, if missing create it. {{{
3703
3704 if [[ ! -f "${DIR_CONFIG}/${CONFIG_CORE}" ]] ; then
3705
3706 echo " Installing default user configuration file in ${DIR_CONFIG}/${CONFIG_CORE}"
3707 sed --silent -e '/TEXT_DEFAULT_CONFIG$/,/^TEXT_DEFAULT_CONFIG/p' "$0" |
3708 sed -e '/TEXT_DEFAULT_CONFIG/d' |
3709 sed -e "s|@HOME@|${HOME}|" -e "s/@VERSION@/${VERSION}/" -e "s/@SERVERLIST@/${CONFIG_SERVERLIST}/"> "${DIR_CONFIG}"/"${CONFIG_CORE}"
3710 EXITSTATUS=$?
3711 if (( EXITSTATUS != 0 )); then
3712 printf '%-30s %s' "Error:" "Failed to create \"${DIR_CONFIG}/${CONFIG_CORE}\""
3713 CleanupAndExit 1
3714 fi
3715 INSTALL_SESSION=1
3716 fi
3717
3718 # }}}
3719 # ------------------------------------------------------------------------------------------------------------------------------
3720 # CONFIG TEST PART 3 of 4: Test if configuration file was created by a version that supports all required items and formats. {{{
3721
3722 if ! grep -F "Podget configuration file created by version" "${DIR_CONFIG}"/"${CONFIG_CORE}" >/dev/null ; then
3723 echo "${DIR_CONFIG}/${CONFIG_CORE} cannot be verified to be compatible with this version of podget."
3724 echo
3725 echo "It is missing the version line that is included in configuration files created by newer versions of podget."
3726 echo
3727 echo "Please create a new configuration file by running 'podget --create-config <FILENAME>',"
3728 echo "and then converting your old configuration to the new format. Then move the new file"
3729 echo "in place of the old and podget will work as it used to."
3730 CleanupAndExit 1
3731 else
3732 # get version
3733 VERSION=$(grep -F "Podget configuration file created by version" "${DIR_CONFIG}"/"${CONFIG_CORE}" | \
3734 sed -e 's/.*by version \([0-9.]\)/\1/')
3735
3736 # Split version string into an array by replacing '.' with 'space'
3737 IFS='.' read -r -a VERSION_ARRAY <<< "${VERSION}"
3738
3739 # Assign values from array to named variables with a default of '0' if unset.
3740 # NOTE: BASE is currently commented out because it is currently unused. It is here if we need it.
3741 local BASE="${VERSION_ARRAY[0]:-0}"
3742 local MAJOR="${VERSION_ARRAY[1]:-0}"
3743 local MINOR="${VERSION_ARRAY[2]:-0}"
3744
3745 __MSG_DEBUG "PODGETRC Version Check: (looking for newer than 0.6.18)"
3746 __MSG_DEBUG " BASE: ${BASE:-0}"
3747 __MSG_DEBUG " MAJOR: ${MAJOR}"
3748 __MSG_DEBUG " MINOR: ${MINOR}"
3749
3750 # Version 0.6.18 was the last version before 0.7.0, so this check should catch any of it's configuration files.
3751 if (( (BASE < 1) && (MAJOR < 7) && (MINOR < 19) )); then
3752 echo "${DIR_CONFIG}/${CONFIG_CORE} was created by an older version of podget than is needed by this version."
3753 echo
3754 echo "This version of podget requires a configuration produced for version 0.7.0 or newer. This configuration"
3755 echo "was produced by version ${VERSION}"
3756 echo
3757 echo "Please update your configuration by creating a new one with the command 'podget --create-config <FILENAME>'"
3758 echo "and then comparing its contents to your old configuration. Once the new file has been updated to reflect"
3759 echo "your desired configuration, move it in place of the old one."
3760 CleanupAndExit 1
3761 fi
3762
3763 unset -v BASE
3764 unset -v MAJOR
3765 unset -v MINOR
3766 fi
3767
3768 # }}}
3769 # ------------------------------------------------------------------------------------------------------------------------------
3770 # Read core configuration options {{{
3771
3772 # SHELLCHECK SC1090
3773 # shellcheck source=/dev/null
3774 source "${DIR_CONFIG}"/"${CONFIG_CORE}"
3775
3776 # Config adjustment: Restore serverlist setting from command line if necessary
3777 if [[ -n ${CMDL_SERVERLIST+set} ]]; then
3778 if (( VERBOSITY >= 1 )) ; then
3779 echo "Serverlist set on command line, overriding value from configuration file."
3780 fi
3781 CONFIG_SERVERLIST=${CMDL_SERVERLIST}
3782 fi
3783
3784 # }}}
3785 # ------------------------------------------------------------------------------------------------------------------------------
3786 # CONFIG TEST PART 4 of 4: Test for existing DIR_SERVERLIST, if missing create it. {{{
3787
3788 # Note: This test needs to happen after CONFIG_CORE has been read, as it may specify a different serverlist name than the
3789 # default.
3790
3791 if [[ ! -f "${DIR_CONFIG}/${CONFIG_SERVERLIST}" ]] ; then
3792 echo " Installing default server list configuration."
3793 sed --silent -e '/TEXT_DEFAULT_SERVERLIST$/,/^TEXT_DEFAULT_SERVERLIST/p' "$0" |
3794 sed -e '/TEXT_DEFAULT_SERVERLIST/d' > "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"
3795 EXITSTATUS=$?
3796 if (( EXITSTATUS != 0 )); then
3797 echo " Failed to install \"${DIR_CONFIG}/${CONFIG_SERVERLIST}\""
3798 CleanupAndExit 1
3799 fi
3800 INSTALL_SESSION=1
3801 fi
3802
3803 # }}}
3804 # ------------------------------------------------------------------------------------------------------------------------------
3805 # Exit if set to --create-config {{{
3806
3807 if [[ -n ${CMDL_CREATECONFIG+set} ]]; then
3808 if (( CMDL_CREATECONFIG == 1 )); then
3809 CleanupAndExit 0
3810 fi
3811 fi
3812
3813 # }}}
3814 # ------------------------------------------------------------------------------------------------------------------------------
3815 # Configuration adjustments for command line options {{{
3816
3817 if [[ -n ${CMDL_NOPLAYLIST+set} ]]; then
3818 if (( VERBOSITY >= 1 )) ; then
3819 printf '\t\t%s\n' "NO PLAYLIST set on command line, overriding value from configuration file."
3820 fi
3821 NO_PLAYLIST=${CMDL_NOPLAYLIST}
3822 fi
3823
3824 if (( INSTALL_SESSION > 0 )); then
3825 echo " Downloading a single item from each default server to test configuration."
3826 echo
3827 MOST_RECENT=1
3828 VERBOSITY=3
3829 fi
3830
3831 if [[ -n ${CMDL_LIBRARY+set} ]] ; then
3832 if [[ ${CMDL_LIBRARY} == "NONE" ]]; then
3833 echo "Unset directory to store podcast library"
3834 CleanupAndExit 1
3835 fi
3836 if (( VERBOSITY >= 3 )) ; then
3837 printf '\t\t%s\n' "Overriding Library Directory specified in configuration file."
3838 fi
3839 DIR_LIBRARY=${CMDL_LIBRARY}
3840 fi
3841
3842 __MSG_INFO "Library Directory" "${DIR_LIBRARY}"
3843
3844 if [[ -z ${DIR_LIBRARY} ]] ; then
3845 echo "ERROR - Library directory not defined." 1>&2
3846 CleanupAndExit ${ERR_LIBNOTDEF}
3847 else
3848 DirectoryCheck DIR_LIBRARY
3849 fi
3850
3851 if [[ -n ${CMDL_SESSION+set} ]] ; then
3852 if [[ ${CMDL_SESSION} == "NONE" ]]; then
3853 echo "Unset directory to store session files."
3854 CleanupAndExit 1
3855 fi
3856 DIR_SESSION=${CMDL_SESSION}
3857 fi
3858
3859 # Added so old configuration files (that were created before this option was added) still work.
3860 if [[ -z ${DIR_SESSION+set} ]] ; then
3861 if [[ -n ${TMPDIR+set} ]]; then
3862 DIR_SESSION=${TMPDIR}/podget
3863 else
3864 DIR_SESSION=/tmp/podget
3865 fi
3866 fi
3867
3868 if [[ -n ${DIR_SESSION+set} ]]; then
3869 DirectoryCheck DIR_SESSION
3870 fi
3871
3872 __MSG_INFO "Session Directory" "${DIR_SESSION}"
3873
3874 if [[ -n ${CMDL_CLEANUP_DAYS+set} ]] ; then
3875 if [[ -z ${CMDL_CLEANUP_DAYS##*[!0-9]*} ]]; then
3876 echo "Cleanup Days is not a positive integer value"
3877 CleanupAndExit 1
3878 fi
3879 if (( CMDL_CLEANUP_DAYS >= 0 )); then
3880 CLEANUP_DAYS=${CMDL_CLEANUP_DAYS}
3881 fi
3882 fi
3883
3884 if [[ -n ${CMDL_CLEANUP_SIMULATE} ]] ; then
3885 CLEANUP_SIMULATE=${CMDL_CLEANUP_SIMULATE}
3886 fi
3887
3888 if [[ -z ${DIR_LOG+set} ]] ; then
3889 DIR_LOG=${DIR_LIBRARY}/.LOG
3890 fi
3891
3892 DirectoryCheck DIR_LOG
3893
3894 __MSG_INFO "Log Directory" "${DIR_LOG}"
3895
3896 if [[ -n ${CMDL_ASX+set} ]]; then
3897 ASX_PLAYLIST=${CMDL_ASX}
3898 fi
3899
3900 if [[ -n ${CMDL_PLAYLISTPERPODCAST+set} ]]; then
3901 PLAYLIST_PERPODCAST=1
3902 fi
3903
3904 if (( CMDL_FORCE != 0 )); then
3905 FORCE=${CMDL_FORCE}
3906 WGET_BASEOPTS="${WGET_BASEOPTS/-c /}"
3907 fi
3908
3909 if [[ -n ${CMDL_MOSTRECENT+set} ]] ; then
3910 if [[ -z ${CMDL_MOSTRECENT##*[!0-9]*} ]]; then
3911 echo
3912 echo "Recent is not a positive integer value"
3913 CleanupAndExit 1
3914 fi
3915 if (( CMDL_MOSTRECENT != 0 )); then
3916 MOST_RECENT=${CMDL_MOSTRECENT}
3917 fi
3918 fi
3919
3920 if (( VERBOSITY <= 1 )) ; then
3921 WGET_COMMON_OPTIONS="-q ${WGET_BASEOPTS}"
3922 elif (( VERBOSITY == 2 )) ; then
3923 WGET_COMMON_OPTIONS="-nv ${WGET_BASEOPTS}"
3924 elif (( VERBOSITY == 3 )) ; then
3925 WGET_COMMON_OPTIONS="${WGET_BASEOPTS} --progress=dot:mega"
3926 else
3927 WGET_COMMON_OPTIONS="${WGET_BASEOPTS} --progress=bar"
3928 fi
3929
3930 # Remove any residual leading spaces from WGET_COMMON_OPTIONS
3931 WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS#[ ]*}"
3932
3933 __MSG_DEBUG "WGET COMMON OPTIONS" "${WGET_COMMON_OPTIONS}"
3934
3935 if [[ -n ${FILENAME_BADCHARS+set} ]] ; then
3936 # make sure backslash is escaped.
3937 FILENAME_BADCHARS="${FILENAME_BADCHARS/\\/\\\\}"
3938
3939 __MSG_DEBUG "Filename Bad Characters" "${FILENAME_BADCHARS}"
3940 __MSG_DEBUG "Filename Replace Character" "${FILENAME_REPLACECHAR}"
3941 fi
3942
3943 if (( DEBUG == 0 )); then
3944 __MSG_INFO "Debug Disabled" "Delete temp files and reduced progress messages."
3945 else
3946 __MSG_DEBUG "Debug Enabled" "Do not delete temp files and increased progress messages."
3947 fi
3948
3949 if (( VERBOSITY >= 1 )) ; then
3950 echo
3951 fi
3952
3953 # }}}
3954 # ------------------------------------------------------------------------------------------------------------------------------
3955 # Test for another session. {{{
3956 # Moved below the configuration reading so that the DIR_SESSION could be configurable.
3957
3958 # Test that session directory exists (useful when placed on a tmpfs filesystem).
3959 if [[ ! -d ${DIR_SESSION} ]]; then
3960 __MSG_INFO "Session directory not found, creating"
3961 mkdir -p "${DIR_SESSION}"
3962 fi
3963
3964 # The cleanup portion of the following procedure may be less needed because we have gotten a lot more complete in our cleanup
3965 # procedures with traps that mean that the session file should be deleted whenever the session exits (whether good or
3966 # bad). This procedures main purpose is to prevent concurrent sessions for running on the same configuration file.
3967
3968 TEST_SESSION=0
3969 while read -r -d $'\0' FILE ; do
3970 if [[ $(stat -c %u "${FILE}") == "${UID}" ]]; then
3971 __MSG_DEBUG "Session FILE found: ${FILE} (that my user owns)"
3972 TEST_SESSION=1
3973 # shellcheck disable=SC2094
3974 while read -r LINE ; do
3975 if [[ "${LINE}" =~ ^[Cc]onfig[[:space:]][Ff]ile:.* ]]; then
3976 TEST_File=$(echo "${LINE}" | sed -n -e 's/^[^:]\+:\s\(.*\)$/\1/p')
3977 if [[ ${TEST_File} == "${CONFIG_CORE}" ]] ; then
3978 SESSION_PID=$(echo "${FILE}" | sed -n -e 's/.*podget.\([0-9]*\)$/\1/p')
3979 __MSG_DEBUG "Testing PID ${SESSION_PID} to determine if its still running."
3980
3981 if ps --pid "${SESSION_PID}" &>/dev/null; then
3982 echo "Another session with config file ${CONFIG_CORE} found running. Killing session." 1>&2
3983 CleanupAndExit ${ERR_RUNNINGSESSION}
3984 else
3985 __MSG_DEBUG "Session PID ${SESSION_PID} is not running, removing lock file"
3986 rm -f "${FILE}"
3987 fi
3988 fi
3989 fi
3990 done < "${FILE}"
3991 fi
3992 done < <(find "${DIR_SESSION}" -maxdepth 1 -type f -name "podget.[0-9]*" -print0)
3993
3994 if (( DEBUG > 1 )); then echo; fi
3995 if (( TEST_SESSION > 0 )) ; then
3996 __MSG_INFO "Old Session file(s) found and removed. Creating new one."
3997 else
3998 __MSG_INFO "Session file not found. Creating podget.$$"
3999 fi
4000
4001 # Set session file. Stores the configuration file used so that multiple sessions can be run per user simultaneously as
4002 # long as they each have different configuration files.
4003 # An example would be two sessions running as:
4004 # podget -c podgetrc.1
4005 # podget -c podgetrc.2
4006 echo -e "Config file: ${CONFIG_CORE}" > "${DIR_SESSION}"/podget.$$
4007
4008 # }}}
4009 # ------------------------------------------------------------------------------------------------------------------------------
4010 # Loop over servers on list {{{
4011
4012 if (( CLEANUP_ONLY == 0 )) && [[ -z ${IMPORT_OPML+set} && -z ${EXPORT_OPML+set} && -z ${IMPORT_PCAST+set} ]] ; then
4013 PodgetServerLoop
4014 fi
4015
4016 # }}}
4017 # ------------------------------------------------------------------------------------------------------------------------------
4018 # Removal of downloaded files older than CLEANUP_DAYS {{{
4019
4020 if [[ -z ${IMPORT_OPML+set} && -z ${EXPORT_OPML+set} && -z ${IMPORT_PCAST+set} ]] ; then
4021 if (( CLEANUP != 0 || CLEANUP_ONLY != 0 )) ; then
4022 PodgetCleanup
4023 fi
4024 fi
4025
4026 # }}}
4027 # ------------------------------------------------------------------------------------------------------------------------------
4028 # Build individual Podcast Full Playlists {{{
4029
4030 # Placed here so it is run after any session whether it includes cleanup or not. Does not run before importing or exporting
4031 # OPML or PCAST feed lists.
4032
4033 if [[ -z ${IMPORT_OPML+set} && -z ${EXPORT_OPML+set} && -z ${IMPORT_PCAST+set} ]] ; then
4034 PodgetBuildFeedPlaylist
4035 fi
4036
4037 # }}}
4038 # ------------------------------------------------------------------------------------------------------------------------------
4039 # OPML import loop: {{{
4040
4041 if [[ -n ${IMPORT_OPML+set} ]]; then
4042 PodgetImportOPML "${IMPORT_OPML}"
4043 fi
4044
4045 # }}}
4046 # ------------------------------------------------------------------------------------------------------------------------------
4047 # OPML export loop: {{{
4048
4049 if [[ -n ${EXPORT_OPML+set} ]]; then
4050 PodgetExportOPML "${EXPORT_OPML}"
4051 fi
4052
4053 # }}}
4054 # ------------------------------------------------------------------------------------------------------------------------------
4055 # PCAST import: {{{
4056
4057 if [[ -n ${IMPORT_PCAST+set} ]] ; then
4058 PodgetImportPCAST "${IMPORT_PCAST}"
4059 fi
4060
4061
4062 # }}}
4063 # ------------------------------------------------------------------------------------------------------------------------------
4064
4065 return 0
4066 }
4067
4068 # Call main function to run this whole kit and caboodle.
4069 PodgetCore "${@}"
4070
4071 # }}}
4072 # ----------------------------------------------------------------------------------------------------------------------------------
4073 # Close session with '0' status and clean up: {{{
4074
4075 __MSG_DEBUG "============================================================"
4076 __MSG_INFO "Closing session with '0' status and cleanup"
4077
4078 # Disable extended glob matches.
4079 shopt -u extglob
4080
4081 CleanupAndExit 0
4082
4083 # }}}
4084 # ----------------------------------------------------------------------------------------------------------------------------------
4085 # Notes: {{{
4086 #
4087 # 1. In version 1.0.0, we begin an experiment with limiting variable scope with functions and local declarations. The default way
4088 # Bash implements this works well for most cases, however we ran into a small issue that a variable would have near global status
4089 # within any function (child) called from the function (parent) it was declared local in. Not generally an issue but it could
4090 # make tracking down where a variable change happened a bit more difficult. To address this issue, it was discovered that within
4091 # a child function when we declared a variable local read-only we could also assign it the value of a variable of the same name
4092 # from the parent function. This allowed us to pass the value and name of the variable to the child function in a way that
4093 # effectively limited the scope of where the variable could be changed while still allowing us to use variables of the same name.
4094 #
4095 # For example, in the function PodgetBuildFeedPlaylist() we have the following declaration:
4096 # local -r DIR_CONFIG="${DIR_CONFIG}"
4097 # This creates a local read-only variable named DIR_CONFIG and inherits its setting from a variable of the same name that was set
4098 # within the PodgetCore parent function before it called the child function. The syntax might look a little redundant because
4099 # the local variable has the same name as the global but it works and Shellcheck does not complain.
4100 #
4101 # Declaring the variable local provides the protection from altering it that we want, while declaring it read-only causes an
4102 # error if we ever mistakenly do so we know where to fix it. In some cases, this may mean not protecting the variable and
4103 # allowing it to be changed.
4104 #
4105 # }}}
4106 # ----------------------------------------------------------------------------------------------------------------------------------
4107 # vim:tw=132:ts=4:sw=4:foldmethod=marker