niconico.py 8.5 KB

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