[niconico] Try to extract all optional fields from various sources
[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,
11     compat_urllib_request,
12     compat_urlparse,
13 )
14 from ..utils import (
15     ExtractorError,
16     int_or_none,
17     parse_duration,
18     parse_iso8601,
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
72     _VALID_URL = r'https?://(?:www\.|secure\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)'
73     _NETRC_MACHINE = 'niconico'
74     # Determine whether the downloader used authentication to download video
75     _AUTHENTICATED = False
76
77     def _real_initialize(self):
78         self._login()
79
80     def _login(self):
81         (username, password) = self._get_login_info()
82         # No authentication to be performed
83         if not username:
84             return True
85
86         # Log in
87         login_form_strs = {
88             'mail': username,
89             'password': password,
90         }
91         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
92         # chokes on unicode
93         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k, v in login_form_strs.items())
94         login_data = compat_urllib_parse.urlencode(login_form).encode('utf-8')
95         request = compat_urllib_request.Request(
96             'https://secure.nicovideo.jp/secure/login', login_data)
97         login_results = self._download_webpage(
98             request, None, note='Logging in', errnote='Unable to log in')
99         if re.search(r'(?i)<h1 class="mb8p4">Log in error</h1>', login_results) is not None:
100             self._downloader.report_warning('unable to log in: bad username or password')
101             return False
102         # Successful login
103         self._AUTHENTICATED = True
104         return True
105
106     def _real_extract(self, url):
107         video_id = self._match_id(url)
108
109         # Get video webpage. We are not actually interested in it for normal
110         # cases, but need the cookies in order to be able to download the
111         # info webpage
112         webpage = self._download_webpage('http://www.nicovideo.jp/watch/' + video_id, video_id)
113
114         video_info = self._download_xml(
115             'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, video_id,
116             note='Downloading video info page')
117
118         if self._AUTHENTICATED:
119             # Get flv info
120             flv_info_webpage = self._download_webpage(
121                 'http://flapi.nicovideo.jp/api/getflv/' + video_id + '?as3=1',
122                 video_id, 'Downloading flv info')
123         else:
124             # Get external player info
125             ext_player_info = self._download_webpage(
126                 'http://ext.nicovideo.jp/thumb_watch/' + video_id, video_id)
127             thumb_play_key = self._search_regex(
128                 r'\'thumbPlayKey\'\s*:\s*\'(.*?)\'', ext_player_info, 'thumbPlayKey')
129
130             # Get flv info
131             flv_info_data = compat_urllib_parse.urlencode({
132                 'k': thumb_play_key,
133                 'v': video_id
134             })
135             flv_info_request = compat_urllib_request.Request(
136                 'http://ext.nicovideo.jp/thumb_watch', flv_info_data,
137                 {'Content-Type': 'application/x-www-form-urlencoded'})
138             flv_info_webpage = self._download_webpage(
139                 flv_info_request, video_id,
140                 note='Downloading flv info', errnote='Unable to download 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             else:
148                 raise ExtractorError('Unable to find video URL')
149
150         video_real_url = flv_info['url'][0]
151
152         # Start extracting information
153         title = xpath_text(video_info, './/title')
154         if not title:
155             title = self._og_search_title(webpage, default=None)
156         if not title:
157             title = self._html_search_regex(
158                 r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>',
159                 webpage, 'video title')
160
161         watch_api_data_string = self._html_search_regex(
162             r'<div[^>]+id="watchAPIDataContainer"[^>]+>([^<]+)</div>',
163             webpage, 'watch api data', default=None)
164         watch_api_data = self._parse_json(watch_api_data_string, video_id) if watch_api_data_string else {}
165         video_detail = watch_api_data.get('videoDetail', {})
166
167         extension = xpath_text(video_info, './/movie_type')
168         if not extension:
169             extension = determine_ext(video_real_url)
170         video_format = extension.upper()
171
172         thumbnail = (
173             xpath_text(video_info, './/thumbnail_url') or
174             self._html_search_meta('image', webpage, 'thumbnail', default=None) or
175             video_detail.get('thumbnail'))
176
177         description = xpath_text(video_info, './/description')
178
179         timestamp = parse_iso8601(xpath_text(video_info, './/first_retrieve'))
180         if not timestamp:
181             match = self._html_search_meta('datePublished', webpage, 'date published', default=None)
182             if match:
183                 timestamp = parse_iso8601(match.replace('+', ':00+'))
184         if not timestamp and video_detail.get('postedAt'):
185             timestamp = parse_iso8601(
186                 video_detail['postedAt'].replace('/', '-'),
187                 delimiter=' ', timezone=datetime.timedelta(hours=9))
188
189         view_count = int_or_none(xpath_text(video_info, './/view_counter'))
190         if not view_count:
191             match = self._html_search_regex(
192                 r'>Views: <strong[^>]*>([^<]+)</strong>',
193                 webpage, 'view count', default=None)
194             if match:
195                 view_count = int_or_none(match.replace(',', ''))
196         view_count = view_count or video_detail.get('viewCount')
197
198         comment_count = int_or_none(xpath_text(video_info, './/comment_num'))
199         if not comment_count:
200             match = self._html_search_regex(
201                 r'>Comments: <strong[^>]*>([^<]+)</strong>',
202                 webpage, 'comment count', default=None)
203             if match:
204                 comment_count = int_or_none(match.replace(',', ''))
205         comment_count = comment_count or video_detail.get('commentCount')
206
207         duration = (parse_duration(
208             xpath_text(video_info, './/length') or
209             self._html_search_meta(
210                 'video:duration', webpage, 'video duration', default=None)) or
211             video_detail.get('length'))
212
213         webpage_url = xpath_text(video_info, './/watch_url') or url
214
215         if video_info.find('.//ch_id') is not None:
216             uploader_id = video_info.find('.//ch_id').text
217             uploader = video_info.find('.//ch_name').text
218         elif video_info.find('.//user_id') is not None:
219             uploader_id = video_info.find('.//user_id').text
220             uploader = video_info.find('.//user_nickname').text
221         else:
222             uploader_id = uploader = None
223
224         return {
225             'id': video_id,
226             'url': video_real_url,
227             'title': title,
228             'ext': extension,
229             'format': video_format,
230             'thumbnail': thumbnail,
231             'description': description,
232             'uploader': uploader,
233             'timestamp': timestamp,
234             'uploader_id': uploader_id,
235             'view_count': view_count,
236             'comment_count': comment_count,
237             'duration': duration,
238             'webpage_url': webpage_url,
239         }
240
241
242 class NiconicoPlaylistIE(InfoExtractor):
243     _VALID_URL = r'https?://www\.nicovideo\.jp/mylist/(?P<id>\d+)'
244
245     _TEST = {
246         'url': 'http://www.nicovideo.jp/mylist/27411728',
247         'info_dict': {
248             'id': '27411728',
249             'title': 'AKB48のオールナイトニッポン',
250         },
251         'playlist_mincount': 225,
252     }
253
254     def _real_extract(self, url):
255         list_id = self._match_id(url)
256         webpage = self._download_webpage(url, list_id)
257
258         entries_json = self._search_regex(r'Mylist\.preload\(\d+, (\[.*\])\);',
259                                           webpage, 'entries')
260         entries = json.loads(entries_json)
261         entries = [{
262             '_type': 'url',
263             'ie_key': NiconicoIE.ie_key(),
264             'url': ('http://www.nicovideo.jp/watch/%s' %
265                     entry['item_data']['video_id']),
266         } for entry in entries]
267
268         return {
269             '_type': 'playlist',
270             'title': self._search_regex(r'\s+name: "(.*?)"', webpage, 'title'),
271             'id': list_id,
272             'entries': entries,
273         }