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