niconico.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # encoding: utf-8
  2. import re
  3. import socket
  4. import xml.etree.ElementTree
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. compat_http_client,
  8. compat_urllib_error,
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. compat_urlparse,
  12. compat_str,
  13. ExtractorError,
  14. unified_strdate,
  15. )
  16. class NiconicoIE(InfoExtractor):
  17. IE_NAME = u'niconico'
  18. IE_DESC = u'ニコニコ動画'
  19. _TEST = {
  20. u'url': u'http://www.nicovideo.jp/watch/sm22312215',
  21. u'file': u'sm22312215.mp4',
  22. u'md5': u'd1a75c0823e2f629128c43e1212760f9',
  23. u'info_dict': {
  24. u'title': u'Big Buck Bunny',
  25. u'uploader': u'takuya0301',
  26. u'uploader_id': u'2698420',
  27. u'upload_date': u'20131123',
  28. u'description': u'(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
  29. },
  30. u'params': {
  31. u'username': u'ydl.niconico@gmail.com',
  32. u'password': u'youtube-dl',
  33. },
  34. }
  35. _VALID_URL = r'^(?:https?://)?(?:www\.)?nicovideo\.jp/watch/([a-z][a-z][0-9]+)(?:.*)$'
  36. _LOGIN_URL = 'https://secure.nicovideo.jp/secure/login'
  37. _NETRC_MACHINE = 'niconico'
  38. # If True it will raise an error if no login info is provided
  39. _LOGIN_REQUIRED = True
  40. def _real_initialize(self):
  41. self._login()
  42. def _login(self):
  43. (username, password) = self._get_login_info()
  44. # No authentication to be performed
  45. if username is None:
  46. if self._LOGIN_REQUIRED:
  47. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  48. return False
  49. # Log in
  50. login_form_strs = {
  51. u'mail': username,
  52. u'password': password,
  53. }
  54. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  55. # chokes on unicode
  56. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  57. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  58. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  59. try:
  60. self.report_login()
  61. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  62. if re.search(r'(?i)<h1 class="mb8p4">Log in error</h1>', login_results) is not None:
  63. self._downloader.report_warning(u'unable to log in: bad username or password')
  64. return False
  65. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  66. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  67. return False
  68. return True
  69. def _real_extract(self, url):
  70. video_id = self._extract_id(url)
  71. # Get video webpage
  72. self.report_video_webpage_download(video_id)
  73. url = 'http://www.nicovideo.jp/watch/' + video_id
  74. request = compat_urllib_request.Request(url)
  75. try:
  76. video_webpage = compat_urllib_request.urlopen(request).read()
  77. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  78. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  79. # Get video info
  80. self.report_video_info_webpage_download(video_id)
  81. url = 'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id
  82. request = compat_urllib_request.Request(url)
  83. try:
  84. video_info_webpage = compat_urllib_request.urlopen(request).read()
  85. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  86. raise ExtractorError(u'Unable to download video info webpage: %s' % compat_str(err))
  87. # Get flv info
  88. self.report_flv_info_webpage_download(video_id)
  89. url = 'http://flapi.nicovideo.jp/api/getflv?v=' + video_id
  90. request = compat_urllib_request.Request(url)
  91. try:
  92. flv_info_webpage = compat_urllib_request.urlopen(request).read()
  93. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  94. raise ExtractorError(u'Unable to download flv info webpage: %s' % compat_str(err))
  95. # Start extracting information
  96. self.report_information_extraction(video_id)
  97. video_info = xml.etree.ElementTree.fromstring(video_info_webpage)
  98. # url
  99. video_real_url = compat_urlparse.parse_qs(flv_info_webpage.decode('utf-8'))['url'][0]
  100. # title
  101. video_title = video_info.find('.//title').text
  102. # ext
  103. video_extension = video_info.find('.//movie_type').text
  104. # format
  105. video_format = video_extension.upper()
  106. # thumbnail
  107. video_thumbnail = video_info.find('.//thumbnail_url').text
  108. # description
  109. video_description = video_info.find('.//description').text
  110. # uploader_id
  111. video_uploader_id = video_info.find('.//user_id').text
  112. # uploader
  113. url = 'http://seiga.nicovideo.jp/api/user/info?id=' + video_uploader_id
  114. request = compat_urllib_request.Request(url)
  115. try:
  116. user_info_webpage = compat_urllib_request.urlopen(request).read()
  117. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  118. self._downloader.report_warning(u'Unable to download user info webpage: %s' % compat_str(err))
  119. user_info = xml.etree.ElementTree.fromstring(user_info_webpage)
  120. video_uploader = user_info.find('.//nickname').text
  121. # uploder_date
  122. video_upload_date = unified_strdate(video_info.find('.//first_retrieve').text.split('+')[0])
  123. # view_count
  124. video_view_count = video_info.find('.//view_counter').text
  125. # webpage_url
  126. video_webpage_url = video_info.find('.//watch_url').text
  127. return {
  128. 'id': video_id,
  129. 'url': video_real_url,
  130. 'title': video_title,
  131. 'ext': video_extension,
  132. 'format': video_format,
  133. 'thumbnail': video_thumbnail,
  134. 'description': video_description,
  135. 'uploader': video_uploader,
  136. 'upload_date': video_upload_date,
  137. 'uploader_id': video_uploader_id,
  138. 'view_count': video_view_count,
  139. 'webpage_url': video_webpage_url,
  140. }
  141. def _extract_id(self, url):
  142. mobj = re.match(self._VALID_URL, url)
  143. if mobj is None:
  144. raise ExtractorError(u'Invalid URL: %s' % url)
  145. video_id = mobj.group(1)
  146. return video_id
  147. def report_video_webpage_download(self, video_id):
  148. """Report attempt to download video webpage."""
  149. self.to_screen(u'%s: Downloading video webpage' % video_id)
  150. def report_video_info_webpage_download(self, video_id):
  151. """Report attempt to download video info webpage."""
  152. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  153. def report_flv_info_webpage_download(self, video_id):
  154. """Report attempt to download flv info webpage."""
  155. self.to_screen(u'%s: Downloading flv info webpage' % video_id)
  156. def report_information_extraction(self, video_id):
  157. """Report attempt to extract video information."""
  158. self.to_screen(u'%s: Extracting video information' % video_id)