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.py
More file actions
258 lines (218 loc) · 8.52 KB
/
Copy pathnow.py
File metadata and controls
258 lines (218 loc) · 8.52 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
import urllib.error
import argparse
import time
import json
import ffmpeg
import sys
import os.path
version = '22.09.17.1'
now_link = 'https://apis.naver.com/now_web/oldnow_web/v4/stream/'
bannertable_link = now_link.replace("stream/", "upcoming-shows")
livelist_link = now_link.replace("stream/", "naver-main/on-air")
def renamer(string):
# ¨ ¤ ø ; « » ¿ ÷ ¦ -> UTF-8
# “ ⁎ ∕ ꞉ < > ? ⧵ ⏐ -> UTF-16
# https://mythofechelon.co.uk/blog/2020/3/6/how-to-work-around-windows-restricted-characters
if sys.platform == 'win32':
invalid_char = {'"': '“', '*': '⁎', '/': '∕', ':': '꞉',
'<': '<', '>': '>', '?': '?', '\\': '⧵', '|': '⏐'}
elif sys.platform == 'linux':
invalid_char = {'/': '∕'}
for i in string:
if i in invalid_char:
string = string.replace(i, invalid_char.get(i))
return string
def tag_parse(string):
invalid_char = {'\r': '', '\n': ' '}
for i in string:
if i in invalid_char:
string = string.replace(i, invalid_char.get(i))
return string
def get_stream(url, name, path, test=False):
name = renamer(name)
if sys.platform == 'win32':
name = str(path) + '\\' + name
elif sys.platform == 'linux':
name = str(path) + '/' + name
else:
sys.exit('ERROR: Unknown platform (%s)' % sys.platform)
print('Downloading... Press Q or Ctrl+Z to quit.\nOutput: %s.ts' % name)
if test is False:
(
ffmpeg
.input(url)
.output(name+'.ts', c='copy', f='mpegts', map='p:0')
.overwrite_output()
.run(capture_stderr=True)
)
sys.exit()
else:
sys.exit('\n** In Test Run **\nInput URL: %s' % url)
def check_url(url, id, no_msg=False, msg=False, exit=False):
if msg:
text = 'ERROR: ' + msg + ' of show ID %d is not accessible (%d)'
else:
text = 'ERROR: URL of show ID %d is not accessible (%d)'
try:
if not url:
sys.exit(print('ERROR: URL is empty!', file=sys.stderr))
response = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
if no_msg is False:
print(text % (id, e.code), file=sys.stderr)
if exit is True:
sys.exit()
else:
pass
except urllib.error.URLError as e:
if no_msg is False:
print(text % (id, e.reason), file=sys.stderr)
if exit is True:
sys.exit()
else:
pass
else:
return response
def ask_to_proceed(msg, exit=False):
choice = input(msg)
y_list = ('y', 'Y', 'yes', 'Yes', 'YES')
if choice not in y_list:
if exit:
sys.exit(0)
else:
return False
else:
pass
def get_list(live=False):
if live is True:
livelist = check_url(livelist_link, '')
livelist_json = json.loads(livelist.read().decode('utf-8'))
contentId = []
for i in range(len(livelist_json)):
contentId.append(int(livelist_json[i].get('live_no')))
print("Found total %d on-air shows" % len(contentId))
else:
bannertable = check_url(bannertable_link, '')
bannertable_json = json.loads(bannertable.read().decode('utf-8'))
contentId = []
for i in range(len(bannertable_json.get('data'))):
contentId.append(
int(bannertable_json.get('data')[i].get('liveNo')))
print("Found total %d upcoming shows shows" % len(contentId))
contentId.sort()
show_title, show_host, show_name, count = [], [], [], 0
for i in range(len(contentId)):
show_link = now_link + str(contentId[i]) + '/content'
show_json_response = check_url(show_link, contentId[i])
if show_json_response:
show_json = json.loads(show_json_response.read().decode('utf-8'))
show_name.append(show_json.get('contentList')[0].
get('home').get('title').get('text'))
show_host.append(show_json.get('contentList')[0].get('hosts'))
show_title.append(tag_parse(show_json.get(
'contentList')[0].get('title').get('text')))
count += 1
print("Retriving information... (%d/%d)" %
(count, len(contentId)), end='\r')
print('\n')
for i in range(len(contentId)):
print("%d | %s | %s | %s" % (contentId[i], show_name[i],
', '.join(show_host[i]), show_title[i]))
print()
ask_to_proceed('Proceed to download? (Y/N): ', exit=True)
try:
id = int(input('Please enter the show ID to download: '))
except ValueError:
sys.exit('ERROR: Invalid Input')
if id in contentId:
path = os.getcwd()
msg = 'Do you want to download into \'' + str(path) + '\'? (Y/N): '
if ask_to_proceed(msg) is False:
try:
path = os.path.abspath(input('Enter directory to download: '))
print('Overrided download dir: %s' % path)
except ValueError:
sys.exit('ERROR: Invalid Input')
else:
print('Download dir: %s' % path)
print()
main(show_id=id, path=path, test_run=False)
else:
sys.exit('ERROR: Show %d not found' % id)
def main(show_id=None, test_run=False, path=None):
try:
if bool(show_id):
show_link = now_link + str(show_id) + '/content'
except NameError:
show_link = now_link
# content_link = show_link + 'content'
# livestatus_link = show_link + 'livestatus'
show_json_response = check_url(show_link, show_id, exit=True)
if show_json_response:
current_time = time.strftime('%H%M%S')
current_date = time.strftime('%Y%m%d')
show_json = json.loads(show_json_response.read().decode('utf-8'))
show_json = show_json.get('contentList')[0]
hls_url = show_json.get('videoStreamUrl')
if not hls_url:
hls_url = show_json.get('streamUrl')
show_name = show_json.get('home').get('title').get('text')
show_ep = str(show_json.get('count').replace('회', ''))
show_title = tag_parse(show_json.get('title').get('text'))
show_info = show_json.get('description').get('text')
filename = current_date + '.NAVER NOW.' + show_name + \
'.E' + show_ep + '.' + show_title + '_' + current_time
print('\n%s (E%s): %s\n%s\n\n%s\n' %
(show_name, show_ep, show_title, hls_url, show_info))
try:
if bool(print_info):
ask_to_proceed('Proceed to download? (Y/N): ', exit=True)
except NameError:
pass
check_url(hls_url, show_id, msg='m3u8 url', exit=True)
get_stream(hls_url, filename, path, test=test_run)
help_msg = 'Simple NOW Downloader in Python (' + version + ')'
get_msg = 'Print show info or get stream'
list_msg = 'List available shows'
parser = argparse.ArgumentParser(allow_abbrev=False, description=help_msg)
subparser = parser.add_subparsers()
parser_get = subparser.add_parser(
'get', description=get_msg, help=get_msg, allow_abbrev=False)
parser_get.add_argument('show_id', type=int, help='Show ID to download')
parser_get.add_argument('-i', '--info', action='store_true',
help='Print detailed show information')
parser_get.add_argument('-o', '--output-dir', type=os.path.abspath,
nargs='?', help='Set download dir', dest='output')
parser_get.add_argument('--test', action='store_true',
help='Print test information, but do not download')
parser_list = subparser.add_parser(
'list', description=list_msg, help=list_msg, allow_abbrev=False)
parser_list.set_defaults(func=get_list)
parser_list.add_argument('--live', action='store_true',
dest='live', help='List currently shows on air')
args = parser.parse_args()
if hasattr(args, 'func'):
if hasattr(args, 'live'):
get_list(args.live)
else:
get_list()
elif hasattr(args, 'show_id'):
if args.output:
path = args.output
print('Overrided download dir: %s' % path)
else:
path = os.getcwd()
print('Download dir: %s' % path)
if args.info:
print_info = args.info
if args.test:
test_run = args.test
else:
test_run = False
show_id = args.show_id
else:
sys.exit('ERROR: You have to supply get or list option')
main(show_id=show_id, path=path, test_run=test_run)