[vlive] Add CH+ support (closes #16887)
[youtube-dl] / youtube_dl / extractor / vlive.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import time
6 import itertools
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_urllib_parse_urlencode,
11     compat_str,
12 )
13 from ..utils import (
14     dict_get,
15     ExtractorError,
16     float_or_none,
17     int_or_none,
18     remove_start,
19     try_get,
20     urlencode_postdata,
21 )
22
23
24 class VLiveIE(InfoExtractor):
25     IE_NAME = 'vlive'
26     _VALID_URL = r'https?://(?:(?:www|m)\.)?vlive\.tv/video/(?P<id>[0-9]+)'
27     _NETRC_MACHINE = 'vlive'
28     _TESTS = [{
29         'url': 'http://www.vlive.tv/video/1326',
30         'md5': 'cc7314812855ce56de70a06a27314983',
31         'info_dict': {
32             'id': '1326',
33             'ext': 'mp4',
34             'title': "[V LIVE] Girl's Day's Broadcast",
35             'creator': "Girl's Day",
36             'view_count': int,
37         },
38     }, {
39         'url': 'http://www.vlive.tv/video/16937',
40         'info_dict': {
41             'id': '16937',
42             'ext': 'mp4',
43             'title': '[V LIVE] 첸백시 걍방',
44             'creator': 'EXO',
45             'view_count': int,
46             'subtitles': 'mincount:12',
47         },
48         'params': {
49             'skip_download': True,
50         },
51     }, {
52         'url': 'https://www.vlive.tv/video/129100',
53         'md5': 'ca2569453b79d66e5b919e5d308bff6b',
54         'info_dict': {
55             'id': '129100',
56             'ext': 'mp4',
57             'title': "[V LIVE] [BTS+] Run BTS! 2019 - EP.71 :: Behind the scene",
58             'creator': "BTS+",
59             'view_count': int,
60             'subtitles': 'mincount:10',
61         },
62         'skip': 'This video is only available for CH+ subscribers',
63     }]
64
65     @classmethod
66     def suitable(cls, url):
67         return False if VLivePlaylistIE.suitable(url) else super(VLiveIE, cls).suitable(url)
68
69     def _real_initialize(self):
70         self._login()
71
72     def _login(self):
73         email, password = self._get_login_info()
74         if None in (email, password):
75             return
76
77         def is_logged_in():
78             login_info = self._download_json(
79                 'https://www.vlive.tv/auth/loginInfo', None,
80                 note='Downloading login info',
81                 headers={'Referer': 'https://www.vlive.tv/home'})
82
83             return try_get(login_info,
84                            lambda x: x['message']['login'], bool) or False
85
86         if is_logged_in():
87             return
88
89         LOGIN_URL = 'https://www.vlive.tv/auth/email/login'
90         self._request_webpage(LOGIN_URL, None,
91                               note='Downloading login cookies')
92
93         self._download_webpage(
94             LOGIN_URL, None, note='Logging in',
95             data=urlencode_postdata({'email': email, 'pwd': password}),
96             headers={
97                 'Referer': LOGIN_URL,
98                 'Content-Type': 'application/x-www-form-urlencoded'
99             })
100
101         if not is_logged_in():
102             raise ExtractorError('Unable to log in', expected=True)
103
104     def _real_extract(self, url):
105         video_id = self._match_id(url)
106
107         webpage = self._download_webpage(
108             'https://www.vlive.tv/video/%s' % video_id, video_id)
109
110         VIDEO_PARAMS_RE = r'\bvlive\.video\.init\(([^)]+)'
111         VIDEO_PARAMS_FIELD = 'video params'
112
113         params = self._parse_json(self._search_regex(
114             VIDEO_PARAMS_RE, webpage, VIDEO_PARAMS_FIELD, default=''), video_id,
115             transform_source=lambda s: '[' + s + ']', fatal=False)
116
117         if not params or len(params) < 7:
118             params = self._search_regex(
119                 VIDEO_PARAMS_RE, webpage, VIDEO_PARAMS_FIELD)
120             params = [p.strip(r'"') for p in re.split(r'\s*,\s*', params)]
121
122         status, long_video_id, key = params[2], params[5], params[6]
123         status = remove_start(status, 'PRODUCT_')
124
125         if status in ('LIVE_ON_AIR', 'BIG_EVENT_ON_AIR'):
126             return self._live(video_id, webpage)
127         elif status in ('VOD_ON_AIR', 'BIG_EVENT_INTRO'):
128             return self._replay(video_id, webpage, long_video_id, key)
129
130         if status == 'LIVE_END':
131             raise ExtractorError('Uploading for replay. Please wait...',
132                                  expected=True)
133         elif status == 'COMING_SOON':
134             raise ExtractorError('Coming soon!', expected=True)
135         elif status == 'CANCELED':
136             raise ExtractorError('We are sorry, '
137                                  'but the live broadcast has been canceled.',
138                                  expected=True)
139         elif status == 'ONLY_APP':
140             raise ExtractorError('Unsupported video type', expected=True)
141         else:
142             raise ExtractorError('Unknown status %s' % status)
143
144     def _get_common_fields(self, webpage):
145         title = self._og_search_title(webpage)
146         creator = self._html_search_regex(
147             r'<div[^>]+class="info_area"[^>]*>\s*(?:<em[^>]*>.*</em\s*>\s*)?<a\s+[^>]*>([^<]+)',
148             webpage, 'creator', fatal=False)
149         thumbnail = self._og_search_thumbnail(webpage)
150         return {
151             'title': title,
152             'creator': creator,
153             'thumbnail': thumbnail,
154         }
155
156     def _live(self, video_id, webpage):
157         init_page = self._download_init_page(video_id)
158
159         live_params = self._search_regex(
160             r'"liveStreamInfo"\s*:\s*(".*"),',
161             init_page, 'live stream info')
162         live_params = self._parse_json(live_params, video_id)
163         live_params = self._parse_json(live_params, video_id)
164
165         formats = []
166         for vid in live_params.get('resolutions', []):
167             formats.extend(self._extract_m3u8_formats(
168                 vid['cdnUrl'], video_id, 'mp4',
169                 m3u8_id=vid.get('name'),
170                 fatal=False, live=True))
171         self._sort_formats(formats)
172
173         info = self._get_common_fields(webpage)
174         info.update({
175             'title': self._live_title(info['title']),
176             'id': video_id,
177             'formats': formats,
178             'is_live': True,
179         })
180         return info
181
182     def _replay(self, video_id, webpage, long_video_id, key):
183         if '' in (long_video_id, key):
184             init_page = self._download_init_page(video_id)
185             video_info = self._parse_json(self._search_regex(
186                 r'(?s)oVideoStatus\s*=\s*({.*})', init_page, 'video info'),
187                 video_id)
188             if video_info['status'] == 'NEED_CHANNEL_PLUS':
189                 self.raise_login_required(
190                     'This video is only available for CH+ subscribers')
191             long_video_id, key = video_info['vid'], video_info['inkey']
192
193         playinfo = self._download_json(
194             'http://global.apis.naver.com/rmcnmv/rmcnmv/vod_play_videoInfo.json?%s'
195             % compat_urllib_parse_urlencode({
196                 'videoId': long_video_id,
197                 'key': key,
198                 'ptc': 'http',
199                 'doct': 'json',  # document type (xml or json)
200                 'cpt': 'vtt',  # captions type (vtt or ttml)
201             }), video_id)
202
203         formats = [{
204             'url': vid['source'],
205             'format_id': vid.get('encodingOption', {}).get('name'),
206             'abr': float_or_none(vid.get('bitrate', {}).get('audio')),
207             'vbr': float_or_none(vid.get('bitrate', {}).get('video')),
208             'width': int_or_none(vid.get('encodingOption', {}).get('width')),
209             'height': int_or_none(vid.get('encodingOption', {}).get('height')),
210             'filesize': int_or_none(vid.get('size')),
211         } for vid in playinfo.get('videos', {}).get('list', []) if vid.get('source')]
212         self._sort_formats(formats)
213
214         view_count = int_or_none(playinfo.get('meta', {}).get('count'))
215
216         subtitles = {}
217         for caption in playinfo.get('captions', {}).get('list', []):
218             lang = dict_get(caption, ('locale', 'language', 'country', 'label'))
219             if lang and caption.get('source'):
220                 subtitles[lang] = [{
221                     'ext': 'vtt',
222                     'url': caption['source']}]
223
224         info = self._get_common_fields(webpage)
225         info.update({
226             'id': video_id,
227             'formats': formats,
228             'view_count': view_count,
229             'subtitles': subtitles,
230         })
231         return info
232
233     def _download_init_page(self, video_id):
234         return self._download_webpage(
235             'https://www.vlive.tv/video/init/view',
236             video_id, note='Downloading live webpage',
237             data=urlencode_postdata({'videoSeq': video_id}),
238             headers={
239                 'Referer': 'https://www.vlive.tv/video/%s' % video_id,
240                 'Content-Type': 'application/x-www-form-urlencoded'
241             })
242
243
244 class VLiveChannelIE(InfoExtractor):
245     IE_NAME = 'vlive:channel'
246     _VALID_URL = r'https?://channels\.vlive\.tv/(?P<id>[0-9A-Z]+)'
247     _TEST = {
248         'url': 'http://channels.vlive.tv/FCD4B',
249         'info_dict': {
250             'id': 'FCD4B',
251             'title': 'MAMAMOO',
252         },
253         'playlist_mincount': 110
254     }
255     _APP_ID = '8c6cc7b45d2568fb668be6e05b6e5a3b'
256
257     def _real_extract(self, url):
258         channel_code = self._match_id(url)
259
260         webpage = self._download_webpage(
261             'http://channels.vlive.tv/%s/video' % channel_code, channel_code)
262
263         app_id = None
264
265         app_js_url = self._search_regex(
266             r'<script[^>]+src=(["\'])(?P<url>http.+?/app\.js.*?)\1',
267             webpage, 'app js', default=None, group='url')
268
269         if app_js_url:
270             app_js = self._download_webpage(
271                 app_js_url, channel_code, 'Downloading app JS', fatal=False)
272             if app_js:
273                 app_id = self._search_regex(
274                     r'Global\.VFAN_APP_ID\s*=\s*[\'"]([^\'"]+)[\'"]',
275                     app_js, 'app id', default=None)
276
277         app_id = app_id or self._APP_ID
278
279         channel_info = self._download_json(
280             'http://api.vfan.vlive.tv/vproxy/channelplus/decodeChannelCode',
281             channel_code, note='Downloading decode channel code',
282             query={
283                 'app_id': app_id,
284                 'channelCode': channel_code,
285                 '_': int(time.time())
286             })
287
288         channel_seq = channel_info['result']['channelSeq']
289         channel_name = None
290         entries = []
291
292         for page_num in itertools.count(1):
293             video_list = self._download_json(
294                 'http://api.vfan.vlive.tv/vproxy/channelplus/getChannelVideoList',
295                 channel_code, note='Downloading channel list page #%d' % page_num,
296                 query={
297                     'app_id': app_id,
298                     'channelSeq': channel_seq,
299                     # Large values of maxNumOfRows (~300 or above) may cause
300                     # empty responses (see [1]), e.g. this happens for [2] that
301                     # has more than 300 videos.
302                     # 1. https://github.com/ytdl-org/youtube-dl/issues/13830
303                     # 2. http://channels.vlive.tv/EDBF.
304                     'maxNumOfRows': 100,
305                     '_': int(time.time()),
306                     'pageNo': page_num
307                 }
308             )
309
310             if not channel_name:
311                 channel_name = try_get(
312                     video_list,
313                     lambda x: x['result']['channelInfo']['channelName'],
314                     compat_str)
315
316             videos = try_get(
317                 video_list, lambda x: x['result']['videoList'], list)
318             if not videos:
319                 break
320
321             for video in videos:
322                 video_id = video.get('videoSeq')
323                 if not video_id:
324                     continue
325                 video_id = compat_str(video_id)
326                 entries.append(
327                     self.url_result(
328                         'http://www.vlive.tv/video/%s' % video_id,
329                         ie=VLiveIE.ie_key(), video_id=video_id))
330
331         return self.playlist_result(
332             entries, channel_code, channel_name)
333
334
335 class VLivePlaylistIE(InfoExtractor):
336     IE_NAME = 'vlive:playlist'
337     _VALID_URL = r'https?://(?:(?:www|m)\.)?vlive\.tv/video/(?P<video_id>[0-9]+)/playlist/(?P<id>[0-9]+)'
338     _TEST = {
339         'url': 'http://www.vlive.tv/video/22867/playlist/22912',
340         'info_dict': {
341             'id': '22912',
342             'title': 'Valentine Day Message from TWICE'
343         },
344         'playlist_mincount': 9
345     }
346
347     def _real_extract(self, url):
348         mobj = re.match(self._VALID_URL, url)
349         video_id, playlist_id = mobj.group('video_id', 'id')
350
351         VIDEO_URL_TEMPLATE = 'http://www.vlive.tv/video/%s'
352         if self._downloader.params.get('noplaylist'):
353             self.to_screen(
354                 'Downloading just video %s because of --no-playlist' % video_id)
355             return self.url_result(
356                 VIDEO_URL_TEMPLATE % video_id,
357                 ie=VLiveIE.ie_key(), video_id=video_id)
358
359         self.to_screen(
360             'Downloading playlist %s - add --no-playlist to just download video'
361             % playlist_id)
362
363         webpage = self._download_webpage(
364             'http://www.vlive.tv/video/%s/playlist/%s'
365             % (video_id, playlist_id), playlist_id)
366
367         item_ids = self._parse_json(
368             self._search_regex(
369                 r'playlistVideoSeqs\s*=\s*(\[[^]]+\])', webpage,
370                 'playlist video seqs'),
371             playlist_id)
372
373         entries = [
374             self.url_result(
375                 VIDEO_URL_TEMPLATE % item_id, ie=VLiveIE.ie_key(),
376                 video_id=compat_str(item_id))
377             for item_id in item_ids]
378
379         playlist_name = self._html_search_regex(
380             r'<div[^>]+class="[^"]*multicam_playlist[^>]*>\s*<h3[^>]+>([^<]+)',
381             webpage, 'playlist title', fatal=False)
382
383         return self.playlist_result(entries, playlist_id, playlist_name)