[vlive] Update extraction
[youtube-dl] / youtube_dl / extractor / vlive.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     dict_get,
9     ExtractorError,
10     float_or_none,
11     int_or_none,
12     remove_start,
13 )
14 from ..compat import compat_urllib_parse_urlencode
15
16
17 class VLiveIE(InfoExtractor):
18     IE_NAME = 'vlive'
19     _VALID_URL = r'https?://(?:(?:www|m)\.)?vlive\.tv/video/(?P<id>[0-9]+)'
20     _TESTS = [{
21         'url': 'http://www.vlive.tv/video/1326',
22         'md5': 'cc7314812855ce56de70a06a27314983',
23         'info_dict': {
24             'id': '1326',
25             'ext': 'mp4',
26             'title': "[V LIVE] Girl's Day's Broadcast",
27             'creator': "Girl's Day",
28             'view_count': int,
29         },
30     }, {
31         'url': 'http://www.vlive.tv/video/16937',
32         'info_dict': {
33             'id': '16937',
34             'ext': 'mp4',
35             'title': '[V LIVE] 첸백시 걍방',
36             'creator': 'EXO',
37             'view_count': int,
38             'subtitles': 'mincount:12',
39         },
40         'params': {
41             'skip_download': True,
42         },
43     }]
44
45     def _real_extract(self, url):
46         video_id = self._match_id(url)
47
48         webpage = self._download_webpage(
49             'http://www.vlive.tv/video/%s' % video_id, video_id)
50
51         video_params = self._parse_json(self._search_regex(
52             r'\bvlive\.video\.init\(([^)]+)\);',
53             webpage, 'video params'), video_id,
54             transform_source=lambda s: '[' + s + ']')
55
56         status, long_video_id, key = video_params[2], video_params[5], video_params[6]
57         status = remove_start(status, 'PRODUCT_')
58
59         if status == 'LIVE_ON_AIR' or status == 'BIG_EVENT_ON_AIR':
60             return self._live(video_id, webpage)
61         elif status == 'VOD_ON_AIR' or status == 'BIG_EVENT_INTRO':
62             if long_video_id and key:
63                 return self._replay(video_id, webpage, long_video_id, key)
64             else:
65                 status = 'COMING_SOON'
66
67         if status == 'LIVE_END':
68             raise ExtractorError('Uploading for replay. Please wait...',
69                                  expected=True)
70         elif status == 'COMING_SOON':
71             raise ExtractorError('Coming soon!', expected=True)
72         elif status == 'CANCELED':
73             raise ExtractorError('We are sorry, '
74                                  'but the live broadcast has been canceled.',
75                                  expected=True)
76         else:
77             raise ExtractorError('Unknown status %s' % status)
78
79     def _get_common_fields(self, webpage):
80         title = self._og_search_title(webpage)
81         creator = self._html_search_regex(
82             r'<div[^>]+class="info_area"[^>]*>\s*<a\s+[^>]*>([^<]+)',
83             webpage, 'creator', fatal=False)
84         thumbnail = self._og_search_thumbnail(webpage)
85         return {
86             'title': title,
87             'creator': creator,
88             'thumbnail': thumbnail,
89         }
90
91     def _live(self, video_id, webpage):
92         init_page = self._download_webpage(
93             'http://www.vlive.tv/video/init/view',
94             video_id, data="videoSeq=%s" % video_id, headers={
95                 'Referer': 'http://www.vlive.tv/video/%s' % video_id,
96                 'Content-Type': 'application/x-www-form-urlencoded'
97             })
98
99         live_params = self._search_regex(
100             r'"liveStreamInfo"\s*:\s*(".*"),',
101             init_page, 'video params')
102         live_params = self._parse_json(live_params, video_id)
103         live_params = self._parse_json(live_params, video_id)
104
105         formats = []
106         for vid in live_params.get('resolutions', []):
107             formats.extend(self._extract_m3u8_formats(
108                 vid['cdnUrl'], video_id, 'mp4',
109                 m3u8_id=vid.get('name'),
110                 fatal=False, live=True))
111         self._sort_formats(formats)
112
113         return dict(self._get_common_fields(webpage),
114                     id=video_id,
115                     formats=formats,
116                     is_live=True)
117
118     def _replay(self, video_id, webpage, long_video_id, key):
119         playinfo = self._download_json(
120             'http://global.apis.naver.com/rmcnmv/rmcnmv/vod_play_videoInfo.json?%s'
121             % compat_urllib_parse_urlencode({
122                 'videoId': long_video_id,
123                 'key': key,
124                 'ptc': 'http',
125                 'doct': 'json',  # document type (xml or json)
126                 'cpt': 'vtt',  # captions type (vtt or ttml)
127             }), video_id)
128
129         formats = [{
130             'url': vid['source'],
131             'format_id': vid.get('encodingOption', {}).get('name'),
132             'abr': float_or_none(vid.get('bitrate', {}).get('audio')),
133             'vbr': float_or_none(vid.get('bitrate', {}).get('video')),
134             'width': int_or_none(vid.get('encodingOption', {}).get('width')),
135             'height': int_or_none(vid.get('encodingOption', {}).get('height')),
136             'filesize': int_or_none(vid.get('size')),
137         } for vid in playinfo.get('videos', {}).get('list', []) if vid.get('source')]
138         self._sort_formats(formats)
139
140         view_count = int_or_none(playinfo.get('meta', {}).get('count'))
141
142         subtitles = {}
143         for caption in playinfo.get('captions', {}).get('list', []):
144             lang = dict_get(caption, ('locale', 'language', 'country', 'label'))
145             if lang and caption.get('source'):
146                 subtitles[lang] = [{
147                     'ext': 'vtt',
148                     'url': caption['source']}]
149
150         return dict(self._get_common_fields(webpage),
151                     id=video_id,
152                     formats=formats,
153                     view_count=view_count,
154                     subtitles=subtitles)