]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/niconico.py
[niconico] Simplify and make work with old Python versions
[youtube-dl] / youtube_dl / extractor / niconico.py
1 # encoding: utf-8
2
3 import re
4 import socket
5 import xml.etree.ElementTree
6
7 from .common import InfoExtractor
8 from ..utils import (
9     compat_http_client,
10     compat_urllib_error,
11     compat_urllib_parse,
12     compat_urllib_request,
13     compat_urlparse,
14     compat_str,
15
16     ExtractorError,
17     unified_strdate,
18 )
19
20
21 class NiconicoIE(InfoExtractor):
22     IE_NAME = u'niconico'
23     IE_DESC = u'ニコニコ動画'
24
25     _TEST = {
26         u'url': u'http://www.nicovideo.jp/watch/sm22312215',
27         u'file': u'sm22312215.mp4',
28         u'md5': u'd1a75c0823e2f629128c43e1212760f9',
29         u'info_dict': {
30             u'title': u'Big Buck Bunny',
31             u'uploader': u'takuya0301',
32             u'uploader_id': u'2698420',
33             u'upload_date': u'20131123',
34             u'description': u'(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
35         },
36         u'params': {
37             u'username': u'ydl.niconico@gmail.com',
38             u'password': u'youtube-dl',
39         },
40     }
41
42     _VALID_URL = r'^https?://(?:www\.|secure\.)?nicovideo\.jp/watch/([a-z][a-z][0-9]+)(?:.*)$'
43     _NETRC_MACHINE = 'niconico'
44     # If True it will raise an error if no login info is provided
45     _LOGIN_REQUIRED = True
46
47     def _real_initialize(self):
48         self._login()
49
50     def _login(self):
51         (username, password) = self._get_login_info()
52         # No authentication to be performed
53         if username is None:
54             if self._LOGIN_REQUIRED:
55                 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
56             return False
57
58         # Log in
59         login_form_strs = {
60             u'mail': username,
61             u'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             u'https://secure.nicovideo.jp/secure/login', login_data)
69         login_results = self._download_webpage(
70             request, u'', note=u'Logging in', errnote=u'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(u'unable to log in: bad username or password')
73             return False
74         return True
75
76     def _real_extract(self, url):
77         mobj = re.match(self._VALID_URL, url)
78         video_id = mobj.group(1)
79
80         # Get video webpage
81         video_webpage = self._download_webpage(
82             'http://www.nicovideo.jp/watch/' + video_id, video_id)
83
84         video_info_webpage = self._download_webpage(
85             'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, video_id,
86             note=u'Downloading video info page')
87
88         # Get flv info
89         flv_info_webpage = self._download_webpage(
90             u'http://flapi.nicovideo.jp/api/getflv?v=' + video_id,
91             video_id, u'Downloading flv info')
92         video_real_url = compat_urlparse.parse_qs(flv_info_webpage)['url'][0]
93
94         # Start extracting information
95         video_info = xml.etree.ElementTree.fromstring(video_info_webpage)
96         video_title = video_info.find('.//title').text
97         video_extension = video_info.find('.//movie_type').text
98         video_format = video_extension.upper()
99         video_thumbnail = video_info.find('.//thumbnail_url').text
100         video_description = video_info.find('.//description').text
101         video_uploader_id = video_info.find('.//user_id').text
102         video_upload_date = unified_strdate(video_info.find('.//first_retrieve').text.split('+')[0])
103         video_view_count = video_info.find('.//view_counter').text
104         video_webpage_url = video_info.find('.//watch_url').text
105
106         # uploader
107         video_uploader = video_uploader_id
108         url = 'http://seiga.nicovideo.jp/api/user/info?id=' + video_uploader_id
109         try:
110             user_info_webpage = self._download_webpage(
111                 url, video_id, note=u'Downloading user information')
112         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
113             self._downloader.report_warning(u'Unable to download user info webpage: %s' % compat_str(err))
114         else:
115             user_info = xml.etree.ElementTree.fromstring(user_info_webpage)
116             video_uploader = user_info.find('.//nickname').text
117
118         return {
119             'id':          video_id,
120             'url':         video_real_url,
121             'title':       video_title,
122             'ext':         video_extension,
123             'format':      video_format,
124             'thumbnail':   video_thumbnail,
125             'description': video_description,
126             'uploader':    video_uploader,
127             'upload_date': video_upload_date,
128             'uploader_id': video_uploader_id,
129             'view_count':  video_view_count,
130             'webpage_url': video_webpage_url,
131         }