[niconico] Remove credentials from tests and enhance title extraction
[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
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_urllib_parse,
10     compat_urllib_request,
11     compat_urlparse,
12 )
13 from ..utils import (
14     ExtractorError,
15     int_or_none,
16     parse_duration,
17     parse_iso8601,
18     xpath_text,
19     determine_ext,
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     }, {
42         # File downloaded with and without credentials are different, so omit
43         # the md5 field
44         'url': 'http://www.nicovideo.jp/watch/nm14296458',
45         'info_dict': {
46             'id': 'nm14296458',
47             'ext': 'swf',
48             'title': '【鏡音リン】Dance on media【オリジナル】take2!',
49             'description': 'md5:689f066d74610b3b22e0f1739add0f58',
50             'uploader': 'りょうた',
51             'uploader_id': '18822557',
52             'upload_date': '20110429',
53             'timestamp': 1304065916,
54             'duration': 209,
55         },
56     }, {
57         # 'video exists but is marked as "deleted"
58         'url': 'http://www.nicovideo.jp/watch/sm10000',
59         'md5': '38e53c9aad548f3ecf01ca7680b59b08',
60         'info_dict': {
61             'id': 'sm10000',
62             'ext': 'unknown_video',
63             'description': 'deleted',
64             'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
65         },
66     }]
67
68     _VALID_URL = r'https?://(?:www\.|secure\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)'
69     _NETRC_MACHINE = 'niconico'
70     # Determine whether the downloader used authentication to download video
71     _AUTHENTICATED = False
72
73     def _real_initialize(self):
74         self._login()
75
76     def _login(self):
77         (username, password) = self._get_login_info()
78         # No authentication to be performed
79         if not username:
80             return True
81
82         # Log in
83         login_form_strs = {
84             'mail': username,
85             'password': password,
86         }
87         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
88         # chokes on unicode
89         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k, v in login_form_strs.items())
90         login_data = compat_urllib_parse.urlencode(login_form).encode('utf-8')
91         request = compat_urllib_request.Request(
92             'https://secure.nicovideo.jp/secure/login', login_data)
93         login_results = self._download_webpage(
94             request, None, note='Logging in', errnote='Unable to log in')
95         if re.search(r'(?i)<h1 class="mb8p4">Log in error</h1>', login_results) is not None:
96             self._downloader.report_warning('unable to log in: bad username or password')
97             return False
98         # Successful login
99         self._AUTHENTICATED = True
100         return True
101
102     def _real_extract(self, url):
103         video_id = self._match_id(url)
104
105         # Get video webpage. We are not actually interested in it for normal
106         # cases, but need the cookies in order to be able to download the
107         # info webpage
108         webpage = self._download_webpage('http://www.nicovideo.jp/watch/' + video_id, video_id)
109
110         video_info = self._download_xml(
111             'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, video_id,
112             note='Downloading video info page')
113
114         if self._AUTHENTICATED:
115             # Get flv info
116             flv_info_webpage = self._download_webpage(
117                 'http://flapi.nicovideo.jp/api/getflv/' + video_id + '?as3=1',
118                 video_id, 'Downloading flv info')
119         else:
120             # Get external player info
121             ext_player_info = self._download_webpage(
122                 'http://ext.nicovideo.jp/thumb_watch/' + video_id, video_id)
123             thumb_play_key = self._search_regex(
124                 r'\'thumbPlayKey\'\s*:\s*\'(.*?)\'', ext_player_info, 'thumbPlayKey')
125
126             # Get flv info
127             flv_info_data = compat_urllib_parse.urlencode({
128                 'k': thumb_play_key,
129                 'v': video_id
130             })
131             flv_info_request = compat_urllib_request.Request(
132                 'http://ext.nicovideo.jp/thumb_watch', flv_info_data,
133                 {'Content-Type': 'application/x-www-form-urlencoded'})
134             flv_info_webpage = self._download_webpage(
135                 flv_info_request, video_id,
136                 note='Downloading flv info', errnote='Unable to download 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             else:
144                 raise ExtractorError('Unable to find video URL')
145
146         video_real_url = flv_info['url'][0]
147
148         # Start extracting information
149         title = xpath_text(video_info, './/title')
150         if not title:
151             title = self._og_search_title(webpage, default=None)
152         if not title:
153             title = self._html_search_regex(
154                 r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>',
155                 webpage, 'video title')
156
157         extension = xpath_text(video_info, './/movie_type')
158         if not extension:
159             extension = determine_ext(video_real_url)
160         video_format = extension.upper()
161         thumbnail = xpath_text(video_info, './/thumbnail_url')
162         description = xpath_text(video_info, './/description')
163         timestamp = parse_iso8601(xpath_text(video_info, './/first_retrieve'))
164         view_count = int_or_none(xpath_text(video_info, './/view_counter'))
165         comment_count = int_or_none(xpath_text(video_info, './/comment_num'))
166         duration = parse_duration(xpath_text(video_info, './/length'))
167         webpage_url = xpath_text(video_info, './/watch_url')
168
169         if video_info.find('.//ch_id') is not None:
170             uploader_id = video_info.find('.//ch_id').text
171             uploader = video_info.find('.//ch_name').text
172         elif video_info.find('.//user_id') is not None:
173             uploader_id = video_info.find('.//user_id').text
174             uploader = video_info.find('.//user_nickname').text
175         else:
176             uploader_id = uploader = None
177
178         ret = {
179             'id': video_id,
180             'url': video_real_url,
181             'title': title,
182             'ext': extension,
183             'format': video_format,
184             'thumbnail': thumbnail,
185             'description': description,
186             'uploader': uploader,
187             'timestamp': timestamp,
188             'uploader_id': uploader_id,
189             'view_count': view_count,
190             'comment_count': comment_count,
191             'duration': duration,
192             'webpage_url': webpage_url,
193         }
194         return dict((k, v) for k, v in ret.items() if v is not None)
195
196
197 class NiconicoPlaylistIE(InfoExtractor):
198     _VALID_URL = r'https?://www\.nicovideo\.jp/mylist/(?P<id>\d+)'
199
200     _TEST = {
201         'url': 'http://www.nicovideo.jp/mylist/27411728',
202         'info_dict': {
203             'id': '27411728',
204             'title': 'AKB48のオールナイトニッポン',
205         },
206         'playlist_mincount': 225,
207     }
208
209     def _real_extract(self, url):
210         list_id = self._match_id(url)
211         webpage = self._download_webpage(url, list_id)
212
213         entries_json = self._search_regex(r'Mylist\.preload\(\d+, (\[.*\])\);',
214                                           webpage, 'entries')
215         entries = json.loads(entries_json)
216         entries = [{
217             '_type': 'url',
218             'ie_key': NiconicoIE.ie_key(),
219             'url': ('http://www.nicovideo.jp/watch/%s' %
220                     entry['item_data']['video_id']),
221         } for entry in entries]
222
223         return {
224             '_type': 'playlist',
225             'title': self._search_regex(r'\s+name: "(.*?)"', webpage, 'title'),
226             'id': list_id,
227             'entries': entries,
228         }