Merge pull request #3180 from hakatashi/niconico-without-authentication
[youtube-dl] / youtube_dl / extractor / niconico.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     compat_urllib_parse,
9     compat_urllib_request,
10     compat_urlparse,
11     ExtractorError,
12     unified_strdate,
13     parse_duration,
14     int_or_none,
15 )
16
17
18 class NiconicoIE(InfoExtractor):
19     IE_NAME = 'niconico'
20     IE_DESC = 'ニコニコ動画'
21
22     _TEST = {
23         'url': 'http://www.nicovideo.jp/watch/sm22312215',
24         'md5': 'd1a75c0823e2f629128c43e1212760f9',
25         'info_dict': {
26             'id': 'sm22312215',
27             'ext': 'mp4',
28             'title': 'Big Buck Bunny',
29             'uploader': 'takuya0301',
30             'uploader_id': '2698420',
31             'upload_date': '20131123',
32             'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
33             'duration': 33,
34         },
35         'params': {
36             'username': 'ydl.niconico@gmail.com',
37             'password': 'youtube-dl',
38         },
39     }
40
41     _VALID_URL = r'https?://(?:www\.|secure\.)?nicovideo\.jp/watch/((?:[a-z]{2})?[0-9]+)'
42     _NETRC_MACHINE = 'niconico'
43     # Determine whether the downloader uses authentication to download video
44     _AUTHENTICATE = False
45
46     def _real_initialize(self):
47         if self._downloader.params.get('username', None) is not None:
48             self._AUTHENTICATE = True
49
50         if self._AUTHENTICATE:
51             self._login()
52
53     def _login(self):
54         (username, password) = self._get_login_info()
55
56         # Log in
57         login_form_strs = {
58             'mail': username,
59             'password': password,
60         }
61         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
62         # chokes on unicode
63         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k, v in login_form_strs.items())
64         login_data = compat_urllib_parse.urlencode(login_form).encode('utf-8')
65         request = compat_urllib_request.Request(
66             'https://secure.nicovideo.jp/secure/login', login_data)
67         login_results = self._download_webpage(
68             request, None, note='Logging in', errnote='Unable to log in')
69         if re.search(r'(?i)<h1 class="mb8p4">Log in error</h1>', login_results) is not None:
70             self._downloader.report_warning('unable to log in: bad username or password')
71             return False
72         return True
73
74     def _real_extract(self, url):
75         mobj = re.match(self._VALID_URL, url)
76         video_id = mobj.group(1)
77
78         # Get video webpage. We are not actually interested in it, but need
79         # the cookies in order to be able to download the info webpage
80         self._download_webpage('http://www.nicovideo.jp/watch/' + video_id, video_id)
81
82         video_info = self._download_xml(
83             'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, video_id,
84             note='Downloading video info page')
85
86         if self._AUTHENTICATE:
87             # Get flv info
88             flv_info_webpage = self._download_webpage(
89                 'http://flapi.nicovideo.jp/api/getflv?v=' + video_id,
90                 video_id, 'Downloading flv info')
91         else:
92             # Get external player info
93             ext_player_info = self._download_webpage(
94                 'http://ext.nicovideo.jp/thumb_watch/' + video_id, video_id)
95             thumb_play_key = self._search_regex(
96                 r'\'thumbPlayKey\'\s*:\s*\'(.*?)\'', ext_player_info, 'thumbPlayKey')
97
98             # Get flv info
99             flv_info_data = compat_urllib_parse.urlencode({
100                 'k': thumb_play_key,
101                 'v': video_id
102             })
103             flv_info_request = compat_urllib_request.Request(
104                 'http://ext.nicovideo.jp/thumb_watch', flv_info_data,
105                 {'Content-Type': 'application/x-www-form-urlencoded'})
106             flv_info_webpage = self._download_webpage(
107                 flv_info_request, video_id,
108                 note='Downloading flv info', errnote='Unable to download flv info')
109
110         video_real_url = compat_urlparse.parse_qs(flv_info_webpage)['url'][0]
111
112         # Start extracting information
113         title = video_info.find('.//title').text
114         extension = video_info.find('.//movie_type').text
115         video_format = extension.upper()
116         thumbnail = video_info.find('.//thumbnail_url').text
117         description = video_info.find('.//description').text
118         upload_date = unified_strdate(video_info.find('.//first_retrieve').text.split('+')[0])
119         view_count = int_or_none(video_info.find('.//view_counter').text)
120         comment_count = int_or_none(video_info.find('.//comment_num').text)
121         duration = parse_duration(video_info.find('.//length').text)
122         webpage_url = video_info.find('.//watch_url').text
123
124         if video_info.find('.//ch_id') is not None:
125             uploader_id = video_info.find('.//ch_id').text
126             uploader = video_info.find('.//ch_name').text
127         elif video_info.find('.//user_id') is not None:
128             uploader_id = video_info.find('.//user_id').text
129             uploader = video_info.find('.//user_nickname').text
130         else:
131             uploader_id = uploader = None
132
133         return {
134             'id': video_id,
135             'url': video_real_url,
136             'title': title,
137             'ext': extension,
138             'format': video_format,
139             'thumbnail': thumbnail,
140             'description': description,
141             'uploader': uploader,
142             'upload_date': upload_date,
143             'uploader_id': uploader_id,
144             'view_count': view_count,
145             'comment_count': comment_count,
146             'duration': duration,
147             'webpage_url': webpage_url,
148         }