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