-
Notifications
You must be signed in to change notification settings - Fork 38
/
live-dl
executable file
·1714 lines (1533 loc) · 58.8 KB
/
live-dl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# live-dl
# Download live streams from YouTube
#
# Tunghsiao Liu <t@sparanoid.com>
# Released under AGPL-3.0
#
#
# System reqirements
#
# - aria2c
# - bash
# - exiv2
# - ffmpeg
# - jq
# - streamlink
# - yt-dlp
# - yq (python-yq)
#
#
# Changelog
#
# See https://github.com/sparanoid/live-dl
#
#
# To-do list
#
# - [x] dependencies check
# - [x] convert output from .ts to .mp4
# - [x] youtube playlist support (not perfect when writing metadata)
# - [x] thumbnail size check
# - [x] write metadata and cover
# - [x] email notification
# - [x] mailgun setup guide
# - [x] slack notification
# - [x] telegram notification
# - [x] discord notification
# - [x] refine telegram multichannel support
# - [x] channel name mapping
# - [x] download base dir support
# - [ ] upcoming streams detection
# - [x] keyword filter
# - [x] summary output for uploading
# - [x] recording summary
# - [x] embed cover
# - [x] add hostname to output
# - [x] dockerize this script
# - [x] rewrite is_live detection logic
#
#
# Variables
#
BIN_VERSION="2.0.0"
# DEPRECATED: use `user_agent` in `config.yml` instead. This is for backward compatibility.
LEGACY_USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"
#
# Functions
#
# Text color helper borrowed from acme.sh
__green() {
printf '\033[1;31;32m%b\033[0m' "$1"
}
__yellow() {
printf '\033[1;31;33m%b\033[0m' "$1"
}
__red() {
printf '\033[1;31;40m%b\033[0m' "$1"
}
__info() {
printf "[$(date)] %s\n" "$1"
}
__debug() {
DEBUG="${PARAM_DEBUG:-"false"}"
if [ "$DEBUG" == "true" ]; then
printf "[$(date)] DEBUG: %s\n" "$1"
fi
}
# Convert secs to HH:MM:SS format
__convert_seconds() {
# https://stackoverflow.com/a/39452629/412385
printf '%02d:%02d:%02d\n' $(($1/3600)) $(($1%3600/60)) $(($1%60))
}
# Set the current working directory to the directory of this script
# http://stackoverflow.com/a/17744637/412385
cd ${0%/*}
# Prepare options
POSITIONAL=()
while [ $# -gt 0 ]; do
key="$1"
case $key in
-e|--extension)
EXTENSION="$2"
shift # past argument
shift # past value
;;
-m|--mode)
PARAM_MODE="$2"
shift
shift
;;
--filter)
PARAM_FILTER="$2"
shift
shift
;;
-o|--output)
PARAM_BASE_DIR="$2"
shift
shift
;;
-i|--interval)
PARAM_INTERVAL="$2"
shift
shift
;;
-u|--user-agent)
PARAM_USER_AGENT="$2"
shift
shift
;;
--image-proxy)
PARAM_IMAGE_PROXY="$2"
shift
shift
;;
--ytdl-stream)
PARAM_YTDL_STREAM=true
shift
;;
--ytdl-args)
PARAM_YTDL_ARGS="$2"
shift
shift
;;
--streamlink-args)
PARAM_STREAMLINK_ARGS="$2"
shift
shift
;;
--init)
PARAM_INIT_SCRIPT=true
shift
;;
--debug)
PARAM_DEBUG=true
shift
;;
--skip-convert)
PARAM_SKIP_CONVERT=true
shift
;;
--skip-metadata)
PARAM_SKIP_METADATA=true
shift
;;
--skip-email)
PARAM_SKIP_EMAIL=true
shift
;;
--skip-slack)
PARAM_SKIP_SLACK=true
shift
;;
--skip-telegram)
PARAM_SKIP_TELEGRAM=true
shift
;;
--skip-discord)
PARAM_SKIP_DISCORD=true
shift
;;
-1|--once)
PARAM_ONE_TIME=true
shift
;;
-v|--version)
PARAM_SHOW_VERSION=true
shift
;;
*) # other unknown options
POSITIONAL+=("$1") # save it in an array for later
shift
;;
esac
done
# restore positional parameters
set -- "${POSITIONAL[@]}"
# Install repo for CentOS/RHEL
function func_add_repo_rhel() {
rpm --import http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro
rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm
}
# Check dependencies
function func_check_deps() {
__info "Checking dependencies..."
if command -v ffmpeg >/dev/null 2>&1 ; then
__info "$(__green "Found"): $(ffmpeg -version | head -n 1)"
else
__info "FFmpeg not found, trying to install..."
if [ "$OSTYPE" == "linux-gnu" ]; then
if [ -f /etc/redhat-release ]; then
yum install epel-release -y
func_add_repo_rhel
yum install ffmpeg -y
fi
if [ -f /etc/lsb-release ]; then
apt-get install ffmpeg -y
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install ffmpeg
else
__info "No platform/architecture supported, please install it manually."
fi
fi
if command -v yt-dlp >/dev/null 2>&1 ; then
__info "$(__green "Found"): yt-dlp $(yt-dlp --version | head -n 1)"
else
__info "yt-dlp not found, trying to install..."
if [ "$OSTYPE" == "linux-gnu" ]; then
curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp
chmod a+rx /usr/local/bin/yt-dlp
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install yt-dlp
else
__info "No platform/architecture supported, please install it manually."
fi
fi
if command -v jq >/dev/null 2>&1 ; then
__info "$(__green "Found"): $(jq --version | head -n 1)"
else
__info "jq not found, trying to install..."
if [ "$OSTYPE" == "linux-gnu" ]; then
if [ -f /etc/redhat-release ]; then
yum install epel-release -y
yum install jq -y
fi
if [ -f /etc/lsb-release ]; then
apt-get install jq -y
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install jq
else
__info "No platform/architecture supported, please install it manually."
fi
fi
if command -v yq >/dev/null 2>&1 ; then
__info "$(__green "Found"): $(yq --version | head -n 1)"
else
__info "yq not found, trying to install..."
if [ "$OSTYPE" == "linux-gnu" ]; then
if [ -f /etc/redhat-release ]; then
pip install yq
fi
if [ -f /etc/lsb-release ]; then
apt install python-pip
pip install yq
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install python-yq
else
__info "No platform/architecture supported, please install it manually."
fi
fi
if command -v exiv2 >/dev/null 2>&1 ; then
__info "$(__green "Found"): $(exiv2 --version | head -n 1)"
else
__info "exiv2 not found, trying to install..."
if [ "$OSTYPE" == "linux-gnu" ]; then
if [ -f /etc/redhat-release ]; then
yum install exiv2 -y
fi
if [ -f /etc/lsb-release ]; then
apt-get install exiv2 -y
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install exiv2
else
__info "No platform/architecture supported, please install it manually."
fi
fi
if command -v aria2c >/dev/null 2>&1 ; then
__info "$(__green "Found"): $(aria2c -v | head -n 1)"
else
__info "aria2 not found, trying to install..."
if [ "$OSTYPE" == "linux-gnu" ]; then
if [ -f /etc/redhat-release ]; then
yum install epel-release -y
yum install aria2 -y
fi
if [ -f /etc/lsb-release ]; then
apt-get install aria2 -y
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install aria2
else
__info "No platform/architecture supported, please install it manually."
fi
fi
if command -v streamlink >/dev/null 2>&1 ; then
__info "$(__green "Found"): $(streamlink --version | head -n 1)"
else
__info "streamlink not found, trying to install..."
if [ "$OSTYPE" == "linux-gnu" ]; then
if [ -f /etc/redhat-release ]; then
pip install streamlink
fi
if [ -f /etc/lsb-release ]; then
add-apt-repository ppa:nilarimogard/webupd8
apt install streamlink
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
brew install streamlink
else
__info "No platform/architecture supported, please install it manually."
fi
fi
}
function func_create_url() {
# Create correct URL/URI based on user input
#
# https://www.youtube.com/channel/UCxRuOqAAVo-f516Gygjh_wA/live
# https://www.youtube.com/channel/UC1opHUrw8rvnsadT-iGp7Cg
# https://www.youtube.com/watch?v=S3CAGeeMRvo
# https://www.youtube.com/playlist?list=UU1opHUrw8rvnsadT-iGp7Cg
# https://www.youtube.com/feed/subscriptions
# https://live.bilibili.com/14917277
# https://live.bilibili.com/456117
#
local _url=$1
if [[ "$_url" =~ "youtube.com" ]]; then
__info "YouTube URL detected"
DL_PLATFORM="YouTube"
if [[ "$_url" =~ "/channel" && "$_url" =~ "/live" ]]; then
__info "YouTube channel detected"
DL_URL="$_url"
DL_TYPE="channel"
elif [[ "$_url" =~ "/channel" && ! "$_url" =~ "/live" ]]; then
__info "YouTube video detected (alt)"
DL_URL="$_url/live"
DL_TYPE="channel"
elif [[ "$_url" =~ "/watch"* ]]; then
__info "YouTube video detected"
DL_URL="$_url"
DL_TYPE="video"
elif [[ "$_url" =~ "/playlist"* ]]; then
__info "YouTube playlist detected"
DL_URL="$_url"
DL_TYPE="playlist"
else
__info "$(__red "Non-supported YouTube URL")"
exit 1
fi
elif [[ "$_url" =~ "live.bilibili.com" ]]; then
__info "Bilibili detected"
DL_URL="$_url"
DL_PLATFORM="bilibili"
else
if [[ ! "$_url" == "http"* ]]; then
__info "$(__yellow "URI detected, guessing... (Use full URL to avoid guessing URL)")"
if [[ "$_url" =~ ^([0-9]+)$ ]]; then
__info "Bilibili room ID detected"
DL_URL="https://live.bilibili.com/$_url"
DL_PLATFORM="bilibili"
# if URI is longer than 11 (11 is the length of YouTube video ID)
elif [[ ${#_url} -ge 12 ]]; then
__info "YouTube channel ID detected"
DL_URL="https://www.youtube.com/channel/$_url/live"
DL_PLATFORM="YouTube"
DL_TYPE="channel"
else
__info "YouTube video ID detected"
DL_URL="https://www.youtube.com/watch?v=$_url"
DL_PLATFORM="YouTube"
DL_TYPE="video"
fi
else
__info "$(__red "Non-supported URL")"
exit 1
fi
fi
}
function func_check_state() {
local _url=$1
local _mode=$2
__debug "start func_check_state"
# Assume it's not a valid page, I use a custom state `invalid` here as initial state
CONTENT_STATE="invalid"
if [ "$DL_PLATFORM" == "YouTube" ]; then
# Actually there's an official way to check if the streamer is live or not[^1] using YouTube
# offical Data API, but it's costy that every search request costs you 100 credits. However
# you can try it online[^2] to see how it works.
#
# If you have accounts that registered YouTube developer program before 2017, and has more
# than 10 million credit quota, you can contact me t@sparanoid.com
#
# [1]: https://developers.google.com/youtube/v3/docs/search
# [2]: https://developers.google.com/youtube/v3/code_samples/code_snippets
# First check: use curl to check HTML pages for live state
# Pros:
# - Fast, no additional API requests compared to yt-dlp
# - More ban-proof compared to yt-dlp
# Cons:
# - Can get wrong live state due to page caching, network interrupts, etc.
METADATA_CURL_RAW=$(curl -b cookies.txt -s --compressed -H "User-Agent: $USER_AGENT" "$_url")
# Match only JSON part
# https://regex101.com/r/QiyZE2/3
#
# Debug commmand if YouTube changes its HTML structure in the future:
# $ curl -s --compressed -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" 'https://www.youtube.com/watch?v=j2z06YUbulk' | grep 'ytInitialPlayerResponse' | grep '<script' | grep 'responseContext' | perl -pe 's/^.*?ytInitialPlayerResponse = ({".*]});var .*/\1/g' | jq -r .
METADATA_CURL=`echo "$METADATA_CURL_RAW" | sed -n 's/.*var ytInitialPlayerResponse = \({[^<]*}\);.*/\1/p' | jq -r .`
# Check if returns nothing
if [ ! -z "$METADATA_CURL" ]; then
__debug "Got valid cURL metadata"
# At the time of writing, when `videoDetails.isLive` exists, it should be on live, when a video
# is not live (normal videos, and even upcoming streams) this key will be missing and jq will
# return `null`
IS_LIVE=$(echo "$METADATA_CURL" | jq -r '.videoDetails.isLive | select(.!=null)')
__debug "Is live: $IS_LIVE"
# This status will always return:
# - `OK` for live streams, private streams, or normal videos,
# - `LIVE_STREAM_OFFLINE` for offline channel
PLAYABILITY=$(echo "$METADATA_CURL" | jq -r '.playabilityStatus.status | select(.!=null)')
__debug "Playability: $PLAYABILITY"
# You will get some playability reasons for:
# - `Offline` for streams are not live
# - `This live event will begin in {n} hours.` for upcoming streams, you can also get specific
# UNIX timestamp with .scheduledStartTime (see below)
# - `null` (this key will be missing) for:
# - On live streams or private streams
# - Non-streaming content
PLAYABILITY_REASON=$(echo "$METADATA_CURL" | jq -r '.playabilityStatus.reason | select(.!=null)')
__debug "Playability Reason: $PLAYABILITY_REASON"
# When the streamer is streaming privately, this key will be empty
STREAMABILITY=$(echo "$METADATA_CURL" | jq -r '.playabilityStatus.liveStreamability.liveStreamabilityRenderer.videoId | select(.!=null)')
__debug "Streamability ID: $STREAMABILITY"
# Get upcoming time when available
# This key will be missing if no upcoming events available
UPCOMING_TIME=$(echo "$METADATA_CURL" | jq -r '.playabilityStatus.liveStreamability.liveStreamabilityRenderer.offlineSlate.liveStreamOfflineSlateRenderer.scheduledStartTime | select(.!=null)')
if [ ! -z "$UPCOMING_TIME" ]; then
if [[ "$OSTYPE" == "darwin"* ]]; then
local _date_calc=`date -r $UPCOMING_TIME`
else
local _date_calc=`date -d @$UPCOMING_TIME`
fi
__debug "Scheduled Time: $_date_calc ($UPCOMING_TIME)"
fi
# Get some metadata first, I will retrieve more later using yt-dlp
VIDEO_ID=$(echo "$METADATA_CURL" | jq -r '.videoDetails.videoId')
FULLTITLE=$(echo "$METADATA_CURL" | jq -r '.videoDetails.title')
DESCRIPTION=$(echo "$METADATA_CURL" | jq -r '.videoDetails.shortDescription')
UPLOADER=$(echo "$METADATA_CURL" | jq -r '.videoDetails.author')
CHANNEL_ID=$(echo "$METADATA_CURL" | jq -r '.videoDetails.channelId')
# Print basic metadata for reference
__debug "Channel: $UPLOADER"
__debug "Title: $FULLTITLE"
# NOTE: Oct 25, 2020
# With recent changes of YouTube API, you cannot get live JSON from a /live channel URL.
# This causes empty response during yt-dlp second check. So I redirect channel page check to
# video page check after I got the specific video ID.
if ([ "$DL_TYPE" == "channel" ] && [ "$DL_PLATFORM" == "YouTube" ]); then
_url="https://www.youtube.com/watch?v=$VIDEO_ID"
fi
# If I got `isLive: true` in first check, let me assume it's live but I can't trust it so I
# will do a secound check using yt-dlp later with this flag.
if [ "$IS_LIVE" == "true" ]; then
__info "cURL check seems goes live now, continue checking..."
if [ ! -z "$FILTER" ]; then
__debug "User filter found: $(__yellow "$FILTER"). Checking if video title matches..."
if [[ "$FULLTITLE" =~ $FILTER ]]; then
__info "$(__green "Video title matched, mark as downloadable...")"
CONTENT_STATE="live"
else
__info "$(__yellow "Video title does not match, skipping and continue monitoring...")"
CONTENT_STATE="invalid"
fi
else
__debug "No user filter found, mark as downloadable..."
CONTENT_STATE="live"
fi
else
# If `isLive` key not exists, check if it's a valid video (playable)
if [ "$PLAYABILITY" == "OK" ]; then
# Then check if it's a channel URL
if [ "$DL_TYPE" == "channel" ]; then
# Check if the streamer is streaming privately.
if [ -z "$STREAMABILITY" ]; then
__info "$(__yellow "/live redirects to /, event mode or streaming privately?")"
fi
else
CONTENT_STATE="video"
fi
fi
# Then check if the stream just goes offline
if [ "$PLAYABILITY" == "LIVE_STREAM_OFFLINE" ]; then
CONTENT_STATE="offline"
# Check if upcoming event available
if [ ! -z "$UPCOMING_TIME" ]; then
__info "$(__yellow "Upcoming event detected: $UPCOMING_TIME")"
fi
fi
fi
# Print current state for first check
__debug "Current state for first check: $(__yellow "$CONTENT_STATE")"
else
# Nov 14, 2021: YouTube no longer retuns a valid JSON response for /live channel URL when the
# channel is not live. So just silent fail here.
if ([ "$DL_TYPE" == "channel" ] && [ "$DL_PLATFORM" == "YouTube" ]); then
__debug "$(__yellow "Channel page is offline with no JSON extracted")"
else
__info "$(__yellow "Not a valid page, something wrong with your internet connection?")"
fi
fi
# Old method:
# if echo "$_body" | grep -q 'ytplayer'; then
# # Assume it's not a live streaming page
# IS_LIVE_CONTENT="false"
# # Actually there's an official way to check if the streamer is live or not[^1] using YouTube
# # offical Data API, but it's costy that every search request costs you 100 credits. However
# # you can try it online[^2] to see how it works.
# #
# # If you have accounts that registered YouTube developer program before 2017, and has more
# # than 10 million credit quota, you can contact me t@sparanoid.com
# #
# # [1]: https://developers.google.com/youtube/v3/docs/search
# # [2]: https://developers.google.com/youtube/v3/code_samples/code_snippets
# if echo "$_body" | grep 'ytplayer' | grep -q '\\"isLive\\":true'; then
# # Is live, break out of loop and continue to next step
# IS_LIVE_CONTENT="true"
# break
# fi
# # Also break out if the given URL is not a channel (probably a video or a playlist)
# # This extra check could avoid downloading an upcoming stream when then "isLive" check above
# # fails for some reason (like YouTube changes the `isLive` JSON key to something else)
# if ! [ "$DL_TYPE" == "channel" ]; then
# # This script now can also handle normal YouTube video, but there's no way to check if the
# # given URL is a normal video or an upcoming stream, so we can just break out of the loop
# # and fallback to yt-dlp to check whelter this URL is downloadable. And make sure it
# # only execute once.
# ONE_TIME="true"
# break
# fi
# else
# __info "$(__yellow "Not a valid video page!")"
# __info "You may get this warning due to internet interruption, continue running"
# # NOTE: Although this is the natural logic to exit the program if we can't find specific
# # element on this page that means it's not a valid video page. But in some rare cases, the
# # original page may be down or unreachable for internet interruption or other network issues.
# # So I decide to let the script continue to execute because this script is mainly focused on
# # recording streams.
# # exit 1
# fi
# Second check: use `yt-dlp` to check live state
# NOTE: please avoid adding additional paths in the -o (template) option, it doesn't work well
# and conflicts with my custom directory setup!
# I also need redirect stderr to stdout to catch any error during fetching URL
# Pros:
# - Accurate live state detection
# Cons:
# - Slow, yt-dlp will fire API requests to get more info it need to download videos
# - Your IP can get banned easily when running in download or notifier mode due to large amount of
# API requests.
if [ "$CONTENT_STATE" != "invalid" ]; then
# Condition explain:
# Only run second check when:
# - The stream goes live that need a second check to ensure it's actually live
# - The stream goes offline that need a second check to ensure it's actually offline
if ([ "$CONTENT_STATE" != "offline" ] && [ "$_mode" != "lazy" ]) || \
([ "$CONTENT_STATE" == "offline" ] && [ "$_mode" == "lazy" ])
then
__info "Re-checking via yt-dlp..."
METADATA=`yt-dlp --ignore-config --no-playlist --playlist-items 0 --no-warnings \
--skip-download --print-json --referer 'https://www.youtube.com/feed/subscriptions' \
--cookies cookies.txt $YTDL_ARGS -o '%(upload_date)s %(title)s (%(id)s).%(ext)s' \
"$_url" 2>&1`
# Check if returns nothing
if [ ! -z "$METADATA" ]; then
__debug "Got valid yt-dlp metadata"
# Check if it's a valid JSON return
if [[ "$METADATA" == '{'* ]]; then
# Unlike other part of the jq checks, I ignore the `| select(.!=null)` to explicitly
# return `null` to tell if it's a normal video or it just returns nothing
local _is_live=`echo "$METADATA" | jq -r '.is_live'`
# Parse metadata
func_process_youtube_metadata
# Map uploader name with pre-defined config
func_process_channel_mapping
# Finalize variables and paths then output summary
func_finalize_vars
if [ "$_is_live" == "true" ]; then
__debug "Got state: live";
CONTENT_STATE="live"
elif [ "$_is_live" == "false" ]; then
__debug "Got state: video";
CONTENT_STATE="video"
else
__info "yt-dlp does not returns a valid state";
CONTENT_STATE="invalid"
fi
else
__debug "$METADATA"
if [[ "$METADATA" =~ "This video is unavailable" ]]; then
# Suppress `video is unavailable` errors since they're common when stream is not live
# NOTE: Nov 17, 2021: Now YouTube no longer returns any JSON response for offline channels
# so all offline state will fallback to `invalid` at the moment
__debug "This video is unavailable, maybe not live at the moment."
CONTENT_STATE="unavailable"
elif [[ "$METADATA" =~ "HTTP Error 404" ]]; then
__info "$(__yellow "Not a valid video page (Error 404)!")"
CONTENT_STATE="not_found"
elif [[ "$METADATA" =~ "HTTP Error 429" ]]; then
__info "$(__yellow "Your IP is limited by YouTube (Error 429)!")"
CONTENT_STATE="too_many_requests"
else
__info "$(__yellow "Unknown metadata")"
__info "$METADATA"
CONTENT_STATE="invalid"
fi
fi
else
__info "$(__yellow "Second check failed, not valid yt-dlp metadata")"
CONTENT_STATE="invalid"
fi
# Print current state for second check
__debug "Current state for second check: $(__yellow "$CONTENT_STATE")"
fi
fi
fi
}
function func_send_email() {
local _title=$1
local _content=$2
if [ "$SKIP_EMAIL" != "true" ]; then
if [ "$CONFIG_EMAIL_PROVIDER" == "mailgun" ]; then
if [ "$CONFIG_MAILGUN_API" == "key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ]; then
__info "$(__yellow "No Mailgun credentials found, skip sending email notification")"
else
__info "Sending email notification..."
curl -s --user "api:$CONFIG_MAILGUN_API" \
https://api.mailgun.net/v3/"$CONFIG_MAILGUN_DOMAIN"/messages \
-F from="Livestream Downloader (live-dl) <live-dl@$CONFIG_MAILGUN_DOMAIN>" \
-F to="$CONFIG_MAILGUN_RECEIPT" \
-F subject="$_title" \
-F text="$_content" >> "$OUTPUT_PATH.log" 2>&1
fi
fi
if [ "$CONFIG_EMAIL_PROVIDER" == "ses" ]; then
if [ "$CONFIG_SES_ACCESS" == "AKxxxxxxxxxxxxxxxxxx" ]; then
__info "$(__yellow "No AWS SES credentials found, skip sending email notification")"
else
__info "Sending email notification..."
local FROM="Livestream Downloader (live-dl) <live-dl@$CONFIG_SES_DOMAIN>"
local ses_date="$(date -R)"
# base64 different behavior alert:
# https://stackoverflow.com/a/46464081/412385
# Just use `base64` or `base64 -b 0` on macOS, on other platforms, use:
# `base64 -w 0`
local ses_signature="$(echo -n "$ses_date" | openssl dgst -sha256 -hmac "$CONFIG_SES_SECRET" -binary | base64)"
local ses_auth_header="X-Amzn-Authorization: AWS3-HTTPS AWSAccessKeyId=$CONFIG_SES_ACCESS, Algorithm=HmacSHA256, Signature=$ses_signature"
local ses_endpoint="https://email.us-east-1.amazonaws.com/"
local ses_action="Action=SendEmail"
local ses_source="Source=$FROM"
local ses_to="Destination.ToAddresses.member.1=$TO"
local ses_subject="Message.Subject.Data=$_title"
local ses_message="Message.Body.Text.Data=$_content"
curl -X POST -H "Date: $ses_date" -H "$ses_auth_header" \
--data-urlencode "$ses_message" \
--data-urlencode "$ses_to" \
--data-urlencode "$ses_source" \
--data-urlencode "$ses_action" \
--data-urlencode "$ses_subject" \
"$ses_endpoint" >/dev/null 2>&1
fi
fi
fi
}
function func_send_slack() {
local _type=$1
if [ "$SKIP_SLACK" != "true" ]; then
if [ "$CONFIG_SLACK_WEBHOOK" == "https://hooks.slack.com/services/" ]; then
__info "$(__yellow "No Slack credentials found, skip sending Slack notification")"
else
__info "Sending Slack notification..."
if [ "$_type" == "start" ]; then
local _body='{
"icon_emoji": ":red_circle:",
"channel": "'"$UPLOADER"'",
"text": "'"$UPLOADER"' goes live on '"$DL_PLATFORM"' '"$WEBPAGE_URL"'",
"attachments": [
{
"fallback": "'"$UPLOADER"' goes live on '"$DL_PLATFORM"'",
"color": "#f570de",
"fields": [
{
"title": "Title",
"value": "'"$FULLTITLE"'",
"short": false
},
{
"title": "ID",
"value": "<'"$WEBPAGE_URL"'|'"$VIDEO_ID"'>",
"short": true
},
{
"title": "Channel",
"value": "<'"$CHANNEL_URL"'|'"$CHANNEL_ID"'>",
"short": true
},
{
"title": "Thumbnail",
"value": "<'"$THUMBNAIL_CALC"'|View in new tab>",
"short": true
},
{
"title": "Date",
"value": "'"$UPLOAD_DATE"'",
"short": true
}
]
}
]
}'
elif [ "$_type" == "stop" ]; then
local _body='{
"icon_emoji": ":black_square:",
"channel": "'"$UPLOADER"'",
"text": "'"$UPLOADER"' stopped streaming on '"$DL_PLATFORM"' '"$WEBPAGE_URL"'",
"attachments": [
{
"fallback": "'"$UPLOADER"' stopped streaming on '"$DL_PLATFORM"'",
"color": "#f570de",
"fields": [
{
"title": "Title",
"value": "'"$FULLTITLE"'",
"short": false
},
{
"title": "Views",
"value": "'"$VIEW_COUNT"'",
"short": true
},
{
"title": "Likes",
"value": "'"$LIKE_COUNT"'",
"short": true
},
{
"title": "Dislikes",
"value": "'"$DISLIKE_COUNT"'",
"short": true
},
{
"title": "Average Rating",
"value": "'"$AVERAGE_RATING"'",
"short": true
}
]
}
]
}'
else
local _body='{
"icon_emoji": ":ghost:",
"channel": "'"$UPLOADER"'",
"text": "'"$UPLOADER"' goes live on '"$DL_PLATFORM"' '"$WEBPAGE_URL"'",
"attachments": [
{
"fallback": "'"$UPLOADER"' goes live on '"$DL_PLATFORM"'",
"color": "#f570de",
"fields": [
{
"title": "Title",
"value": "'"$FULLTITLE"'",
"short": false
},
{
"title": "ID",
"value": "<'"$WEBPAGE_URL"'|'"$VIDEO_ID"'>",
"short": true
},
{
"title": "Channel",
"value": "<'"$CHANNEL_URL"'|'"$CHANNEL_ID"'>",
"short": true
},
{
"title": "Thumbnail",
"value": "<'"$THUMBNAIL_CALC"'|View in new tab>",
"short": true
},
{
"title": "Date",
"value": "'"$UPLOAD_DATE"'",
"short": true
}
]
}
]
}'
fi
curl -s -X POST -H 'Content-type: application/json' \
-d "$_body" "$CONFIG_SLACK_WEBHOOK"
fi
fi
}
function func_send_telegram() {
local _type=$1
# https://core.telegram.org/bots/api
if [ "$SKIP_TELEGRAM" != "true" ]; then
if [ "$CONFIG_TELEGRAM_BOT" == "000000000:xxxxxxxxx" ]; then
__info "$(__yellow "No Telegram credentials found, skip sending Telegram notification")"
else
if [ "$UPLOADER_TG_CHANNEL" ]; then
__info "Sending Telegram notification..."
local _time_start=$(TZ=":$UPLOADER_TIMEZONE" date +"%b %e %H:%M %Z (%z)")
if [ "$_type" == "start" ]; then
local _type="sendPhoto"
local _body='{
"chat_id": "'"$UPLOADER_TG_CHANNEL"'",
"photo": "'"$THUMBNAIL_CALC"'",
"caption": "🔴 '"$UPLOADER"' goes live on '"$DL_PLATFORM"'\n'"$FULLTITLE"'\n\nStarts on '"$_time_start"'",
"reply_markup": {
"inline_keyboard": [
[
{"text": "Watch it now", "url": "'"$WEBPAGE_URL"'"}
],
[
{"text": "View channel", "url": "'"$CHANNEL_URL"'"},
{"text": "View artwork", "url": "'"$IMAGE_PROXY$THUMBNAIL_CALC"'"}
]
]
},
"disable_notification": false
}'
elif [ "$_type" == "stop" ]; then
local _type="sendMessage"
local _body='{
"chat_id": "'"$UPLOADER_TG_CHANNEL"'",
"text": "⬛️ '"$UPLOADER"' stopped streaming on '"$DL_PLATFORM"'\n'"$FULLTITLE"'\n\nViews: '"$VIEW_COUNT"'\nLikes: '"$LIKE_COUNT"'\nDislikes: '"$DISLIKE_COUNT"'\nAverage Rating: '"$AVERAGE_RATING"'",
"reply_markup": {
"inline_keyboard": [
[
{"text": "Watch finished stream", "url": "'"$WEBPAGE_URL"'"}
]
]
},
"disable_notification": true
}'
else
local _type="sendMessage"
local _body='{
"chat_id": "'"$UPLOADER_TG_CHANNEL"'",
"text": "🔴 '"$UPLOADER"' goes live on '"$DL_PLATFORM"'\n'"$FULLTITLE"'\n'"$WEBPAGE_URL"'",
"reply_markup": {
"inline_keyboard": [
[
{"text": "Watch it now", "url": "'"$WEBPAGE_URL"'"}
],
[
{"text": "View channel", "url": "'"$CHANNEL_URL"'"},
{"text": "View artwork", "url": "'"$IMAGE_PROXY$THUMBNAIL_CALC"'"}
]
]
},
"disable_notification": false
}'
fi
curl -s -X POST -H 'Content-Type: application/json' \
-d "$_body" "https://api.telegram.org/bot$CONFIG_TELEGRAM_BOT/$_type"
else
__info "No specific channel set for current user, skip sending Telegram notification."
fi
fi
fi
}
function func_send_discord() {
local _type=$1
if [ "$SKIP_DISCORD" != "true" ]; then
CURRENT_DISCORD_WEBOOK="$CONFIG_DISCORD_WEBHOOK"
if [ "$UPLOADER_DISCORD_URL" ]; then
CURRENT_DISCORD_WEBOOK="$UPLOADER_DISCORD_URL"
fi
if [ "$CURRENT_DISCORD_WEBOOK" == "https://discord.com/api/webhooks/" ]; then
__info "$(__yellow "No Discord credentials found, skip sending Discord notification")"
else
__info "Sending Discord notification..."
if [ "$_type" == "start" ]; then
local _body='{
"content": "'"$UPLOADER"' goes live on '"$DL_PLATFORM"' '"$WEBPAGE_URL"'",
"embeds": [
{
"color": 16085214,
"thumbnail": {
"url": "'$THUMBNAIL_CALC'"
},
"fields": [
{
"name": "Title",