[compat] Add compat_urllib_parse_urlencode and eliminate encode_dict
[youtube-dl] / youtube_dl / extractor / niconico.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6 import datetime
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_urllib_parse_urlencode,
11     compat_urlparse,
12 )
13 from ..utils import (
14     ExtractorError,
15     int_or_none,
16     parse_duration,
17     parse_iso8601,
18     sanitized_Request,
19     xpath_text,
20     determine_ext,
21 )
22
23
24 class NiconicoIE(InfoExtractor):
25     IE_NAME = 'niconico'
26     IE_DESC = 'ニコニコ動画'
27
28     _TESTS = [{
29         'url': 'http://www.nicovideo.jp/watch/sm22312215',
30         'md5': 'd1a75c0823e2f629128c43e1212760f9',
31         'info_dict': {
32             'id': 'sm22312215',
33             'ext': 'mp4',
34             'title': 'Big Buck Bunny',
35             'uploader': 'takuya0301',
36             'uploader_id': '2698420',
37             'upload_date': '20131123',
38             'timestamp': 1385182762,
39             'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
40             'duration': 33,
41         },
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     }, {
58         # 'video exists but is marked as "deleted"
59         # md5 is unstable
60         'url': 'http://www.nicovideo.jp/watch/sm10000',
61         'info_dict': {
62             'id': 'sm10000',
63             'ext': 'unknown_video',
64             'description': 'deleted',
65             'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
66             'upload_date': '20071224',
67             'timestamp': 1198527840,  # timestamp field has different value if logged in
68             'duration': 304,
69         },
70     }, {
71         'url': 'http://www.nicovideo.jp/watch/so22543406',
72         'info_dict': {
73             'id': '1388129933',
74             'ext': 'mp4',
75             'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
76             'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
77             'timestamp': 1388851200,
78             'upload_date': '20140104',
79             'uploader': 'アニメロチャンネル',
80             'uploader_id': '312',
81         }
82     }]
83
84     _VALID_URL = r'https?://(?:www\.|secure\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)'
85     _NETRC_MACHINE = 'niconico'
86     # Determine whether the downloader used authentication to download video
87     _AUTHENTICATED = False
88
89     def _real_initialize(self):
90         self._login()
91
92     def _login(self):
93         (username, password) = self._get_login_info()
94         # No authentication to be performed
95         if not username:
96             return True
97
98         # Log in
99         login_form_strs = {
100             'mail': username,
101             'password': password,
102         }
103         login_data = compat_urllib_parse_urlencode(login_form_strs).encode('utf-8')
104         request = sanitized_Request(
105             'https://secure.nicovideo.jp/secure/login', login_data)
106         login_results = self._download_webpage(
107             request, None, note='Logging in', errnote='Unable to log in')
108         if re.search(r'(?i)<h1 class="mb8p4">Log in error</h1>', login_results) is not None:
109             self._downloader.report_warning('unable to log in: bad username or password')
110             return False
111         # Successful login
112         self._AUTHENTICATED = True
113         return True
114
115     def _real_extract(self, url):
116         video_id = self._match_id(url)
117
118         # Get video webpage. We are not actually interested in it for normal
119         # cases, but need the cookies in order to be able to download the
120         # info webpage
121         webpage, handle = self._download_webpage_handle(
122             'http://www.nicovideo.jp/watch/' + video_id, video_id)
123         if video_id.startswith('so'):
124             video_id = self._match_id(handle.geturl())
125
126         video_info = self._download_xml(
127             'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, video_id,
128             note='Downloading video info page')
129
130         if self._AUTHENTICATED:
131             # Get flv info
132             flv_info_webpage = self._download_webpage(
133                 'http://flapi.nicovideo.jp/api/getflv/' + video_id + '?as3=1',
134                 video_id, 'Downloading flv info')
135         else:
136             # Get external player info
137             ext_player_info = self._download_webpage(
138                 'http://ext.nicovideo.jp/thumb_watch/' + video_id, video_id)
139             thumb_play_key = self._search_regex(
140                 r'\'thumbPlayKey\'\s*:\s*\'(.*?)\'', ext_player_info, 'thumbPlayKey')
141
142             # Get flv info
143             flv_info_data = compat_urllib_parse_urlencode({
144                 'k': thumb_play_key,
145                 'v': video_id
146             })
147             flv_info_request = sanitized_Request(
148                 'http://ext.nicovideo.jp/thumb_watch', flv_info_data,
149                 {'Content-Type': 'application/x-www-form-urlencoded'})
150             flv_info_webpage = self._download_webpage(
151                 flv_info_request, video_id,
152                 note='Downloading flv info', errnote='Unable to download flv info')
153
154         flv_info = compat_urlparse.parse_qs(flv_info_webpage)
155         if 'url' not in flv_info:
156             if 'deleted' in flv_info:
157                 raise ExtractorError('The video has been deleted.',
158                                      expected=True)
159             else:
160                 raise ExtractorError('Unable to find video URL')
161
162         video_real_url = flv_info['url'][0]
163
164         # Start extracting information
165         title = xpath_text(video_info, './/title')
166         if not title:
167             title = self._og_search_title(webpage, default=None)
168         if not title:
169             title = self._html_search_regex(
170                 r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>',
171                 webpage, 'video title')
172
173         watch_api_data_string = self._html_search_regex(
174             r'<div[^>]+id="watchAPIDataContainer"[^>]+>([^<]+)</div>',
175             webpage, 'watch api data', default=None)
176         watch_api_data = self._parse_json(watch_api_data_string, video_id) if watch_api_data_string else {}
177         video_detail = watch_api_data.get('videoDetail', {})
178
179         extension = xpath_text(video_info, './/movie_type')
180         if not extension:
181             extension = determine_ext(video_real_url)
182
183         thumbnail = (
184             xpath_text(video_info, './/thumbnail_url') or
185             self._html_search_meta('image', webpage, 'thumbnail', default=None) or
186             video_detail.get('thumbnail'))
187
188         description = xpath_text(video_info, './/description')
189
190         timestamp = parse_iso8601(xpath_text(video_info, './/first_retrieve'))
191         if not timestamp:
192             match = self._html_search_meta('datePublished', webpage, 'date published', default=None)
193             if match:
194                 timestamp = parse_iso8601(match.replace('+', ':00+'))
195         if not timestamp and video_detail.get('postedAt'):
196             timestamp = parse_iso8601(
197                 video_detail['postedAt'].replace('/', '-'),
198                 delimiter=' ', timezone=datetime.timedelta(hours=9))
199
200         view_count = int_or_none(xpath_text(video_info, './/view_counter'))
201         if not view_count:
202             match = self._html_search_regex(
203                 r'>Views: <strong[^>]*>([^<]+)</strong>',
204                 webpage, 'view count', default=None)
205             if match:
206                 view_count = int_or_none(match.replace(',', ''))
207         view_count = view_count or video_detail.get('viewCount')
208
209         comment_count = int_or_none(xpath_text(video_info, './/comment_num'))
210         if not comment_count:
211             match = self._html_search_regex(
212                 r'>Comments: <strong[^>]*>([^<]+)</strong>',
213                 webpage, 'comment count', default=None)
214             if match:
215                 comment_count = int_or_none(match.replace(',', ''))
216         comment_count = comment_count or video_detail.get('commentCount')
217
218         duration = (parse_duration(
219             xpath_text(video_info, './/length') or
220             self._html_search_meta(
221                 'video:duration', webpage, 'video duration', default=None)) or
222             video_detail.get('length'))
223
224         webpage_url = xpath_text(video_info, './/watch_url') or url
225
226         if video_info.find('.//ch_id') is not None:
227             uploader_id = video_info.find('.//ch_id').text
228             uploader = video_info.find('.//ch_name').text
229         elif video_info.find('.//user_id') is not None:
230             uploader_id = video_info.find('.//user_id').text
231             uploader = video_info.find('.//user_nickname').text
232         else:
233             uploader_id = uploader = None
234
235         return {
236             'id': video_id,
237             'url': video_real_url,
238             'title': title,
239             'ext': extension,
240             'format_id': 'economy' if video_real_url.endswith('low') else 'normal',
241             'thumbnail': thumbnail,
242             'description': description,
243             'uploader': uploader,
244             'timestamp': timestamp,
245             'uploader_id': uploader_id,
246             'view_count': view_count,
247             'comment_count': comment_count,
248             'duration': duration,
249             'webpage_url': webpage_url,
250         }
251
252
253 class NiconicoPlaylistIE(InfoExtractor):
254     _VALID_URL = r'https?://www\.nicovideo\.jp/mylist/(?P<id>\d+)'
255
256     _TEST = {
257         'url': 'http://www.nicovideo.jp/mylist/27411728',
258         'info_dict': {
259             'id': '27411728',
260             'title': 'AKB48のオールナイトニッポン',
261         },
262         'playlist_mincount': 225,
263     }
264
265     def _real_extract(self, url):
266         list_id = self._match_id(url)
267         webpage = self._download_webpage(url, list_id)
268
269         entries_json = self._search_regex(r'Mylist\.preload\(\d+, (\[.*\])\);',
270                                           webpage, 'entries')
271         entries = json.loads(entries_json)
272         entries = [{
273             '_type': 'url',
274             'ie_key': NiconicoIE.ie_key(),
275             'url': ('http://www.nicovideo.jp/watch/%s' %
276                     entry['item_data']['video_id']),
277         } for entry in entries]
278
279         return {
280             '_type': 'playlist',
281             'title': self._search_regex(r'\s+name: "(.*?)"', webpage, 'title'),
282             'id': list_id,
283             'entries': entries,
284         }