-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplex-dlp-mirror.bash
executable file
·5682 lines (5267 loc) · 261 KB
/
plex-dlp-mirror.bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#############################
## Issues ##
#############################
# If you experience any issues, please let me know here:
# https://github.com/goose-ws/bash-scripts
# These scripts are purely a passion project of convenience for myself, so pull requests welcome :)
#############################
## About ##
#############################
# This script can mirror a media source in a Plex TV series compatible style.
# While it is not the first script to offering media mirroring/downloading, I have yet to find one
# that can do so in the format of a TV series. The only choice was to treat each media item as a movie,
# which is not productive to the way I want to consume media. So I made this, instead.
# It also can mirror media in audio-only format; however, each song will be its own album.
#############################
## Changelog ##
#############################
# 2025-01-05
# Removed YT key rotations, as that breaks their TOS
# Added Discord notifications
# Added private Playlist functionality, but still need to fix sorting
# 2024-12-23
# Functional, I think
# 2024-11-18
# Mostly a total rewrite. Still need to bang out collection/playlist functionality, but seems to be
# working well otherwise.
# 2024-07-29
# Initial commit, script is in 'alpha' testing at this point
#############################
## Installation ##
#############################
# 1. Download the script .bash file somewhere safe
# 2. Download the script .env file somewhere safe
# 3. Set up your Videos folder in Plex:
# - On your Plex Media Server, do "Add a library"
# - Select your library type: TV Shows
# - Add folders: Path to your ${outputDir}
# - Advanced > Scanner: Plex Series Scanner
# - Advanced > Agent: Personal Media Shows
# * You probably also want to disable Intro/Credit detection, and Ad Detection
# 4. Edit the .env file to your liking
# 5. Create a video config directory
# So if you name the script "plex-dlp-mirror.bash"
# Then in the same folder you would create the directory "plex-dlp-mirror.sources"
# And within that directory, you would place a "source.env" file for each source
# you want to add. The files can be named anything, as long as they end in ".env"
# Here is an example source.env: https://github.com/goose-ws/bash-scripts/blob/testing/plex-dlp-mirror.env.example
# 6. Set the script to run via cron on whatever your time preference is
#############################
## Sanity checks ##
#############################
if ! [ -e "/bin/bash" ]; then
echo "This script requires Bash"
exit 255
fi
if [[ -z "${BASH_VERSINFO[0]}" || "${BASH_VERSINFO[0]}" -lt "4" ]]; then
echo "This script requires Bash version 4 or greater"
exit 255
fi
# Dependency check
depsArr=("awk" "basename" "chmod" "cmp" "column" "convert" "curl" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "date" "docker" "ffmpeg" "find" "grep" "identify" "mkdir" "mktemp" "mv" "printf" "realpath" "shuf" "sort" "sqlite3" "sqlite3" "xxd" "yq" "yt-dlp")
depFail="0"
for i in "${depsArr[@]}"; do
if [[ "${i:0:1}" == "/" ]]; then
if ! [[ -e "${i}" ]]; then
echo "Missing dependency [${i}]"
depFail="1"
fi
else
if ! command -v "${i}" > /dev/null 2>&1; then
echo "Missing dependency [${i}]"
depFail="1"
fi
fi
done
if [[ "${depFail}" -eq "1" ]]; then
echo "Dependency check failed"
exit 255
fi
# Local variables
realPath="$(realpath "${0}")"
scriptName="$(basename "${0}")"
lockFile="${realPath%/*}/.${scriptName}.lock"
# URL of where the most updated version of the script is
updateURL="https://raw.githubusercontent.com/goose-ws/bash-scripts/main/plex-dlp-mirror.bash"
# For ease of printing messages
lineBreak=$'\n\n'
scriptStart="$(($(date +%s%N)/1000000))"
#############################
## Lockfile ##
#############################
if [[ -e "${lockFile}" ]]; then
if kill -s 0 "$(<"${lockFile}")" > /dev/null 2>&1; then
# We only need to print the lockfile warning if we're not being spawned by cron
if [[ -t 1 ]]; then
echo "Lockfile present [PID $(<"${lockFile}")], refusing to run"
fi
exit 0
else
echo "Removing stale lockfile for PID $(<"${lockFile}")"
fi
fi
echo "${$}" > "${lockFile}"
#############################
## Standard Functions ##
#############################
function printOutput {
case "${1}" in
0) logLevel="[reqrd]";; # Required
1) logLevel="[error]";; # Errors
2) logLevel="[warn] ";; # Warnings
3) logLevel="[info] ";; # Informational
4) logLevel="[verb] ";; # Verbose
5) logLevel="[DEBUG]";; # Super Secret Debug Mode
esac
if [[ "${1}" -le "${outputVerbosity}" ]]; then
echo "${0##*/} :: $(date "+%Y-%m-%d %H:%M:%S") :: ${logLevel} ${2}"
fi
if [[ "${1}" -le "1" ]]; then
errorArr+=("${2}")
fi
}
function removeLock {
if rm -f "${lockFile}"; then
if ! [[ "${1}" == "silent" ]]; then
printOutput "4" "Lockfile removed"
fi
else
printOutput "1" "Unable to remove lockfile"
fi
}
function badExit {
apiCount
if [[ -n "${tmpDir}" ]]; then
if ! rm -rf "${tmpDir}"; then
printOutput "1" "Failed to clean up tmp folder [${tmpDir}]"
fi
fi
removeLock
if [[ -z "${2}" ]]; then
printOutput "0" "Received signal: ${1}"
exit "255"
else
if [[ "${telegramErrorMessages,,}" =~ ^(yes|true)$ ]]; then
sendTelegramMessage "<b>${0##*/}</b>${lineBreak}${lineBreak}Error Code ${1}:${lineBreak}${2}" "${telegramErrorChannel}"
fi
printOutput "1" "${2} [Error code: ${1}]"
exit "1"
fi
}
function cleanExit {
if [[ "${1}" == "silent" ]]; then
rm -rf "${tmpDir}"
removeLock "silent"
else
apiCount
if [[ -n "${tmpDir}" ]]; then
if ! rm -rf "${tmpDir}"; then
printOutput "1" "Failed to clean up tmp folder [${tmpDir}]"
fi
fi
if [[ "${#errorArr[@]}" -ne "0" ]]; then
printOutput "1" "=== Error Log ==="
for i in "${errorArr[@]}"; do
printOutput "1" "${i}"
done
fi
printOutput "3" "Script executed in $(timeDiff "${scriptStart}")"
removeLock
fi
exit 0
}
function callCurlGet {
# URL to call should be ${1}
# Custom UA can be ${2}
# Will return the variable ${curlOutput}
if [[ -z "${1}" ]]; then
badExit "1" "No input URL provided for GET"
fi
if [[ -z "${2}" ]]; then
curlOutput="$(curl -skL -m 15 "${1}" 2>&1)"
else
curlOutput="$(curl -skL -m 15 -A "${2}" "${1}" 2>&1)"
fi
curlExitCode="${?}"
if [[ "${curlExitCode}" -eq "28" ]]; then
printOutput "2" "Curl timed out, waiting 10 seconds then trying again"
sleep 10
curlOutput="$(curl -skL "${1}" 2>&1)"
curlExitCode="${?}"
fi
if [[ "${curlExitCode}" -ne "0" ]]; then
printOutput "1" "Curl returned non-zero exit code ${curlExitCode}"
while read -r i; do
printOutput "1" "Output: ${i}"
done <<<"${curlOutput}"
badExit "2" "Bad curl output"
fi
}
function timeDiff {
# Start time should be passed as ${1}
# End time can be passed as ${2}
# If no end time is defined, will use the time the function is called as the end time
# Time should be provided via: startTime="$(($(date +%s%N)/1000000))"
if [[ -z "${1}" ]]; then
echo "No start time provided"
return 1
else
startTime="${1}"
fi
if [[ -z "${2}" ]]; then
endTime="$(($(date +%s%N)/1000000))"
fi
if [[ "$(( ${endTime:0:10} - ${startTime:0:10} ))" -le "5" ]]; then
printf "%sms\n" "$(( endTime - startTime ))"
else
local T="$(( ${endTime:0:10} - ${startTime:0:10} ))"
local D="$((T/60/60/24))"
local H="$((T/60/60%24))"
local M="$((T/60%60))"
local S="$((T%60))"
(( D > 0 )) && printf '%dd' "${D}"
(( H > 0 )) && printf '%dh' "${H}"
(( M > 0 )) && printf '%dm' "${M}"
(( D > 0 || H > 0 || M > 0 ))
printf '%ds\n' "${S}"
fi
}
function msToTime {
if [[ "${1}" -le "5" ]]; then
printf "%sms\n" "$(( endTime - startTime ))"
else
local T="$(( ${1} / 1000 ))"
local D="$((T/60/60/24))"
local H="$((T/60/60%24))"
local M="$((T/60%60))"
local S="$((T%60))"
(( D > 0 )) && printf '%dd' "${D}"
(( H > 0 )) && printf '%dh' "${H}"
(( M > 0 )) && printf '%dm' "${M}"
(( D > 0 || H > 0 || M > 0 ))
printf '%ds\n' "${S}"
fi
}
function sendTelegramMessage {
# Message to send should be passed as function positional parameter #1
# We can pass an "Admin channel" as positional parameter #2 for the case of sending error messages
callCurlGet "https://api.telegram.org/bot${telegramBotId}/getMe"
if ! [[ "$(yq -p json ".ok" <<<"${curlOutput}")" == "true" ]]; then
printOutput "1" "Telegram bot API check failed"
else
printOutput "4" "Telegram bot API key authenticated [$(yq -p json ".result.username" <<<"${curlOutput}")]"
for chanId in "${telegramChannelId[@]}"; do
if [[ -n "${2}" ]]; then
chanId="${2}"
fi
callCurlGet "https://api.telegram.org/bot${telegramBotId}/getChat?chat_id=${telegramChannelId}"
if [[ "$(yq -p json ".ok" <<<"${curlOutput}")" == "true" ]]; then
printOutput "4" "Telegram channel authenticated [$(yq -p json ".result.title" <<<"${curlOutput}")]"
msgEncoded="$(rawUrlEncode "${1}")"
callCurlGet "https://api.telegram.org/bot${telegramBotId}/sendMessage?chat_id=${chanId}&parse_mode=html&text=${msgEncoded}"
# Check to make sure Telegram returned a true value for ok
if ! [[ "$(yq -p json ".ok" <<<"${curlOutput}")" == "true" ]]; then
printOutput "1" "Failed to send Telegram message:"
printOutput "1" ""
while read -r i; do
printOutput "1" "${i}"
done < <(yq -p json "." <<<"${curlOutput}")
printOutput "1" ""
else
printOutput "4" "Telegram message sent successfully"
fi
else
printOutput "1" "Telegram channel check failed"
fi
if [[ -n "${2}" ]]; then
break
fi
done
fi
}
#############################
## Unique Functions ##
#############################
function getContainerIp {
if ! [[ "${1}" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.([0-9]{1,3}|[0-9]/[0-9]{1,2})$ ]]; then
# Container name should be passed as positional paramter #1
# It will return the variable ${containerIp} if successful
printOutput "3" "Attempting to automatically determine IP address for: ${1}"
if [[ "${1%%:*}" == "docker" ]]; then
unset containerNetworking
while read -r i; do
if [[ -n "${i}" ]]; then
containerNetworking+=("${i}")
fi
done < <(docker inspect -f '{{range $k, $v := .NetworkSettings.Networks}}{{println $k}}{{end}}' "${1#*:}")
if [[ "${#containerNetworking[@]}" -eq "0" ]]; then
printOutput "3" "No network type defined. Checking to see if networking is through another container."
containerIp="$(docker inspect "${1#*:}" | yq -p json ".[].HostConfig.NetworkMode")"
printOutput "3" "Host config network mode: ${containerIp}"
if [[ "${containerIp%%:*}" == "container" ]]; then
printOutput "3" "Networking routed through another container. Retrieving IP address."
containerIp="$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${containerIp#container:}")"
else
printOutput "1" "Unable to determine networking type"
unset containerIp
fi
else
printOutput "3" "Container is utilizing ${#containerNetworking[@]} network type(s): ${containerNetworking[*]}"
for i in "${containerNetworking[@]}"; do
if [[ "${i}" == "host" ]]; then
printOutput "3" "Networking type: ${i}"
containerIp="127.0.0.1"
else
printOutput "3" "Networking type: ${i}"
containerIp="$(docker inspect "${1#*:}" | yq -p json ".[] | .NetworkSettings.Networks.${i}.IPAddress")"
if [[ "${containerIp}" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.([0-9]{1,3}|[0-9]/[0-9]{1,2})$ ]]; then
break
fi
fi
done
fi
else
badExit "3" "Unknown container daemon: ${1%%:*}"
fi
else
containerIp="${1}"
fi
if [[ -z "${containerIp}" ]] || ! [[ "${containerIp}" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.([0-9]{1,3}|[0-9]/[0-9]{1,2})$ ]]; then
badExit "4" "Unable to determine IP address via networking mode: ${i}"
else
printOutput "3" "Container IP address: ${containerIp}"
fi
}
function sendTelegramImage {
# Message to send should be passed as function positional parameter #1
# Image path should be passed as funcion positonal parameter #2
callCurlGet "https://api.telegram.org/bot${telegramBotId}/getMe"
if ! [[ "$(yq -p json ".ok" <<<"${curlOutput}")" == "true" ]]; then
printOutput "1" "Telegram bot API check failed"
else
printOutput "4" "Telegram bot API key authenticated [$(yq -p json ".result.username" <<<"${curlOutput}")]"
for chanId in "${telegramChannelId[@]}"; do
callCurlGet "https://api.telegram.org/bot${telegramBotId}/getChat?chat_id=${telegramChannelId}"
if [[ "$(yq -p json ".ok" <<<"${curlOutput}")" == "true" ]]; then
printOutput "4" "Telegram channel authenticated [$(yq -p json ".result.title" <<<"${curlOutput}")]"
callCurlPost "tgimage" "https://api.telegram.org/bot${telegramBotId}/sendPhoto" "${chanId}" "${1}" "${2}"
# Check to make sure Telegram returned a true value for ok
if ! [[ "$(yq -p json ".ok" <<<"${curlOutput}")" == "true" ]]; then
printOutput "1" "Failed to send Telegram message:"
printOutput "1" ""
while read -r i; do
printOutput "1" "${i}"
done < <(yq -p json "." <<<"${curlOutput}")
printOutput "1" ""
else
printOutput "4" "Telegram message sent successfully"
fi
else
printOutput "1" "Telegram channel check failed"
fi
if [[ -n "${2}" ]]; then
break
fi
done
fi
}
function sendDiscordImage {
# Message to send should be passed as functional positional parameter #1
# Image path should be passed as functional positional parameter #2
if [[ -z "${discordWebhook}" ]]; then
printOutput "5" "No Discord Webhook URL provided, unable to send Discord message"
return 0
fi
# Make sure our message is not blank
if [[ -z "${1}" ]]; then
printOutput "1" "No message passed to send to Discord"
return 1
fi
# Make sure our image exists
if ! [[ -e "${2}" ]]; then
printOutput "1" "Image file [${2}] does not appear to exist"
return 1
fi
# Send it
# Positional parameter 2 is the URL
# Positional parameter 3 is the text
# Positional parameter 4 is the image
callCurlPost "discordimage" "${discordWebhook}" "${1}" "${2}"
}
function apiCount {
# Notify of how many API calls were made
if [[ "${apiCallsYouTube}" -ne "0" ]]; then
printOutput "4" "Made [${apiCallsYouTube}] API calls to YouTube"
printOutput "4" "Costed [${totalUnits}] units in total | [${totalVideoUnits}] video | [${totalCaptionsUnits}] captions | [${totalChannelsUnits}] channels | [${totalPlaylistsUnits}] playlists"
fi
if [[ "${apiCallsSponsor}" -ne "0" ]]; then
printOutput "4" "Made [${apiCallsSponsor}] API calls to SponsorBlock"
fi
}
function rawUrlEncode {
local string="${1}"
local strlen="${#string}"
local encoded=() # Declare encoded as an array
local pos c o
for (( pos=0 ; pos<strlen ; pos++ )); do
c="${string:$pos:1}"
if [[ "$c" =~ [[:ascii:]] ]]; then
case "${c}" in
[-_.~a-zA-Z0-9] ) o="${c}" ;;
* ) printf -v o '%%%02x' "'${c}" ;;
esac
else
o=$(echo -n "$c" | xxd -p -c1 | while read -r line; do echo -n "%${line}"; done)
fi
encoded+=("${o}") # Add the encoded character to the array
done
printf "%s" "${encoded[@]}"
}
function sqDb {
# Log the command we're executing to the database, for development purposes
# Execute the command
if sqOutput="$(sqlite3 "${sqliteDb}" "${1}" 2>&1)"; then
if [[ -n "${sqOutput}" ]]; then
echo "${sqOutput}"
fi
else
sqlite3 "${sqliteDb}" "INSERT INTO db_log (TIME, COMMAND, RESULT, OUTPUT) VALUES ('$(date)', '${1//\'/\'\'}', 'Failure', '${sqOutput//\'/\'\'}');"
if [[ -n "${sqOutput}" ]]; then
echo "${sqOutput}"
fi
return 1
fi
}
function randomSleep {
# ${1} is minumum seconds, ${2} is maximum
# If no min/max set, min=5 max=30
if [[ -z "${1}" ]]; then
sleepTime="$(shuf -i 5-30 -n 1)"
else
sleepTime="$(shuf -i "${1}"-"${2}" -n 1)"
fi
printOutput "4" "Pausing for ${sleepTime} seconds before continuing"
sleep "${sleepTime}"
}
function printAngryWarning {
printOutput "2" " __ __ _ _ "
printOutput "2" " \ \ / / (_) | |"
printOutput "2" " \ \ /\ / /_ _ _ __ _ __ _ _ __ __ _| |"
printOutput "2" " \ \/ \/ / _\` | '__| '_ \| | '_ \ / _\` | |"
printOutput "2" " \ /\ / (_| | | | | | | | | | | (_| |_|"
printOutput "2" " \/ \/ \__,_|_| |_| |_|_|_| |_|\__, (_)"
printOutput "2" " __/ | "
printOutput "2" " |___/ "
}
function throttleDlp {
if ! [[ "${throttleMin}" -eq "0" && "${throttleMax}" -eq "0" ]]; then
printOutput "4" "Throttling after yt-dlp download call"
randomSleep "${throttleMin}" "${throttleMax}"
fi
}
## Curl functions
function callCurlPost {
# URL to call should be ${1}
if [[ -z "${1}" ]]; then
printOutput "1" "No input URL provided for POST"
return 1
fi
# ${2} could be --data-binary and ${3} could be an image to be uploaded
if [[ "${2}" == "--data-binary" ]]; then
printOutput "5" "Issuing curl command [curl -skL -X POST \"${1}\" --data-binary \"${3}\"]"
curlOutput="$(curl -skL -X POST "${1}" --data-binary "${3}" 2>&1)"
elif [[ "${1}" == "tgimage" ]]; then
# We're sending an image to telegram
# Positional parameter 2 is the URL
# Positional parameter 3 is the chat ID
# Positional parameter 4 is the caption
# Positional parameter 5 is the image
printOutput "5" "Issuing curl command [curl -skL -X POST \"${2}?chat_id=${3}&parse_mode=html&caption=$(rawUrlEncode "${4}")\" -F \"photo=@\"${5}\"\"]"
curlOutput="$(curl -skL -X POST "${2}?chat_id=${3}&parse_mode=html&caption=$(rawUrlEncode "${4}")" -F "photo=@\"${5}\"" 2>&1)"
elif [[ "${1}" == "discordimage" ]]; then
# We're sending an image to discord
# Positional parameter 2 is the URL
# Positional parameter 3 is the text
# Positional parameter 4 is the image
printOutput "5" "Issuing curl command [curl -skL -H \"Accept: application/json\" -H \"Content-Type: multipart/form-data\" -F \"file=@\\\"${4}\\\"\" -F \"payload_json={\\\"content\\\": \\\"${3//$'\n'/\\n}\\\"}\" -X POST \"${2}\"]"
curlOutput="$(curl -skL -H "Accept: application/json" -H "Content-Type: multipart/form-data" -F "file=@\"${4}\"" -F "payload_json={\"content\": \"${3//$'\n'/\\n}\"}" -X POST "${2}")"
else
printOutput "5" "Issuing curl command [curl -skL -X POST \"${1}\"]"
curlOutput="$(curl -skL -X POST "${1}" 2>&1)"
fi
curlExitCode="${?}"
if [[ "${curlExitCode}" -ne "0" ]]; then
printOutput "1" "Curl returned non-zero exit code ${curlExitCode}"
while read -r i; do
printOutput "1" "Output: ${i}"
done <<<"${curlOutput}"
return 1
fi
}
function callCurlDownload {
# URL to call should be $1, output should be $2
if [[ -z "${1}" ]]; then
badExit "5" "No input URL provided for download"
elif [[ -z "${2}" ]]; then
badExit "6" "No output path provided for download"
fi
printOutput "5" "Issuing curl command [curl -skL -m 15 \"${1}\" -o \"${2}\"]"
curlOutput="$(curl -skL -m 15 "${1}" -o "${2}" 2>&1)"
curlExitCode="${?}"
if [[ "${curlExitCode}" -eq "28" ]]; then
printOutput "2" "Curl download call returned exit code 28 -- Waiting 5 seconds and reattempting download"
sleep 5
curlOutput="$(curl -skL -m 15 "${1}" -o "${2}" 2>&1)"
curlExitCode="${?}"
fi
if [[ "${curlExitCode}" -ne "0" ]]; then
printOutput "1" "Curl download call returned non-zero exit code ${curlExitCode}"
while read -r i; do
printOutput "1" "Output: ${i}"
done <<<"${curlOutput}"
badExit "7" "Bad curl output"
fi
}
function callCurlPut {
# URL to call should be $1
if [[ -z "${1}" ]]; then
badExit "8" "No input URL provided for PUT"
fi
printOutput "5" "Issuing curl command [curl -skL -X PUT \"${1}\"]"
curlOutput="$(curl -skL -X PUT "${1}" 2>&1)"
curlExitCode="${?}"
if [[ "${curlExitCode}" -ne "0" ]]; then
printOutput "1" "Curl returned non-zero exit code ${curlExitCode}"
while read -r i; do
printOutput "1" "Output: ${i}"
done <<<"${curlOutput}"
return 1
fi
}
function callCurlDelete {
# URL to call should be $1
if [[ -z "${1}" ]]; then
badExit "9" "No input URL provided for DELETE"
fi
printOutput "5" "Issuing curl command [curl -skL -X DELETE \"${1}\"]"
curlOutput="$(curl -skL -X DELETE "${1}" 2>&1)"
curlExitCode="${?}"
if [[ "${curlExitCode}" -ne "0" ]]; then
printOutput "1" "Curl returned non-zero exit code ${curlExitCode}"
while read -r i; do
printOutput "1" "Output: ${i}"
done <<<"${curlOutput}"
badExit "10" "Bad curl output"
fi
}
## Indexing functions
function ytIdToDb {
unset dbCount vidTitle vidTitleClean channelId uploadDate epochDate uploadYear vidDesc vidType vidStatus vidError sponsorCurl
# Get the video info
# Because we can't get the time string through yt-dlp, there's no point in trying to use it as our fake API here, we *have* to API query YouTube
# There is a possibility that we only need to query the SponsorBlock API, if this video is just being checkd for an upgrade
# If we're not skipping the video, and SponsorBlock is enabled, check for availability for our video
dbCount="$(sqDb "SELECT COUNT(1) FROM source_videos WHERE ID = '${1//\'/\'\'}';")"
if [[ "${dbCount}" -eq "1" ]]; then
vidStatus="$(sqDb "SELECT STATUS FROM source_videos WHERE ID = '${1//\'/\'\'}';")"
# If the video status is not skipped
if ! [[ "${vidStatus}" == "skipped" ]]; then
# And the video status is not import
if ! [[ "${vidStatus}" == "import" ]]; then
# And SponsorBlock is not disabled
if ! [[ "${sponsorblockEnable}" == "disable" ]]; then
# Get the SponsorBlock status of the video
sponsorApiCall "searchSegments?videoID=${1}"
sponsorCurl="${curlOutput}"
# If it is not found
if [[ "${sponsorCurl}" == "Not Found" ]]; then
printOutput "5" "No SponsorBlock data available for video"
sponsorblockAvailable="Not found [$(date)]"
# And we are required to have it for download
if [[ "${sponsorblockRequire}" == "true" ]]; then
# Skip the download the wait for a future run
vidStatus="sb_wait"
vidError="SponsorBlock data required, but not available"
else
# Check and see if we've already grabbed this video
dbVidStatus="$(sqDb "SELECT SB_AVAILABLE FROM source_videos WHERE ID = '${ytId//\'/\'\'}';")"
if [[ "${sponsorblockAvailable%% \[*}" == "Not found" ]]; then
# We've previously indexed this video, and SponsorBlock data was not available at that time.
# It's still not available, so we don't need to re-download this video.
printOutput "4" "Item has no updated SponsorBlock data -- Skipping"
return 0
fi
fi
else
# It was found
printOutput "5" "SponsorBlock data found for video"
sponsorblockAvailable="Found [$(date)]"
fi
fi
else
# The video is being imported
true
fi
else
# The video is marked as skipped. Is SponsorBlock enabled?
if [[ "${sponsorblockEnable}" == "true" ]]; then
# Yes. Get its data.
sponsorApiCall "searchSegments?videoID=${1}"
sponsorCurl="${curlOutput}"
# Is it required, or upgraded?
if [[ "${sponsorblockRequire}" == "true" ]]; then
# Required. Is it found?
if [[ "${sponsorCurl}" == "Not Found" ]]; then
# It was not found
printOutput "5" "No SponsorBlock data available for video ID [${1}]"
sponsorblockAvailable="Not found [$(date)]"
vidStatus="sb_wait"
vidError="SponsorBlock data required, but not available"
else
# It was found
printOutput "3" "SponsorBlock data found for video ID [${1}] -- Marking file for download"
sponsorblockAvailable="Found [$(date)]"
vidStatus="queued"
vidError="null"
fi
else
# It is not required. We technically shouldn't end up here.
# Queue the video either way, since it's not required
vidStatus="queued"
# Is the sponsorblock data found?
if [[ "${sponsorCurl}" == "Not Found" ]]; then
# It was not found
printOutput "5" "No SponsorBlock data available for video ID [${1}]"
sponsorblockAvailable="Not found [$(date)]"
else
# It was found
printOutput "3" "SponsorBlock data found for video ID [${1}] -- Marking file for download"
sponsorblockAvailable="Found [$(date)]"
vidError="null"
fi
fi
# Do our sqlite calls here
# Update the item's status
if sqDb "UPDATE source_videos SET STATUS = '${vidStatus//\'/\'\'}', UPDATED = '$(date +%s)' WHERE ID = '${1//\'/\'\'}';"; then
printOutput "5" "Updated SponsorBlock enable for video ID [${1}]"
else
printOutput "1" "Failed to update SponsorBlock enable for video ID [${1}]"
fi
# Update the error, if needed
if [[ -n "${vidError}" ]]; then
# If we have a "NULL", the null it
if [[ "${vidError,,}" == "null" ]]; then
if sqDb "UPDATE source_videos SET ERROR = null, UPDATED = '$(date +%s)' WHERE ID = '${1//\'/\'\'}';"; then
printOutput "5" "Removed error for video ID [${1}]"
else
printOutput "1" "Failed to remove error for video ID [${1}]"
fi
else
if sqDb "UPDATE source_videos SET ERROR = '${vidError//\'/\'\'}', UPDATED = '$(date +%s)' WHERE ID = '${1//\'/\'\'}';"; then
printOutput "5" "Updated error for video ID [${1}]"
else
printOutput "1" "Failed to update error for video ID [${1}]"
fi
fi
fi
# Update the SponsorBlock availability
if sqDb "UPDATE source_videos SET SB_AVAILABLE = '${sponsorblockAvailable//\'/\'\'}', UPDATED = '$(date +%s)' WHERE ID = '${1//\'/\'\'}';"; then
printOutput "5" "Updated SponsorBlock availability for video ID [${1}]"
else
printOutput "1" "Failed to update SponsorBlock availability for video ID [${1}]"
fi
fi
# Leave the function
return 0
fi
fi
# Query the YouTube API for the video info
printOutput "5" "Calling API for video info [${1}]"
ytApiCall "videos?id=${1}&part=snippet,liveStreamingDetails"
# Check to make sure we got a result
apiResults="$(yq -p json ".pageInfo.totalResults" <<<"${curlOutput}")"
# Validate it
if [[ -z "${apiResults}" ]]; then
printOutput "1" "No data provided to validate integer"
return 1
elif [[ "${apiResults}" =~ ^[0-9]+$ ]]; then
# Expected outcome
true
elif ! [[ "${apiResults}" =~ ^[0-9]+$ ]]; then
printOutput "1" "Data [${apiResults}] failed to validate as an integer"
return 1
else
badExit "11" "Impossible condition"
fi
if [[ "${apiResults}" -eq "0" ]]; then
printOutput "2" "API lookup for video ID [${1}] zero results (Is the video private?)"
if [[ -n "${cookieFile}" && -e "${cookieFile}" ]]; then
printOutput "3" "Re-attempting video ID [${1}] lookup via yt-dlp + cookie"
dlpApiCall="$(yt-dlp --no-warnings -J --cookies "${cookieFile}" "https://www.youtube.com/watch?v=${1}" 2>/dev/null)"
if [[ "$(yq -p json ".id" <<<"${dlpApiCall}")" == "${1}" ]]; then
# Yes, it's a private video we can auth via cookie
printOutput "3" "Lookup via cookie auth successful"
# Get the video title
vidTitle="$(yq -p json ".title" <<<"${dlpApiCall}")"
# Get the video description
# Blank if none set
vidDesc="$(yq -p json ".description" <<<"${dlpApiCall}")"
# Get the channel ID
channelId="$(yq -p json ".channel_id" <<<"${dlpApiCall}")"
# Get the channel name
chanName="$(yq -p json ".channel" <<<"${dlpApiCall}")"
## This is not provided by the yt-dlp payload. It cannot be looked up via the official API without oauth,
## which I do not want to implement for a number of reasons. Instead, I am going to get this via some very
## shameful code. Please do not read the below 2 lines, I am ashamed of them.
uploadDate="$(curl -b "${cookieFile}" -skL "https://www.youtube.com/watch?v=${1}")"
uploadDate="$(grep -E -o "<meta itemprop=\"datePublished\" content=\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}-[0-9]{2}:[0-9]{2}\">" <<<"${uploadDate}")"
## Ok I'm done, you can read it again.
uploadDate="${uploadDate%\">}"
uploadDate="${uploadDate##*\"}"
# Get the video type
vidType="$(yq -p json ".live_status" <<<"${dlpApiCall}")"
# We just need this to be a non-null value
broadcastStart="dlp"
# Get the maxres thumbnail URL
thumbUrl="$(yq -p json ".thumbnail" <<<"${dlpApiCall}")"
thumbUrl="${thumbUrl%\?*}"
else
printOutput "1" "Unable to preform lookup on video ID [${1}] via yt-dlp -- Skipping"
return 1
fi
else
printOutput "1" "Video ID [${1}] API lookup failed, and no cookie file provided to attempt to yt-dlp lookup -- Skipping"
return 1
fi
elif [[ "${apiResults}" -eq "1" ]]; then
# Get the video title
vidTitle="$(yq -p json ".items[0].snippet.title" <<<"${curlOutput}")"
# Get the video description
# Blank if none set
vidDesc="$(yq -p json ".items[0].snippet.description" <<<"${curlOutput}")"
# Get the channel ID
channelId="$(yq -p json ".items[0].snippet.channelId" <<<"${curlOutput}")"
# Get the channel name
chanName="$(yq -p json ".items[0].snippet.channelTitle" <<<"${curlOutput}")"
# Get the upload date
uploadDate="$(yq -p json ".items[0].snippet.publishedAt" <<<"${curlOutput}")"
# Get the video type (Check to see if it's a live broadcast)
vidType="$(yq -p json ".items[0].snippet.liveBroadcastContent" <<<"${curlOutput}")"
# Get the broadcast start time (Will only return value if it's a live broadcast)
broadcastStart="$(yq -p json ".items[0].liveStreamingDetails.actualStartTime" <<<"${curlOutput}")"
# Get the maxres thumbnail URL
thumbUrl="$(yq -p json ".items[0].snippet.thumbnails | to_entries | .[-1].value.url" <<<"${curlOutput}")"
else
badExit "12" "Impossible condition"
fi
# Now that we have the channel name, let's do a quick comparison to validate that it hasn't changed
verifyChannelName "${channelId}" "${chanName}"
# Get the video title
if [[ -z "${vidTitle}" ]]; then
printOutput "1" "Video title returned blank result [${vidTitle}]"
return 1
fi
printOutput "5" "Video title [${vidTitle}]"
# Get the clean video title
vidTitleClean="${vidTitle}"
# Trim any leading spaces and/or periods
while [[ "${vidTitleClean:0:1}" =~ ^( |\.)$ ]]; do
vidTitleClean="${vidTitleClean# }"
vidTitleClean="${vidTitleClean#\.}"
done
# Trim any trailing spaces and/or periods
while [[ "${vidTitleClean:$(( ${#vidTitleClean} - 1 )):1}" =~ ^( |\.)$ ]]; do
vidTitleClean="${vidTitleClean% }"
vidTitleClean="${vidTitleClean%\.}"
done
# Replace any forward or back slashes \ /
vidTitleClean="${vidTitleClean//\//_}"
# Replace any colons :
vidTitleClean="${vidTitleClean//\\/_}"
vidTitleClean="${vidTitleClean//:/}"
# Replace any stars *
vidTitleClean="${vidTitleClean//\*/}"
# Replace any question marks ?
vidTitleClean="${vidTitleClean//\?/}"
# Replace any quotation marks "
vidTitleClean="${vidTitleClean//\"/}"
# Replace any brackets < >
vidTitleClean="${vidTitleClean//</}"
vidTitleClean="${vidTitleClean//>/}"
# Replace any vertical bars |
vidTitleClean="${vidTitleClean//\|/}"
# Condense any instances of '_-_'
while [[ "${vidTitleClean}" =~ .*"_-_".* ]]; do
vidTitleClean="${vidTitleClean//_-_/ - }"
done
# Condense any multiple spaces
while [[ "${vidTitleClean}" =~ .*" ".* ]]; do
vidTitleClean="${vidTitleClean// / }"
done
if [[ -z "${vidTitleClean}" ]]; then
printOutput "1" "Clean video title returned blank result [${vidTitle}]"
return 1
fi
printOutput "5" "Clean video title [${vidTitleClean}]"
# Get the channel ID
if ! [[ "${channelId}" =~ ^[0-9A-Za-z_-]{23}[AQgw]$ ]]; then
printOutput "1" "Unable to validate channel ID [${channelId}]"
return 1
fi
printOutput "5" "Channel ID [${channelId}]"
# Get the upload timestamp
if [[ -z "${uploadDate}" ]]; then
printOutput "1" "Upload date lookup failed for video [${1}]"
return 1
fi
# Convert the date to a Unix timestamp
uploadEpoch="$(date --date="${uploadDate}" "+%s")"
if ! [[ "${uploadEpoch}" =~ ^[0-9]+$ ]]; then
printOutput "1" "Unable to convert upload date [${uploadDate}] to unix epoch timestamp [${uploadEpoch}]"
return 1
fi
printOutput "5" "Upload timestamp [${uploadEpoch}]"
# Get the upload year
uploadYear="${uploadDate:0:4}"
if ! [[ "${uploadYear}" =~ ^[0-9]+$ ]]; then
printOutput "1" "Unable to extrapolate upload year [${uploadYear}] from upload date [${uploadDate}]"
return 1
fi
printOutput "5" "Upload year [${uploadYear}]"
# Get the episode index number
# Update this after it's been added to the database (skip for now)
# Get the video description
if [[ "${vidDesc}" == " " ]]; then
unset vidDesc
fi
if [[ -z "${vidDesc}" ]]; then
printOutput "5" "No video description"
else
printOutput "5" "Video description present [${#vidDesc} characters]"
fi
# Get the video type (Regular / Short / Live)
if [[ -z "${vidType}" ]]; then
printOutput "1" "Video type lookup returned blank result [${vidType}]"
return 1
elif [[ "${vidType}" == "none" || "${vidType}" == "not_live" || "${vidType}" == "was_live" ]]; then
# Not currently live
# Check to see if it's a previous broadcast
if [[ -z "${broadcastStart}" ]]; then
# This should not be blank, it should be 'null' or a date/time
printOutput "1" "Broadcast start time lookup returned blank result [${broadcastStart}] -- Skipping"
return 1
elif [[ "${broadcastStart}" == "null" || "${vidType}" == "not_live" ]]; then
# It doesn't have one. Must be a short, or a regular video.
# Use our bullshit to find out
httpCode="$(curl -m 15 -s -I -o /dev/null -w "%{http_code}" "https://www.youtube.com/shorts/${1}")"
if [[ "${httpCode}" == "000" ]]; then
# We're being throttled
printOutput "2" "Throttling detected"
randomSleep "5" "15"
httpCode="$(curl -m 15 -s -I -o /dev/null -w "%{http_code}" "https://www.youtube.com/shorts/${1}")"
fi
if [[ -z "${httpCode}" ]]; then
printOutput "1" "Curl lookup to determine video type returned blank result [${httpCode}] -- Skipping"
return 1
elif [[ "${httpCode}" == "200" ]]; then
# It's a short
printOutput "4" "Determined video to be a short"
vidType="short"
elif [[ "${httpCode}" == "303" ]]; then
# It's a regular video
printOutput "4" "Determined video to be a standard video"
vidType="normal"
elif [[ "${httpCode}" == "404" ]]; then
# No such video exists
printOutput "1" "Curl lookup returned HTTP code 404 for video ID [${1}] -- Skipping"
return 1
else
printOutput "1" "Curl lookup to determine video ID [${1}] type returned unexpected result [${httpCode}] -- Skipping"
return 1
fi
elif [[ "${broadcastStart}" =~ ^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]Z$ || "${vidType}" == "was_live" ]]; then
printOutput "4" "Video ID [${1}] detected to be a past live broadcast"
vidType="waslive"
else
printOutput "Broadcast start time lookup returned unexpected result [${broadcastStart}] -- Skipping"
return 1
fi
elif [[ "${vidType}" == "live" || "${vidType}" == "is_live" || "${vidType}" == "upcoming" ]]; then
# Currently live
liveType="${vidType}"
printOutput "2" "Video ID [${1}] detected to be a live broadcast"
vidType="live"
else
printOutput "1" "Video ID [${1}] lookup video type returned invalid result [${vidType}] -- Skipping"
return 1
fi
printOutput "5" "Video type [${vidType}]"
# We have the video format option
# We have the include shorts option
# We have the include live option
# We have the mark watched option
# Determine our status (queued/skipped)
# In case we're doing this as an update, check and see if it's already logged
dbCount="$(sqDb "SELECT COUNT(1) FROM source_videos WHERE ID = '${1//\'/\'\'}';")"
if [[ "${dbCount}" -eq "0" ]]; then
if [[ "${2}" == "import" ]]; then
vidStatus="import"
# Using the error field as a cheap place to store where we need to move the file from
vidError="${3}"
else
vidStatus="queued"
if [[ "${vidType}" == "live" ]]; then
# Can't download a currently live video
vidStatus="waiting"
vidError="Video has live status [${liveType}] at time of indexing"
elif [[ "${vidType}" == "short" && "${includeShorts}" == "false" ]]; then
# Shorts aren't allowed
vidStatus="skipped"
vidError="Shorts not allowed per config"
elif [[ "${vidType}" == "waslive" ]]; then
if [[ "${includeLiveBroadcasts}" == "false" ]]; then
# Past live broadcasts aren't allowed
vidStatus="skipped"
vidError="Past live broadcasts not allowed per config"
elif [[ "${includeLiveBroadcasts}" == "true" ]]; then
# Past live broadcasts are allowed
vidError="null"
fi
fi
fi
elif [[ "${dbCount}" -eq "1" ]]; then
vidStatus="$(sqDb "SELECT STATUS FROM source_videos WHERE ID = '${1//\'/\'\'}';")"
if [[ "${vidStatus}" == "waiting" ]]; then
if [[ "${vidType}" == "waslive" ]]; then
if [[ "${includeLiveBroadcasts}" == "false" ]]; then
# Past live broadcasts aren't allowed
vidStatus="skipped"
vidError="Past live broadcasts not allowed per config"
elif [[ "${includeLiveBroadcasts}" == "true" ]]; then
# Past live broadcasts are allowed
vidStatus="queued"
vidError="null"
fi
fi
fi