[niconico] Support HTML5-only videos (closes #13806)
[youtube-dl] / youtube_dl / extractor / niconico.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import datetime
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_parse_qs,
10     compat_urlparse,
11 )
12 from ..utils import (
13     determine_ext,
14     dict_get,
15     ExtractorError,
16     int_or_none,
17     parse_duration,
18     parse_iso8601,
19     try_get,
20     unified_timestamp,
21     urlencode_postdata,
22     xpath_text,
23 )
24
25
26 class NiconicoIE(InfoExtractor):
27     IE_NAME = 'niconico'
28     IE_DESC = 'ニコニコ動画'
29
30     _TESTS = [{
31         'url': 'http://www.nicovideo.jp/watch/sm22312215',
32         'md5': 'd1a75c0823e2f629128c43e1212760f9',
33         'info_dict': {
34             'id': 'sm22312215',
35             'ext': 'mp4',
36             'title': 'Big Buck Bunny',
37             'thumbnail': r're:https?://.*',
38             'uploader': 'takuya0301',
39             'uploader_id': '2698420',
40             'upload_date': '20131123',
41             'timestamp': 1385182762,
42             'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
43             'duration': 33,
44             'view_count': int,
45             'comment_count': int,
46         },
47         'skip': 'Requires an account',
48     }, {
49         # File downloaded with and without credentials are different, so omit
50         # the md5 field
51         'url': 'http://www.nicovideo.jp/watch/nm14296458',
52         'info_dict': {
53             'id': 'nm14296458',
54             'ext': 'swf',
55             'title': '【鏡音リン】Dance on media【オリジナル】take2!',
56             'description': 'md5:689f066d74610b3b22e0f1739add0f58',
57             'thumbnail': r're:https?://.*',
58             'uploader': 'りょうた',
59             'uploader_id': '18822557',
60             'upload_date': '20110429',
61             'timestamp': 1304065916,
62             'duration': 209,
63         },
64         'skip': 'Requires an account',
65     }, {
66         # 'video exists but is marked as "deleted"
67         # md5 is unstable
68         'url': 'http://www.nicovideo.jp/watch/sm10000',
69         'info_dict': {
70             'id': 'sm10000',
71             'ext': 'unknown_video',
72             'description': 'deleted',
73             'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
74             'thumbnail': r're:https?://.*',
75             'upload_date': '20071224',
76             'timestamp': int,  # timestamp field has different value if logged in
77             'duration': 304,
78             'view_count': int,
79         },
80         'skip': 'Requires an account',
81     }, {
82         'url': 'http://www.nicovideo.jp/watch/so22543406',
83         'info_dict': {
84             'id': '1388129933',
85             'ext': 'mp4',
86             'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
87             'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
88             'thumbnail': r're:https?://.*',
89             'timestamp': 1388851200,
90             'upload_date': '20140104',
91             'uploader': 'アニメロチャンネル',
92             'uploader_id': '312',
93         },
94         'skip': 'The viewing period of the video you were searching for has expired.',
95     }, {
96         # video not available via `getflv`
97         'url': 'http://www.nicovideo.jp/watch/sm1151009',
98         'info_dict': {
99             'id': 'sm1151009',
100             'ext': 'flv',
101             'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
102             'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
103             'thumbnail': r're:https?://.*',
104             'duration': 184,
105             'timestamp': 1190868283,
106             'upload_date': '20070927',
107             'uploader': 'denden2',
108             'uploader_id': '1392194',
109             'view_count': int,
110             'comment_count': int,
111         },
112         'skip': 'Requires an account',
113     }, {
114         'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
115         'only_matching': True,
116     }]
117
118     _VALID_URL = r'https?://(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)'
119     _NETRC_MACHINE = 'niconico'
120
121     def _real_initialize(self):
122         self._login()
123
124     def _login(self):
125         (username, password) = self._get_login_info()
126         # No authentication to be performed
127         if not username:
128             return True
129
130         # Log in
131         login_ok = True
132         login_form_strs = {
133             'mail_tel': username,
134             'password': password,
135         }
136         urlh = self._request_webpage(
137             'https://account.nicovideo.jp/api/v1/login', None,
138             note='Logging in', errnote='Unable to log in',
139             data=urlencode_postdata(login_form_strs))
140         if urlh is False:
141             login_ok = False
142         else:
143             parts = compat_urlparse.urlparse(urlh.geturl())
144             if compat_parse_qs(parts.query).get('message', [None])[0] == 'cant_login':
145                 login_ok = False
146         if not login_ok:
147             self._downloader.report_warning('unable to log in: bad username or password')
148         return login_ok
149
150     def _real_extract(self, url):
151         video_id = self._match_id(url)
152
153         # Get video webpage. We are not actually interested in it for normal
154         # cases, but need the cookies in order to be able to download the
155         # info webpage
156         webpage, handle = self._download_webpage_handle(
157             'http://www.nicovideo.jp/watch/' + video_id, video_id)
158         if video_id.startswith('so'):
159             video_id = self._match_id(handle.geturl())
160
161         api_data = self._parse_json(self._html_search_regex(
162             'data-api-data="([^"]+)"', webpage,
163             'API data', default='{}'), video_id)
164         video_real_url = try_get(
165             api_data, lambda x: x['video']['smileInfo']['url'])
166
167         if video_real_url:
168             def get_video_info(items):
169                 return dict_get(api_data['video'], items)
170         else:
171             # Get flv info
172             flv_info_webpage = self._download_webpage(
173                 'http://flapi.nicovideo.jp/api/getflv/' + video_id + '?as3=1',
174                 video_id, 'Downloading flv info')
175
176             flv_info = compat_urlparse.parse_qs(flv_info_webpage)
177             if 'url' not in flv_info:
178                 if 'deleted' in flv_info:
179                     raise ExtractorError('The video has been deleted.',
180                                          expected=True)
181                 elif 'closed' in flv_info:
182                     raise ExtractorError('Niconico videos now require logging in',
183                                          expected=True)
184                 elif 'error' in flv_info:
185                     raise ExtractorError('%s reports error: %s' % (
186                         self.IE_NAME, flv_info['error'][0]), expected=True)
187                 else:
188                     raise ExtractorError('Unable to find video URL')
189
190             video_real_url = flv_info['url'][0]
191
192             video_info_xml = self._download_xml(
193                 'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id,
194                 video_id, note='Downloading video info page')
195
196             def get_video_info(items):
197                 if not isinstance(items, list):
198                     items = [items]
199                 for item in items:
200                     ret = xpath_text(video_info_xml, './/' + item)
201                     if ret:
202                         return ret
203
204         # Start extracting information
205         title = get_video_info('title')
206         if not title:
207             title = self._og_search_title(webpage, default=None)
208         if not title:
209             title = self._html_search_regex(
210                 r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>',
211                 webpage, 'video title')
212
213         watch_api_data_string = self._html_search_regex(
214             r'<div[^>]+id="watchAPIDataContainer"[^>]+>([^<]+)</div>',
215             webpage, 'watch api data', default=None)
216         watch_api_data = self._parse_json(watch_api_data_string, video_id) if watch_api_data_string else {}
217         video_detail = watch_api_data.get('videoDetail', {})
218
219         extension = get_video_info(['movie_type', 'movieType'])
220         if not extension:
221             extension = determine_ext(video_real_url)
222
223         thumbnail = (
224             get_video_info(['thumbnail_url', 'thumbnailURL']) or
225             self._html_search_meta('image', webpage, 'thumbnail', default=None) or
226             video_detail.get('thumbnail'))
227
228         description = get_video_info('description')
229
230         timestamp = (parse_iso8601(get_video_info('first_retrieve')) or
231                      unified_timestamp(get_video_info('postedDateTime')))
232         if not timestamp:
233             match = self._html_search_meta('datePublished', webpage, 'date published', default=None)
234             if match:
235                 timestamp = parse_iso8601(match.replace('+', ':00+'))
236         if not timestamp and video_detail.get('postedAt'):
237             timestamp = parse_iso8601(
238                 video_detail['postedAt'].replace('/', '-'),
239                 delimiter=' ', timezone=datetime.timedelta(hours=9))
240
241         view_count = int_or_none(get_video_info(['view_counter', 'viewCount']))
242         if not view_count:
243             match = self._html_search_regex(
244                 r'>Views: <strong[^>]*>([^<]+)</strong>',
245                 webpage, 'view count', default=None)
246             if match:
247                 view_count = int_or_none(match.replace(',', ''))
248         view_count = view_count or video_detail.get('viewCount')
249
250         comment_count = (int_or_none(get_video_info('comment_num')) or
251                          video_detail.get('commentCount') or
252                          try_get(api_data, lambda x: x['thread']['commentCount']))
253         if not comment_count:
254             match = self._html_search_regex(
255                 r'>Comments: <strong[^>]*>([^<]+)</strong>',
256                 webpage, 'comment count', default=None)
257             if match:
258                 comment_count = int_or_none(match.replace(',', ''))
259
260         duration = (parse_duration(
261             get_video_info('length') or
262             self._html_search_meta(
263                 'video:duration', webpage, 'video duration', default=None)) or
264             video_detail.get('length') or
265             get_video_info('duration'))
266
267         webpage_url = get_video_info('watch_url') or url
268
269         owner = api_data.get('owner', {})
270         uploader_id = get_video_info(['ch_id', 'user_id']) or owner.get('id')
271         uploader = get_video_info(['ch_name', 'user_nickname']) or owner.get('nickname')
272
273         return {
274             'id': video_id,
275             'url': video_real_url,
276             'title': title,
277             'ext': extension,
278             'format_id': 'economy' if video_real_url.endswith('low') else 'normal',
279             'thumbnail': thumbnail,
280             'description': description,
281             'uploader': uploader,
282             'timestamp': timestamp,
283             'uploader_id': uploader_id,
284             'view_count': view_count,
285             'comment_count': comment_count,
286             'duration': duration,
287             'webpage_url': webpage_url,
288         }
289
290
291 class NiconicoPlaylistIE(InfoExtractor):
292     _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/mylist/(?P<id>\d+)'
293
294     _TEST = {
295         'url': 'http://www.nicovideo.jp/mylist/27411728',
296         'info_dict': {
297             'id': '27411728',
298             'title': 'AKB48のオールナイトニッポン',
299         },
300         'playlist_mincount': 225,
301     }
302
303     def _real_extract(self, url):
304         list_id = self._match_id(url)
305         webpage = self._download_webpage(url, list_id)
306
307         entries_json = self._search_regex(r'Mylist\.preload\(\d+, (\[.*\])\);',
308                                           webpage, 'entries')
309         entries = json.loads(entries_json)
310         entries = [{
311             '_type': 'url',
312             'ie_key': NiconicoIE.ie_key(),
313             'url': ('http://www.nicovideo.jp/watch/%s' %
314                     entry['item_data']['video_id']),
315         } for entry in entries]
316
317         return {
318             '_type': 'playlist',
319             'title': self._search_regex(r'\s+name: "(.*?)"', webpage, 'title'),
320             'id': list_id,
321             'entries': entries,
322         }