Merge branch 'niconico_nm' of https://github.com/ndac-todoroki/youtube-dl into ndac...
[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     _TEST = {
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
44     _VALID_URL = r'https?://(?:www\.|secure\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)'
45     _NETRC_MACHINE = 'niconico'
46     # Determine whether the downloader used authentication to download video
47     _AUTHENTICATED = False
48
49     def _real_initialize(self):
50         self._login()
51
52     def _login(self):
53         (username, password) = self._get_login_info()
54         # No authentication to be performed
55         if not username:
56             return True
57
58         # Log in
59         login_form_strs = {
60             'mail': username,
61             'password': password,
62         }
63         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
64         # chokes on unicode
65         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k, v in login_form_strs.items())
66         login_data = compat_urllib_parse.urlencode(login_form).encode('utf-8')
67         request = compat_urllib_request.Request(
68             'https://secure.nicovideo.jp/secure/login', login_data)
69         login_results = self._download_webpage(
70             request, None, note='Logging in', errnote='Unable to log in')
71         if re.search(r'(?i)<h1 class="mb8p4">Log in error</h1>', login_results) is not None:
72             self._downloader.report_warning('unable to log in: bad username or password')
73             return False
74         # Successful login
75         self._AUTHENTICATED = True
76         return True
77
78     def _real_extract(self, url):
79         video_id = self._match_id(url)
80
81         # Get video webpage. We are not actually interested in it, but need
82         # the cookies in order to be able to download the info webpage
83         self._download_webpage('http://www.nicovideo.jp/watch/' + video_id, video_id)
84
85         video_info = self._download_xml(
86             'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, video_id,
87             note='Downloading video info page')
88
89         if self._AUTHENTICATED:
90             # Get flv info
91             flv_info_webpage = self._download_webpage(
92                 'http://flapi.nicovideo.jp/api/getflv/' + video_id + '?as3=1',
93                 video_id, 'Downloading flv info')
94         else:
95             # Get external player info
96             ext_player_info = self._download_webpage(
97                 'http://ext.nicovideo.jp/thumb_watch/' + video_id, video_id)
98             thumb_play_key = self._search_regex(
99                 r'\'thumbPlayKey\'\s*:\s*\'(.*?)\'', ext_player_info, 'thumbPlayKey')
100
101             # Get flv info
102             flv_info_data = compat_urllib_parse.urlencode({
103                 'k': thumb_play_key,
104                 'v': video_id
105             })
106             flv_info_request = compat_urllib_request.Request(
107                 'http://ext.nicovideo.jp/thumb_watch', flv_info_data,
108                 {'Content-Type': 'application/x-www-form-urlencoded'})
109             flv_info_webpage = self._download_webpage(
110                 flv_info_request, video_id,
111                 note='Downloading flv info', errnote='Unable to download flv info')
112
113         if 'deleted=' in flv_info_webpage:
114             raise ExtractorError('The video has been deleted.',
115                                  expected=True)
116         video_real_url = compat_urlparse.parse_qs(flv_info_webpage)['url'][0]
117
118         # Start extracting information
119         title = video_info.find('.//title').text
120         extension = video_info.find('.//movie_type').text
121         video_format = extension.upper()
122         thumbnail = video_info.find('.//thumbnail_url').text
123         description = video_info.find('.//description').text
124         upload_date = unified_strdate(video_info.find('.//first_retrieve').text.split('+')[0])
125         view_count = int_or_none(video_info.find('.//view_counter').text)
126         comment_count = int_or_none(video_info.find('.//comment_num').text)
127         duration = parse_duration(video_info.find('.//length').text)
128         webpage_url = video_info.find('.//watch_url').text
129
130         if video_info.find('.//ch_id') is not None:
131             uploader_id = video_info.find('.//ch_id').text
132             uploader = video_info.find('.//ch_name').text
133         elif video_info.find('.//user_id') is not None:
134             uploader_id = video_info.find('.//user_id').text
135             uploader = video_info.find('.//user_nickname').text
136         else:
137             uploader_id = uploader = None
138
139         return {
140             'id': video_id,
141             'url': video_real_url,
142             'title': title,
143             'ext': extension,
144             'format': video_format,
145             'thumbnail': thumbnail,
146             'description': description,
147             'uploader': uploader,
148             'upload_date': upload_date,
149             'uploader_id': uploader_id,
150             'view_count': view_count,
151             'comment_count': comment_count,
152             'duration': duration,
153             'webpage_url': webpage_url,
154         }
155
156
157 class NiconicoPlaylistIE(InfoExtractor):
158     _VALID_URL = r'https?://www\.nicovideo\.jp/mylist/(?P<id>\d+)'
159
160     _TEST = {
161         'url': 'http://www.nicovideo.jp/mylist/27411728',
162         'info_dict': {
163             'id': '27411728',
164             'title': 'AKB48のオールナイトニッポン',
165         },
166         'playlist_mincount': 225,
167     }
168
169     def _real_extract(self, url):
170         list_id = self._match_id(url)
171         webpage = self._download_webpage(url, list_id)
172
173         entries_json = self._search_regex(r'Mylist\.preload\(\d+, (\[.*\])\);',
174                                           webpage, 'entries')
175         entries = json.loads(entries_json)
176         entries = [{
177             '_type': 'url',
178             'ie_key': NiconicoIE.ie_key(),
179             'url': ('http://www.nicovideo.jp/watch/%s' %
180                     entry['item_data']['video_id']),
181         } for entry in entries]
182
183         return {
184             '_type': 'playlist',
185             'title': self._search_regex(r'\s+name: "(.*?)"', webpage, 'title'),
186             'id': list_id,
187             'entries': entries,
188         }