]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/niconico.py
[SpankBang] Use python2.6 compatible string formatting spec
[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     unified_strdate,
18 )
19
20
21 class NiconicoIE(InfoExtractor):
22     IE_NAME = 'niconico'
23     IE_DESC = 'ニコニコ動画'
24
25     _TESTS = [{
26         'url': 'http://www.nicovideo.jp/watch/sm22312215',
27         'md5': 'd1a75c0823e2f629128c43e1212760f9',
28         'info_dict': {
29             'id': 'sm22312215',
30             'ext': 'mp4',
31             'title': 'Big Buck Bunny',
32             'uploader': 'takuya0301',
33             'uploader_id': '2698420',
34             'upload_date': '20131123',
35             'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
36             'duration': 33,
37         },
38         'params': {
39             'username': 'ydl.niconico@gmail.com',
40             'password': 'youtube-dl',
41         },
42     }, {
43         'url': 'http://www.nicovideo.jp/watch/nm14296458',
44         'md5': '8db08e0158457cf852a31519fceea5bc',
45         'info_dict': {
46             'id': 'nm14296458',
47             'ext': 'swf',
48             'title': '【鏡音リン】Dance on media【オリジナル】take2!',
49             'description': 'md5:',
50             'uploader': 'りょうた',
51             'uploader_id': '18822557',
52             'upload_date': '20110429',
53             'duration': 209,
54         },
55         'params': {
56             'username': 'ydl.niconico@gmail.com',
57             'password': 'youtube-dl',
58         },
59     }]
60
61     _VALID_URL = r'https?://(?:www\.|secure\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)'
62     _NETRC_MACHINE = 'niconico'
63     # Determine whether the downloader used authentication to download video
64     _AUTHENTICATED = False
65
66     def _real_initialize(self):
67         self._login()
68
69     def _login(self):
70         (username, password) = self._get_login_info()
71         # No authentication to be performed
72         if not username:
73             return True
74
75         # Log in
76         login_form_strs = {
77             'mail': username,
78             'password': password,
79         }
80         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
81         # chokes on unicode
82         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k, v in login_form_strs.items())
83         login_data = compat_urllib_parse.urlencode(login_form).encode('utf-8')
84         request = compat_urllib_request.Request(
85             'https://secure.nicovideo.jp/secure/login', login_data)
86         login_results = self._download_webpage(
87             request, None, note='Logging in', errnote='Unable to log in')
88         if re.search(r'(?i)<h1 class="mb8p4">Log in error</h1>', login_results) is not None:
89             self._downloader.report_warning('unable to log in: bad username or password')
90             return False
91         # Successful login
92         self._AUTHENTICATED = True
93         return True
94
95     def _real_extract(self, url):
96         video_id = self._match_id(url)
97
98         # Get video webpage. We are not actually interested in it, but need
99         # the cookies in order to be able to download the info webpage
100         self._download_webpage('http://www.nicovideo.jp/watch/' + video_id, video_id)
101
102         video_info = self._download_xml(
103             'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, video_id,
104             note='Downloading video info page')
105
106         if self._AUTHENTICATED:
107             # Get flv info
108             flv_info_webpage = self._download_webpage(
109                 'http://flapi.nicovideo.jp/api/getflv/' + video_id + '?as3=1',
110                 video_id, 'Downloading flv info')
111         else:
112             # Get external player info
113             ext_player_info = self._download_webpage(
114                 'http://ext.nicovideo.jp/thumb_watch/' + video_id, video_id)
115             thumb_play_key = self._search_regex(
116                 r'\'thumbPlayKey\'\s*:\s*\'(.*?)\'', ext_player_info, 'thumbPlayKey')
117
118             # Get flv info
119             flv_info_data = compat_urllib_parse.urlencode({
120                 'k': thumb_play_key,
121                 'v': video_id
122             })
123             flv_info_request = compat_urllib_request.Request(
124                 'http://ext.nicovideo.jp/thumb_watch', flv_info_data,
125                 {'Content-Type': 'application/x-www-form-urlencoded'})
126             flv_info_webpage = self._download_webpage(
127                 flv_info_request, video_id,
128                 note='Downloading flv info', errnote='Unable to download flv info')
129
130         if 'deleted=' in flv_info_webpage:
131             raise ExtractorError('The video has been deleted.',
132                                  expected=True)
133         video_real_url = compat_urlparse.parse_qs(flv_info_webpage)['url'][0]
134
135         # Start extracting information
136         title = video_info.find('.//title').text
137         extension = video_info.find('.//movie_type').text
138         video_format = extension.upper()
139         thumbnail = video_info.find('.//thumbnail_url').text
140         description = video_info.find('.//description').text
141         upload_date = unified_strdate(video_info.find('.//first_retrieve').text.split('+')[0])
142         view_count = int_or_none(video_info.find('.//view_counter').text)
143         comment_count = int_or_none(video_info.find('.//comment_num').text)
144         duration = parse_duration(video_info.find('.//length').text)
145         webpage_url = video_info.find('.//watch_url').text
146
147         if video_info.find('.//ch_id') is not None:
148             uploader_id = video_info.find('.//ch_id').text
149             uploader = video_info.find('.//ch_name').text
150         elif video_info.find('.//user_id') is not None:
151             uploader_id = video_info.find('.//user_id').text
152             uploader = video_info.find('.//user_nickname').text
153         else:
154             uploader_id = uploader = None
155
156         return {
157             'id': video_id,
158             'url': video_real_url,
159             'title': title,
160             'ext': extension,
161             'format': video_format,
162             'thumbnail': thumbnail,
163             'description': description,
164             'uploader': uploader,
165             'upload_date': upload_date,
166             'uploader_id': uploader_id,
167             'view_count': view_count,
168             'comment_count': comment_count,
169             'duration': duration,
170             'webpage_url': webpage_url,
171         }
172
173
174 class NiconicoPlaylistIE(InfoExtractor):
175     _VALID_URL = r'https?://www\.nicovideo\.jp/mylist/(?P<id>\d+)'
176
177     _TEST = {
178         'url': 'http://www.nicovideo.jp/mylist/27411728',
179         'info_dict': {
180             'id': '27411728',
181             'title': 'AKB48のオールナイトニッポン',
182         },
183         'playlist_mincount': 225,
184     }
185
186     def _real_extract(self, url):
187         list_id = self._match_id(url)
188         webpage = self._download_webpage(url, list_id)
189
190         entries_json = self._search_regex(r'Mylist\.preload\(\d+, (\[.*\])\);',
191                                           webpage, 'entries')
192         entries = json.loads(entries_json)
193         entries = [{
194             '_type': 'url',
195             'ie_key': NiconicoIE.ie_key(),
196             'url': ('http://www.nicovideo.jp/watch/%s' %
197                     entry['item_data']['video_id']),
198         } for entry in entries]
199
200         return {
201             '_type': 'playlist',
202             'title': self._search_regex(r'\s+name: "(.*?)"', webpage, 'title'),
203             'id': list_id,
204             'entries': entries,
205         }