This repository was archived by the owner on Feb 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnow.sh
More file actions
executable file
·1153 lines (1052 loc) · 29 KB
/
Copy pathnow.sh
File metadata and controls
executable file
·1153 lines (1052 loc) · 29 KB
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
#------------------------------------------------------------------
#
# Now Downloader
#
# Created on 2020 May 12
#
# Author: TheNoFace (thenoface303@gmail.com)
#
# TODO:
# 200531) 방송 시각과 현재 시각 차이가 20분 이상이면 (시각차이-20)분 sleep
# 200812) 방송 요일 구해서 금일 방송이 아니라면 자동 custimer
# 200829) onairwait 대기 중 24시 넘어가면 Time Difference +24시간 재설정
# 201018) onairwait(): TIMECHECK의 60% 이상 분단위 sleep
# 201018) Verbose 모드에서만 표시할 메세지 정리
# 201018) Log 내재화
# 201109) getstream()에서 URL 확인 시 MAXRETRY 제한
#
#------------------------------------------------------------------
# get_options -> script_init -> main
# contentget -> exrefresh -> timeupdate
# onairwait -> getstream -> convert
# Color template
if [ -t 1 ]
then
RED=$(tput setaf 1)
GRN=$(tput setaf 2)
YLW=$(tput setaf 3)
NC=$(tput sgr0)
else
RED=""
GRN=""
YLW=""
NC=""
fi
NDV="1.6.2"
BANNER="Now Downloader v$NDV"
SCRIPT_NAME=$(basename $0)
oriIFS=$IFS
P_LIST=(bc jq curl wget ffmpeg)
dirList=(content log show chat)
NOW_LINK='https://apis.naver.com/now_web/oldnow_web/v4/stream'
SHOW_ID=""
FORCE=""
KEEP=""
OPATH_I=""
ITG_CHECK=""
N_RETRY=""
MAXRETRYSET=10
CHKINTSET=30
chatCheckInterval=1
CUSTIMER=""
SREASON=""
VERB=""
CTRETRY="0"
RETRY="0"
EXRETRY="0"
S_RETRY="0"
### VALIDATOR
function is_not_empty()
{
[ -z "$1" ] && return 1
return 0
}
function is_empty()
{
[ -z "$1" ] && return 0
return 1
}
### MESSAGES
function err_msg()
{
if [ "$1" = '-t' ] && is_not_empty "$2"
then
echo -e "${RED}[$(date +'%x %T')] $2${NC}"
elif is_not_empty "$1"
then
echo -e "${RED}$1${NC}"
fi
}
function alert_msg()
{
if [ "$1" = '-t' ] && is_not_empty "$2"
then
echo -e "${YLW}[$(date +'%x %T')] $2${NC}"
elif is_not_empty "$1"
then
echo -e "${YLW}$1${NC}"
fi
}
function info_msg()
{
if [ "$1" = '-t' ] && is_not_empty "$2"
then
echo -e "${GRN}[$(date +'%x %T')] $2${NC}"
elif is_not_empty "$1"
then
echo -e "${GRN}$1${NC}"
fi
}
function msg()
{
if [ "$1" = '-t' ] && is_not_empty "$2"
then
echo -e "[$(date +'%x %T')] $2"
elif is_not_empty "$1"
then
echo -e "$1"
fi
}
### FUNCTION STARTS
function get_parms()
{
while :
do
case "$1" in
--version)
print_banner ; exit 0 ;;
--help)
print_help ; exit 0 ;;
-l|--list)
availableArg="live"
if [ "$2" = 'live' ]
then
isListLive=1
elif [ -n "$2" ]
then
isError=1
errArg="$2"
isListLive=1
else
isListLive=0
fi
get_list ; exit 0 ;;
-i|--id)
SHOW_ID="$2" ; shift ; shift ;;
-f|--force)
FORCE=1 ; shift ;;
-k|--keep)
KEEP=1 ; shift ;;
-o|--output)
OPATH_I="$2" ; shift ; shift ;;
-nc|--no-check)
ITG_CHECK=1 ; shift ;;
-r|--retry)
MAXRETRY="$2" ; shift ; shift ;;
-nr|--no-retry)
N_RETRY=1 ; shift ;;
-t|--time-check)
CHKINT="$2" ; shift ; shift ;;
--custimer)
CUSTIMER="$2" ; shift ; shift ;;
-v|--verbose)
VERB=1 ; shift ;;
-u|--user)
G_USR=1 ; shift ;;
--info)
GetInfo=1 ; shift ;;
-c|--chat)
showChat=1 ; managerOnly=1 ; shift ;;
--chat-all)
showChat=1 ; managerOnly=0 ; shift ;;
*)
check_invalid_parms "$1" ; break ;;
esac
done
}
function check_invalid_parms()
{
if is_not_empty "$1"
then
print_help
err_msg "Invalid Option: $1\n"
exit 2
elif [ -z ${SHOW_ID} ]
then
print_help
err_msg "Please enter valid Show ID\n"
exit 2
fi
return 0
}
function print_banner()
{
info_msg "\n$BANNER\n"
}
function print_help()
{
print_banner
echo -e "Usage: $SCRIPT_NAME -i [ShowID] [options]\n"
alert_msg Required:
echo " -i | --id [number] ID of the show to download
Options:
-c | --chat Print live or recent host/manager's chats and save into file
--chat-all Print live or recent chats and save into file"
alert_msg " NOTE: File is saved after the show has finished (ONAIR -> END)"
echo " --custimer [second] Custom sleep timer before starting script"
alert_msg " NOTE: Mandatory if today is not the broadcasting day"
echo " -f | --force Start download immediately without any time checks
--info Display detailed info of the show
-k | --keep Do not delete original audio stream(.ts) file after download finishes
-l | --list (live) List every shows' ID and titles then exits
live: List shows' ID and titles that are currently on air
-nc | --no-check Do not check integrity of content/livestatus files in content folder
-nr | --no-retry Disable retries (same as -r 0)
-o | --output <dir> Overrides output path to check if it's been set before
-r | --retry [number] Maximum retries if download fails
Default is set to $MAXRETRYSET times
-t | --time-check [second] Check stream status if it has ended abnormally by checking file size
Default is set to $CHKINTSET seconds
-u | --user Display current/total users of the show
-v | --verbose Print wget/ffmpeg messages
--help Show this help screen
--version Show program name and version
Notes:
- Short options should not be grouped. You must pass each parameter on its own.
- Disabling flags priors than setting flags
Example:
* $SCRIPT_NAME -i 495 -o /home/$USER/now -r 100 -t 60 -c 86400
- Override output directory to /home/$USER/now
- Wait 86400 seconds (24hr) before starting this script
- Download #495 show
- Retries 100 times if download fails
- Check stream status for every 60 seconds
* $SCRIPT_NAME -i 495 -f -nr -nc -k
- Do not retry download even if download fails
- Do not check integrity of content/livestatus files in content folder
- Download #495 show immediately without checking time
- Do not delete original audio stream file after download finishes
"
}
function dir_check()
{
if [ ! -d "${OPATH}" ]
then
mkdir -p "${OPATH}" & mdpid="$!"
wait ${mdpid}
pstatus="$?"
if [ $pstatus != 0 ]
then
err_msg "\nERROR: Couldn't create directory\nAre you sure you have proper ownership?\n"
exit 3
fi
info_msg "\nCreated Output Directory: ${OPATH}"
unset pstatus
fi
echo ${OPATH} > .opath
echo
}
function package_check()
{
for l in ${P_LIST[@]}
do
P=$(command -v $l)
if [ -z $P ]
then
NFOUND=(${NFOUND[@]} $l)
fi
done
if [ ${#NFOUND[@]} != 0 ]
then
print_banner
array=${NFOUND[@]}
err_msg "Couldn't find follow package(s): $array"
err_msg "Please install required package(s)\n"
exit 4
else
if [ -t 1 ]
then
print_banner
else
msg "\n---$BANNER-----------ShowID: ${SHOW_ID}-----------$(date +'%F %a %T')---\n"
fi
fi
}
function script_init()
{
d_date=$(date +'%y%m%d')
package_check
[ -n "$GetInfo" ] && get_info
if [ -z ${OPATH_I} ]
then
if [ ! -e .opath ]
then
echo -e "Seems like it's your first time to run this scipt"
echo -n "Please enter directory to save (e.g: /home/$USER/now): "
read OPATH
OPATH=${OPATH/"~"/"/home/$USER"}
dir_check
elif [ -e .opath ]
then
OPATH=$(cat .opath)
echo -e "Output Path: ${YLW}${OPATH}${NC}"
echo -e "If you want to change output path, delete ${YLW}$PWD/.opath${NC} file or use -o option"
dir_check
else
err_msg "ERROR: script_init OPATH\n"
exit 5
fi
elif [ -n ${OPATH_I} ]
then
OPATH=${OPATH_I/"~"/"/home/$USER"}
echo -e "Output Path: ${YLW}${OPATH} (Overrided)${NC}"
dir_check
fi
for i in ${dirList[@]}
do
if [ ! -d "${OPATH}/$i" ]
then
alert_msg "$i folder does not exitst, creating..."
mkdir "${OPATH}/$i"
else
msg "$i folder exists"
fi
done
echo
if [ "$showChat" = 1 ]
then
livestatusURL="${NOW_LINK}/$SHOW_ID/livestatus"
chatId=$(curl -s $livestatusURL | jq -r '.status.clientConfig.poll.comment.objectId')
chatURL="https://apis.naver.com/now_web/now-chat-api/list?object_id=$chatId"
show_chat
fi
if [ -n "$VERB" ] # https://unix.stackexchange.com/a/444949
then
alert_msg "Verbose Mode"
wget_c=(wget)
ffmpeg_c=(ffmpeg)
else
wget_c=(wget -q)
ffmpeg_c=(ffmpeg -loglevel quiet)
fi
if [ -n "$FORCE" ]
then
alert_msg "Force Download Enabled"
fi
if [ -n "$KEEP" ]
then
alert_msg "Keep original audio stream file after download has finished"
fi
if [ -z "$CUSTIMER" ]
then
alert_msg "Custom timer before start is not set"
fi
if [ -n "$ITG_CHECK" ]
then
alert_msg "Do not check integrity of content/livestatus files in content folder"
fi
if [ -z $N_RETRY ]
then
if [ -z $MAXRETRY ]
then
alert_msg "Maximum retry set to default ($MAXRETRYSET times)"
MAXRETRY=$MAXRETRYSET
else
alert_msg "Maximum retry set to $MAXRETRY times"
fi
elif [ -n $N_RETRY ]
then
MAXRETRY=0
alert_msg "Retry Disabled"
fi
if [ -z $CHKINT ]
then
alert_msg "Stream status check timer set to default ($CHKINTSET seconds)"
CHKINT=$CHKINTSET
else
alert_msg "Stream status check timer set to $CHKINT seconds"
fi
if [ -n "$CUSTIMER" ]
then
alert_msg "Custom sleep timer set to ${CUSTIMER}s"
fi
if [ -z "$N_RETRY" ] || [ -n "$CUSTIMER" ]
then
echo # For better logging
fi
if [ -n "$G_USR" ]
then
contentget
exrefresh
cur_user=$(echo "${livestatus}" | jq -r .status.indicator.concurrentUserCount)
total_user=$(echo "${livestatus}" | jq -r .status.indicator.cumulativeUserCount)
msg "\n$startdate $title by ${showhost}\n$subject"
if [ "$STATUS" = "ONAIR" ]
then
msg "방송 상태: ${RED}$STATUS${NC}\n접속자 수: $cur_user / 오늘 총 조회수: $total_user\n"
else
msg "방송 상태: $STATUS\n총 조회수: $total_user\n"
fi
exit 0
fi
}
function get_info()
{
content=$(curl -s "${NOW_LINK}/$SHOW_ID/content")
echo "$content" | jq -e '.contentList[].home.title.text' > /dev/null & JQPID=$!
wait $JQPID; ExitCode=$?
if [ $ExitCode != 0 ]
then
err_msg "Invalid Show ID, Use --list option to list available shows!\n"
exit 6
fi
guest=$(echo "$content" | jq -r '.contentList[] | (.guests | join(","))')
if [ -z "$guest" ]
then
info=$(echo "$content" | jq -r '.contentList[] | .home.title.text + " by " + (.hosts | join(", ")) + "\n\n" + .title.text + "\n\n" + .description.text')
else
info=$(echo "$content" | jq -r '.contentList[] | .home.title.text + " by " + (.hosts | join(", ")) + "\nGuest: " + (.guests | join(",")) + "\n\n" + .title.text + "\n\n" + .description.text')
fi
msg "${info}\n"
unset GetInfo
proceed_download ${SHOW_ID}
}
function get_chat()
{
get_status
IFS=$'\n'
# chatList=($(curl -s $chatURL | jq -r '[.result.recentManagerCommentList[] | .userName + ": " + .contents] | reverse[]'))
# timelist=($(curl -s $chatURL | jq -r '[.result.recentManagerCommentList[] | .regTime] | reverse[]'))
if [ "$managerOnly" = 1 ]
then
if [ -z $notFirst ] && [ "$STATUS" = "END" ]
then
chatList=($(curl -s $chatURL | jq -r '[.result.recentManagerCommentList[] | "[" + .regTime + "] " + .userName + ": " + .contents] | reverse[]'))
else
chatList=($(curl -s $chatURL | jq -r '[.result.commentList[] | select(.manager == true) | "[" + .regTime + "] " + .userName + ": " + .contents] | reverse[]'))
fi
elif [ "$managerOnly" = 0 ]
then
chatList=($(curl -s $chatURL | jq -r '[.result.commentList[] | "[" + .regTime + "] " + .userName + ": " + .contents] | reverse[]'))
fi
cumulatedList=(${cumulatedList[@]} ${chatList[@]})
if [ ${#cumulatedList[@]} -lt 20 ]
then
chatArrayStart=0
else
chatArrayStart=$[${#cumulatedList[@]} - 20]
fi
if [ -z $notFirst ]
then
sortedList=($(printf "%s\n" "${cumulatedList[@]}" | sort -u))
fi
}
function show_chat()
{
while :
do
get_chat
if [ "$notFirst" = 1 ]
then
unset sortedList listToPrint
for (( i = $chatArrayStart; i < ${#cumulatedList[@]}; i++ ))
do
sortedList=(${sortedList[@]} ${cumulatedList[$i]})
done
listToPrint=($(printf "%s\n" "${sortedList[@]}" | sort -u))
printf "%s\n" "${listToPrint[@]}"
else
if [ -z $notFirst ] && [ "$STATUS" != "ONAIR" ] && [ "${#sortedList[@]}" != 0 ]
then
if [ "$managerOnly" = 1 ]
then
msg "Last ${#sortedList[@]} manager chat(s) saved in server:\n"
elif [ "$managerOnly" = 0 ]
then
msg "Last ${#sortedList[@]} chat(s) saved in server:\n"
fi
printf "%s\n" "${sortedList[@]}"
break
fi
if [ "$managerOnly" = 1 ]
then
msg "Getting manager chat messages every $chatCheckInterval seconds\n"
elif [ "$managerOnly" = 0 ]
then
msg "Getting every chat messages every $chatCheckInterval seconds\n"
fi
if [ "${#sortedList[@]}" != 0 ]
then
printf "%s\n" "${sortedList[@]}"
fi
fi
get_status
if [ "$STATUS" = "END" ]
then
break
fi
sleep $chatCheckInterval
notFirst=1
done
if [ ${#sortedList[@]} = 0 ]
then
alert_msg -t "Status: $STATUS / No chats found!\n"
exit 0
else
echo
sortedList=($(printf "%s\n" "${cumulatedList[@]}" | sort -u))
info_msg -t "Status: $STATUS (cumulatedList: ${#cumulatedList[@]} / sortedList: ${#sortedList[@]})\n"
if [ "$managerOnly" = 1 ]
then
chatOutPath="${OPATH}/chat/${SHOW_ID}_${d_date}_chat.txt"
elif [ "$managerOnly" = 0 ]
then
chatOutPath="${OPATH}/chat/${SHOW_ID}_${d_date}_chat_all.txt"
fi
n=0
for (( i = 0; i < ${#sortedList[@]}; i++ ))
do
echo "${sortedList[$n]}" >> $chatOutPath
((n++))
done
echo -e "\n[$(date +'%x %T')] Status: $STATUS (cumulatedList: ${#cumulatedList[@]} / sortedList: ${#sortedList[@]})\n" >> $chatOutPath
exit 0
fi
}
function contentget()
{
"${wget_c[@]}" -O "${OPATH}/content/${SHOW_ID}_${d_date}_livestatus.json" ${NOW_LINK}/${SHOW_ID}/livestatus
"${wget_c[@]}" -O "${OPATH}/content/${SHOW_ID}_${d_date}_content.json" ${NOW_LINK}/${SHOW_ID}/content
if [ -z $ITG_CHECK ]
then
ctlength=$(wc -c "${OPATH}/content/${SHOW_ID}_${d_date}_content.json" | awk '{print $1}')
lslength=$(wc -c "${OPATH}/content/${SHOW_ID}_${d_date}_livestatus.json" | awk '{print $1}')
msg "content: $ctlength Bytes / livestatus: $lslength Bytes"
if [ "$ctlength" -lt 1500 ] && [ "$lslength" -lt 1000 ]
then
if [ "$MAXRETRY" = "0" ]
then
err_msg "content/livestatus 파일이 올바르지 않음, 스크립트 종료\n"
content_backup
exit 1
fi
alert_msg "content/livestatus 파일이 올바르지 않음, 다시 시도합니다"
while :
do
((CTRETRY++))
msg "\n재시도 횟수: $CTRETRY / 최대 재시도 횟수: $MAXRETRY\n"
"${wget_c[@]}" -O "${OPATH}/content/${SHOW_ID}_${d_date}_livestatus.json" ${NOW_LINK}/${SHOW_ID}/livestatus
"${wget_c[@]}" -O "${OPATH}/content/${SHOW_ID}_${d_date}_content.json" ${NOW_LINK}/${SHOW_ID}/content
ctlength=$(wc -c "${OPATH}/content/${SHOW_ID}_${d_date}_content.json" | awk '{print $1}')
lslength=$(wc -c "${OPATH}/content/${SHOW_ID}_${d_date}_livestatus.json" | awk '{print $1}')
msg "content: $ctlength Bytes / livestatus: $lslength Bytes"
if [ "$ctlength" -lt 1500 ] && [ "$lslength" -lt 1000 ]
then
if [ "$CTRETRY" -lt "$MAXRETRY" ]
then
alert_msg "content/livestatus 파일이 올바르지 않음, 다시 시도합니다"
elif [ "$CTRETRY" -ge "$MAXRETRY" ]
then
err_msg "최대 재시도 횟수($MAXRETRY회) 도달, 스크립트 종료\n"
content_backup
exit 1
else
err_msg "\nERROR: contentget(): CTRETRY,MAXRETRY\n"
content_backup
exit 1
fi
elif [ "$ctlength" -ge 1500 ] && [ "$lslength" -ge 1000 ]
then
info_msg "정상 content/livestatus 파일\n"
break
else
err_msg "\nERROR: contentget(): ctlength 1\n"
content_backup
exit 1
fi
done
elif [ "$ctlength" -ge 1500 ] && [ "$lslength" -ge 1000 ]
then
info_msg "정상 content/livestatus 파일\n"
else
err_msg "\nERROR: contentget(): ctlength 2\n"
content_backup
exit 1
fi
CTRETRY=0
else
alert_msg "Passed integrity check!"
fi
}
function content_backup()
{
timeupdate
mv "${OPATH}/content/${SHOW_ID}_${d_date}_content.json" "${OPATH}/content/_ERR_${SHOW_ID}_${d_date}_${CTIME}_content.json"
mv "${OPATH}/content/${SHOW_ID}_${d_date}_livestatus.json" "${OPATH}/content/_ERR_${SHOW_ID}_${d_date}_${CTIME}_livestatus.json"
}
function getstream()
{
SREASON="$1"
if [ $RETRY = 0 ]
then
INFO=$(jq -r .contentList[].description.text "${OPATH}/content/${SHOW_ID}_${d_date}_content.json")
echo -e "Host: ${showhost}\nEP: $ep\n\n$subject\n\n$INFO" > "${OPATH}/show/$title/${d_date}_${showhost}_Info.txt"
fi
msg "\n방송시간: $starttime / 현재: $CTIME\n$title By ${showhost} E$ep $subject\n${OPATH}/show/$title/${FILENAME}.ts\n${url}\n"
#-ERROR-CHECK------------------------------------------------------
msg -t "Checking URL..."
curl -fsS "${url}" > /dev/null 2>&1 & CURLPID=$!
wait $CURLPID; ExitCode=$?
if [ $ExitCode = 0 ]
then
info_msg -t "Valid URL, Proceeding..."
"${ffmpeg_c[@]}" -y -headers 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3625.2 Safari/537.36? Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7? Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8? Accept-Encoding: gzip, deflate? Accept-Language: en-us,en;q=0.5?' -i "${url}" -c copy -f mpegts file:"${OPATH}/show/$title/${FILENAME}.ts" & FPID=$!
else
err_msg -t "Invalid URL, retrying...\n"
contentget
exrefresh
timeupdate
getstream "URL_RETRY"
fi
#-ERROR-CHECK------------------------------------------------------
while [[ $(ps -p $FPID 2>/dev/null | awk 'FNR == 2 {print $4}') != 'ffmpeg' ]]
do
echo -en "[$(date +'%x %T')] Waiting for ffmpeg to start...\r"
sleep 1
done
msg -t "Download Started, checking stream status every ${YLW}$CHKINT${NC} seconds\n"
sleep $CHKINT
while :
do
INITSIZE=$(wc -c "${OPATH}/show/$title/${FILENAME}.ts" 2>/dev/null | cut -d ' ' -f 1)
sleep $CHKINT
POSTSIZE=$(wc -c "${OPATH}/show/$title/${FILENAME}.ts" 2>/dev/null | cut -d ' ' -f 1)
if [ -t 1 ]
then
tput el
fi
msg -t "INIT: ${YLW}$INITSIZE${NC} Bytes / POST: ${GRN}$POSTSIZE${NC} Bytes"
get_status
if [ -t 1 ]
then
tput el
fi
if [ "$STATUS" = 'ONAIR' ]
then
msg -t "Show Status: ${RED}$STATUS${NC}"
if [ -t 1 ]
then
tput cuu 2
fi
if [[ $INITSIZE -eq $POSTSIZE ]]
then
if [ -t 1 ]
then
tput cud 2
fi
if [ "$(ps -p $FPID 2>/dev/null | awk 'FNR == 2 {print $4}')" = 'ffmpeg' ]
then
alert_msg -t "Download stalled, but show is still ONAIR!\n"
elif [ "$(ps -p $FPID 2>/dev/null | awk 'FNR == 2 {print $4}')" != 'ffmpeg' ]
then
if [ "$MAXRETRY" = "0" ]
then
echo
err_msg -t "getstream(): 다운로드 실패, 스크립트 종료\n"
content_backup
exit 1
fi
if [ "$RETRY" != "0" ]
then
echo
msg -t "재시도 횟수: $RETRY / 최대 재시도 횟수: $MAXRETRY"
fi
if [ -z "$RETRY" ] || [ "$RETRY" -lt "$MAXRETRY" ]
then
((RETRY++))
err_msg -t "$CHKINT초 동안 다운로드 중단됨, 다시 시도합니다\n"
kill $FPID 2>/dev/null
content_backup
contentget
exrefresh
timeupdate
getstream RETRY
elif [ "$RETRY" -ge "$MAXRETRY" ]
then
echo
err_msg -t "getstream(): 다운로드 실패\n최대 재시도 횟수($MAXRETRY회) 도달, 스크립트 종료\n"
content_backup
exit 1
else
echo
err_msg -t "ERROR: getstream(): RETRY($RETRY/$MAXRETRY)\n"
content_backup
exit 1
fi
fi
fi
elif [ "$STATUS" != 'ONAIR' ]
then
if [ -z "$STATUS" ]
then
echo
alert_msg -t "WARNING: Invalid status, retrying..."
else
msg -t "Show Status: ${YLW}$STATUS${NC}"
msg -t "스트리밍 종료됨, 총 재시도 횟수: $RETRY"
break
fi
fi
done
convert
}
function convert()
{
codec=$(ffprobe -v error -show_streams -select_streams a "${OPATH}/show/$title/${FILENAME}.ts" | grep -oP 'codec_name=\K[^+]*')
if [ "$vcheck" = 'true' ]
then
alert_msg "\nFound video stream, passed audio converting... ($codec)"
msg "Download Complete: ${OPATH}/show/$title/${FILENAME}.ts"
elif [ "$vcheck" != 'true' ]
then
if [ "$codec" = 'mp3' ]
then
msg "\nCodec: MP3, Saving into mp3 file"
"${ffmpeg_c[@]}" -i "${OPATH}/show/$title/${FILENAME}.ts" -vn -c:a copy "${OPATH}/show/$title/${FILENAME}.mp3"
msg "Convert Complete: ${OPATH}/show/$title/${FILENAME}.mp3"
elif [ "$codec" = 'aac' ]
then
msg "\nCodec: AAC, Saving into m4a file"
"${ffmpeg_c[@]}" -i "${OPATH}/show/$title/${FILENAME}.ts" -vn -c:a copy "${OPATH}/show/$title/${FILENAME}.m4a"
msg "Convert Complete: ${OPATH}/show/$title/${FILENAME}.m4a"
else
err_msg "\nERROR: Unidentified Codec ($codec)"
content_backup
exit 1
fi
if [ -z "$KEEP" ]
then
rm "${OPATH}/show/$title/${FILENAME}.ts"
fi
fi
total_user=$(curl -s ${NOW_LINK}/${SHOW_ID}/livestatus | jq -r .status.indicator.cumulativeUserCount)
msg "\n오늘 총 조회수: $total_user"
info_msg "\nJob Finished, Code: $SREASON\n"
exit 0 ### SCRIPT FINISH
}
function renamer()
{
str="$1"
str=${str//'"'/''}
str=${str//'\r\n'/' '}
str=${str//'\'/''}
export $2="$str"
}
function exrefresh()
{
unset url title startdate starttime
content=$(cat "${OPATH}/content/${SHOW_ID}_${d_date}_content.json")
livestatus=$(cat "${OPATH}/content/${SHOW_ID}_${d_date}_livestatus.json")
showhost=$(echo "${content}" | jq -r '.contentList[] | (.hosts | join(", "))')
vcheck=$(echo "${content}" | jq -r .contentList[].video)
title=$(echo "${content}" | jq -r .contentList[].home.title.text)
if [ ${vcheck} == 'true' ]
then
url=$(echo "${content}" | jq -r .contentList[].videoStreamUrl)
else
url=$(echo "${content}" | jq -r .contentList[].streamUrl)
fi
# Seconds since 1970-01-01 00:00:00 UTC
ORI_DATE=$(echo "${content}" | jq -r .contentList[].start | grep -Eo '[0-9]{1,10}' | head -n 1)
# ORI_DATE=$(echo "${ORI_DATE:0:10}") # Seconds since 1970-01-01 00:00:00 UTC
startdate=$(date -d @$ORI_DATE +'%y%m%d')
starttime=$(date -d @$ORI_DATE +'%H%M%S')
subject=$(echo "${content}" | jq .contentList[].title.text)
ep=$(echo "${content}" | jq -r .contentList[].count | grep -Eo '[0-9]{1,}')
STATUS=$(echo "${livestatus}" | jq -r .status.status) # READY | END | ONAIR
renamer "${subject}" subject
if [ -z "$G_USR" ]
then
if [ -z "${url}" ] || [ -z "$title" ] || [ -z "$startdate" ] || [ -z "$starttime" ] || [ -z "$STATUS" ]
then
if [ "$MAXRETRY" = "0" ]
then
err_msg "\nexrefresh(): 정보 업데이트 실패, 스크립트 종료\n"
content_backup
exit 1
fi
if [ "$EXRETRY" != "0" ]
then
echo -e "\n재시도 횟수: $EXRETRY / 최대 재시도 횟수: $MAXRETRY"
fi
if [ -z "$EXRETRY" ] || [ "$EXRETRY" -lt "$MAXRETRY" ]
then
err_msg "정보 업데이트 실패, 재시도 합니다"
((EXRETRY++))
elif [ "$EXRETRY" -ge "$MAXRETRY" ]
then
err_msg "\nexrefresh(): 정보 업데이트 실패\n최대 재시도 횟수($MAXRETRY회) 도달, 스크립트 종료\n"
content_backup
exit 1
else
err_msg "\nERROR: exrefresh(): EXRETRY\n"
content_backup
exit 1
fi
msg "\nSTARTDATE: $startdate\nSTARTTIME: $starttime\nTITLE:$title\nURL:${url}\n"
msg "Retrying...\n"
contentget
exrefresh
fi
EXRETRY=0
fi
alert_msg "Show Info variables refreshed"
}
function timeupdate()
{
d_date=$(date +'%y%m%d')
CTIME=$(date +'%H%M%S')
TIMECHECK=$(echo "($(date -d @$ORI_DATE +%H)*60+$(date -d @$ORI_DATE +%M))-($(date +%H)*60+$(date +%M))" | bc)
if [ "$vcheck" = 'true' ]
then
FILENAME="${d_date}.NAVER NOW.$title.E$ep.${subject}_VID_$CTIME"
else
FILENAME="${d_date}.NAVER NOW.$title.E$ep.${subject}_$CTIME"
fi
FILENAME=${FILENAME//'w/'/'with'}
FILENAME=${FILENAME//'%'/'%%'}
FILENAME=${FILENAME//'\'/''}
alert_msg "Time variables refreshed"
}
function get_status()
{
STATUS=$(curl -s ${NOW_LINK}/${SHOW_ID}/livestatus | jq -r .status.status)
}
function counter()
{
TIMER=$1
if [ "$TIMER" -gt 0 ]
then
echo
echo "$TIMER초 동안 대기합니다"
while [ "$TIMER" -gt 0 ]
do
if [ -t 1 ]
then
tput cuu1;tput el
echo "$TIMER초 동안 대기합니다"
fi
sleep 1
((TIMER--))
done
echo
fi
unset TIMER
}
function onairwait()
{
W_TIMER=0
FIRST=1
while [ "$STATUS" != "ONAIR" ]
do
if [ "$TIMECHECK" -le -15 ]
then
bannerList=$(curl -s ${NOW_LINK}/bannertable)
line=$(echo "${bannerList}" | jq .contentList[].banners[].contentId \
| grep -n ${SHOW_ID} | cut -d : -f 1)
b_day=$(echo "${bannerList}" | jq -r .contentList[].banners[].time \
| awk -v var=$line 'FNR == var')
err_msg "\nERROR: 시작시간과 15분 이상 차이 발생\n금일 방송 유무를 확인해주세요"
msg "\n쇼 이름: $title\n방송 시간: $b_day (KST)\n"
content_backup
exit 1
fi
get_status
if [ -t 1 ] && [ $FIRST != 1 ]
then
for ((n = 1; n <= 6; n++))
do
tput cuu1; tput el
done
fi
[ $FIRST = 1 ] && echo # for better logging
timeupdate
msg -t "Time difference: $TIMECHECK min"
if [ "$STATUS" = "ONAIR" ]
then
msg -t "Live Status: ${RED}$STATUS${NC}\n"
unset FIRST
break
else
msg -t "Live Status: ${YLW}$STATUS${NC}"
fi
FIRST=0
if [ "$TIMECHECK" -ge 65 ]
then
W_TIMER=3600
elif [ "$TIMECHECK" -lt 65 ] # 시작 시간이 65분 미만 차이
then
if [ "$TIMECHECK" -gt 13 ] # 시작 시간이 13분 초과 차이
then
W_TIMER=600
elif [ "$TIMECHECK" -le 13 ] # 시작 시간이 13분 이하 차이
then
if [ "$TIMECHECK" -gt 3 ] # 시작 시간이 3분 초과 차이
then
W_TIMER=60
elif [ "$TIMECHECK" -le 3 ] # 시작 시간이 3분 이하 차이
then
W_TIMER=1
fi
fi
fi
counter "$W_TIMER"
done
}
function main()
{
contentget
exrefresh
timeupdate
if [ ! -d "${OPATH}/show/$title" ]
then
mkdir -p "${OPATH}/show/$title"
fi