You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

421 lines
15 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import hashlib
  4. import re
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_parse_qs,
  8. compat_urlparse,
  9. )
  10. from ..utils import (
  11. ExtractorError,
  12. int_or_none,
  13. float_or_none,
  14. parse_iso8601,
  15. smuggle_url,
  16. str_or_none,
  17. strip_jsonp,
  18. unified_timestamp,
  19. unsmuggle_url,
  20. urlencode_postdata,
  21. )
  22. class BiliBiliIE(InfoExtractor):
  23. _VALID_URL = r'https?://(?:www\.|bangumi\.|)bilibili\.(?:tv|com)/(?:video/av|anime/(?P<anime_id>\d+)/play#)(?P<id>\d+)'
  24. _TESTS = [{
  25. 'url': 'http://www.bilibili.tv/video/av1074402/',
  26. 'md5': '5f7d29e1a2872f3df0cf76b1f87d3788',
  27. 'info_dict': {
  28. 'id': '1074402',
  29. 'ext': 'flv',
  30. 'title': '【金坷垃】金泡沫',
  31. 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
  32. 'duration': 308.067,
  33. 'timestamp': 1398012678,
  34. 'upload_date': '20140420',
  35. 'thumbnail': r're:^https?://.+\.jpg',
  36. 'uploader': '菊子桑',
  37. 'uploader_id': '156160',
  38. },
  39. }, {
  40. # Tested in BiliBiliBangumiIE
  41. 'url': 'http://bangumi.bilibili.com/anime/1869/play#40062',
  42. 'only_matching': True,
  43. }, {
  44. 'url': 'http://bangumi.bilibili.com/anime/5802/play#100643',
  45. 'md5': '3f721ad1e75030cc06faf73587cfec57',
  46. 'info_dict': {
  47. 'id': '100643',
  48. 'ext': 'mp4',
  49. 'title': 'CHAOS;CHILD',
  50. 'description': '如果你是神明,并且能够让妄想成为现实。那你会进行怎么样的妄想?是淫靡的世界?独裁社会?毁灭性的制裁?还是……2015年,涩谷。从6年前发生的大灾害“涩谷地震”之后复兴了的这个街区里新设立的私立高中...',
  51. },
  52. 'skip': 'Geo-restricted to China',
  53. }, {
  54. # Title with double quotes
  55. 'url': 'http://www.bilibili.com/video/av8903802/',
  56. 'info_dict': {
  57. 'id': '8903802',
  58. 'title': '阿滴英文|英文歌分享#6 "Closer',
  59. 'description': '滴妹今天唱Closer給你聽! 有史以来,被推最多次也是最久的歌曲,其实歌词跟我原本想像差蛮多的,不过还是好听! 微博@阿滴英文',
  60. },
  61. 'playlist': [{
  62. 'info_dict': {
  63. 'id': '8903802_part1',
  64. 'ext': 'flv',
  65. 'title': '阿滴英文|英文歌分享#6 "Closer',
  66. 'description': 'md5:3b1b9e25b78da4ef87e9b548b88ee76a',
  67. 'uploader': '阿滴英文',
  68. 'uploader_id': '65880958',
  69. 'timestamp': 1488382634,
  70. 'upload_date': '20170301',
  71. },
  72. 'params': {
  73. 'skip_download': True, # Test metadata only
  74. },
  75. }, {
  76. 'info_dict': {
  77. 'id': '8903802_part2',
  78. 'ext': 'flv',
  79. 'title': '阿滴英文|英文歌分享#6 "Closer',
  80. 'description': 'md5:3b1b9e25b78da4ef87e9b548b88ee76a',
  81. 'uploader': '阿滴英文',
  82. 'uploader_id': '65880958',
  83. 'timestamp': 1488382634,
  84. 'upload_date': '20170301',
  85. },
  86. 'params': {
  87. 'skip_download': True, # Test metadata only
  88. },
  89. }]
  90. }]
  91. _APP_KEY = 'iVGUTjsxvpLeuDCf'
  92. _BILIBILI_KEY = 'aHRmhWMLkdeMuILqORnYZocwMBpMEOdt'
  93. def _report_error(self, result):
  94. if 'message' in result:
  95. raise ExtractorError('%s said: %s' % (self.IE_NAME, result['message']), expected=True)
  96. elif 'code' in result:
  97. raise ExtractorError('%s returns error %d' % (self.IE_NAME, result['code']), expected=True)
  98. else:
  99. raise ExtractorError('Can\'t extract Bangumi episode ID')
  100. def _real_extract(self, url):
  101. url, smuggled_data = unsmuggle_url(url, {})
  102. mobj = re.match(self._VALID_URL, url)
  103. video_id = mobj.group('id')
  104. anime_id = mobj.group('anime_id')
  105. webpage = self._download_webpage(url, video_id)
  106. if 'anime/' not in url:
  107. cid = self._search_regex(
  108. r'\bcid(?:["\']:|=)(\d+)', webpage, 'cid',
  109. default=None
  110. ) or compat_parse_qs(self._search_regex(
  111. [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
  112. r'EmbedPlayer\([^)]+,\s*\\"([^"]+)\\"\)',
  113. r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
  114. webpage, 'player parameters'))['cid'][0]
  115. else:
  116. if 'no_bangumi_tip' not in smuggled_data:
  117. self.to_screen('Downloading episode %s. To download all videos in anime %s, re-run youtube-dl with %s' % (
  118. video_id, anime_id, compat_urlparse.urljoin(url, '//bangumi.bilibili.com/anime/%s' % anime_id)))
  119. headers = {
  120. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  121. 'Referer': url
  122. }
  123. headers.update(self.geo_verification_headers())
  124. js = self._download_json(
  125. 'http://bangumi.bilibili.com/web_api/get_source', video_id,
  126. data=urlencode_postdata({'episode_id': video_id}),
  127. headers=headers)
  128. if 'result' not in js:
  129. self._report_error(js)
  130. cid = js['result']['cid']
  131. headers = {
  132. 'Referer': url
  133. }
  134. headers.update(self.geo_verification_headers())
  135. entries = []
  136. RENDITIONS = ('qn=80&quality=80&type=', 'quality=2&type=mp4')
  137. for num, rendition in enumerate(RENDITIONS, start=1):
  138. payload = 'appkey=%s&cid=%s&otype=json&%s' % (self._APP_KEY, cid, rendition)
  139. sign = hashlib.md5((payload + self._BILIBILI_KEY).encode('utf-8')).hexdigest()
  140. video_info = self._download_json(
  141. 'http://interface.bilibili.com/v2/playurl?%s&sign=%s' % (payload, sign),
  142. video_id, note='Downloading video info page',
  143. headers=headers, fatal=num == len(RENDITIONS))
  144. if not video_info:
  145. continue
  146. if 'durl' not in video_info:
  147. if num < len(RENDITIONS):
  148. continue
  149. self._report_error(video_info)
  150. for idx, durl in enumerate(video_info['durl']):
  151. formats = [{
  152. 'url': durl['url'],
  153. 'filesize': int_or_none(durl['size']),
  154. }]
  155. for backup_url in durl.get('backup_url', []):
  156. formats.append({
  157. 'url': backup_url,
  158. # backup URLs have lower priorities
  159. 'preference': -2 if 'hd.mp4' in backup_url else -3,
  160. })
  161. for a_format in formats:
  162. a_format.setdefault('http_headers', {}).update({
  163. 'Referer': url,
  164. })
  165. self._sort_formats(formats)
  166. entries.append({
  167. 'id': '%s_part%s' % (video_id, idx),
  168. 'duration': float_or_none(durl.get('length'), 1000),
  169. 'formats': formats,
  170. })
  171. break
  172. title = self._html_search_regex(
  173. ('<h1[^>]+\btitle=(["\'])(?P<title>(?:(?!\1).)+)\1',
  174. '(?s)<h1[^>]*>(?P<title>.+?)</h1>'), webpage, 'title',
  175. group='title')
  176. description = self._html_search_meta('description', webpage)
  177. timestamp = unified_timestamp(self._html_search_regex(
  178. r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time',
  179. default=None) or self._html_search_meta(
  180. 'uploadDate', webpage, 'timestamp', default=None))
  181. thumbnail = self._html_search_meta(['og:image', 'thumbnailUrl'], webpage)
  182. # TODO 'view_count' requires deobfuscating Javascript
  183. info = {
  184. 'id': video_id,
  185. 'title': title,
  186. 'description': description,
  187. 'timestamp': timestamp,
  188. 'thumbnail': thumbnail,
  189. 'duration': float_or_none(video_info.get('timelength'), scale=1000),
  190. }
  191. uploader_mobj = re.search(
  192. r'<a[^>]+href="(?:https?:)?//space\.bilibili\.com/(?P<id>\d+)"[^>]*>(?P<name>[^<]+)',
  193. webpage)
  194. if uploader_mobj:
  195. info.update({
  196. 'uploader': uploader_mobj.group('name'),
  197. 'uploader_id': uploader_mobj.group('id'),
  198. })
  199. if not info.get('uploader'):
  200. info['uploader'] = self._html_search_meta(
  201. 'author', webpage, 'uploader', default=None)
  202. for entry in entries:
  203. entry.update(info)
  204. if len(entries) == 1:
  205. return entries[0]
  206. else:
  207. for idx, entry in enumerate(entries):
  208. entry['id'] = '%s_part%d' % (video_id, (idx + 1))
  209. return {
  210. '_type': 'multi_video',
  211. 'id': video_id,
  212. 'title': title,
  213. 'description': description,
  214. 'entries': entries,
  215. }
  216. class BiliBiliBangumiIE(InfoExtractor):
  217. _VALID_URL = r'https?://bangumi\.bilibili\.com/anime/(?P<id>\d+)'
  218. IE_NAME = 'bangumi.bilibili.com'
  219. IE_DESC = 'BiliBili番剧'
  220. _TESTS = [{
  221. 'url': 'http://bangumi.bilibili.com/anime/1869',
  222. 'info_dict': {
  223. 'id': '1869',
  224. 'title': '混沌武士',
  225. 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
  226. },
  227. 'playlist_count': 26,
  228. }, {
  229. 'url': 'http://bangumi.bilibili.com/anime/1869',
  230. 'info_dict': {
  231. 'id': '1869',
  232. 'title': '混沌武士',
  233. 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
  234. },
  235. 'playlist': [{
  236. 'md5': '91da8621454dd58316851c27c68b0c13',
  237. 'info_dict': {
  238. 'id': '40062',
  239. 'ext': 'mp4',
  240. 'title': '混沌武士',
  241. 'description': '故事发生在日本的江户时代。风是一个小酒馆的打工女。一日,酒馆里来了一群恶霸,虽然他们的举动令风十分不满,但是毕竟风只是一届女流,无法对他们采取什么行动,只能在心里嘟哝。这时,酒家里又进来了个“不良份子...',
  242. 'timestamp': 1414538739,
  243. 'upload_date': '20141028',
  244. 'episode': '疾风怒涛 Tempestuous Temperaments',
  245. 'episode_number': 1,
  246. },
  247. }],
  248. 'params': {
  249. 'playlist_items': '1',
  250. },
  251. }]
  252. @classmethod
  253. def suitable(cls, url):
  254. return False if BiliBiliIE.suitable(url) else super(BiliBiliBangumiIE, cls).suitable(url)
  255. def _real_extract(self, url):
  256. bangumi_id = self._match_id(url)
  257. # Sometimes this API returns a JSONP response
  258. season_info = self._download_json(
  259. 'http://bangumi.bilibili.com/jsonp/seasoninfo/%s.ver' % bangumi_id,
  260. bangumi_id, transform_source=strip_jsonp)['result']
  261. entries = [{
  262. '_type': 'url_transparent',
  263. 'url': smuggle_url(episode['webplay_url'], {'no_bangumi_tip': 1}),
  264. 'ie_key': BiliBiliIE.ie_key(),
  265. 'timestamp': parse_iso8601(episode.get('update_time'), delimiter=' '),
  266. 'episode': episode.get('index_title'),
  267. 'episode_number': int_or_none(episode.get('index')),
  268. } for episode in season_info['episodes']]
  269. entries = sorted(entries, key=lambda entry: entry.get('episode_number'))
  270. return self.playlist_result(
  271. entries, bangumi_id,
  272. season_info.get('bangumi_title'), season_info.get('evaluate'))
  273. class BilibiliAudioBaseIE(InfoExtractor):
  274. def _call_api(self, path, sid, query=None):
  275. if not query:
  276. query = {'sid': sid}
  277. return self._download_json(
  278. 'https://www.bilibili.com/audio/music-service-c/web/' + path,
  279. sid, query=query)['data']
  280. class BilibiliAudioIE(BilibiliAudioBaseIE):
  281. _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/au(?P<id>\d+)'
  282. _TEST = {
  283. 'url': 'https://www.bilibili.com/audio/au1003142',
  284. 'md5': 'fec4987014ec94ef9e666d4d158ad03b',
  285. 'info_dict': {
  286. 'id': '1003142',
  287. 'ext': 'm4a',
  288. 'title': '【tsukimi】YELLOW / 神山羊',
  289. 'artist': 'tsukimi',
  290. 'comment_count': int,
  291. 'description': 'YELLOW的mp3版!',
  292. 'duration': 183,
  293. 'subtitles': {
  294. 'origin': [{
  295. 'ext': 'lrc',
  296. }],
  297. },
  298. 'thumbnail': r're:^https?://.+\.jpg',
  299. 'timestamp': 1564836614,
  300. 'upload_date': '20190803',
  301. 'uploader': 'tsukimi-つきみぐー',
  302. 'view_count': int,
  303. },
  304. }
  305. def _real_extract(self, url):
  306. au_id = self._match_id(url)
  307. play_data = self._call_api('url', au_id)
  308. formats = [{
  309. 'url': play_data['cdns'][0],
  310. 'filesize': int_or_none(play_data.get('size')),
  311. }]
  312. song = self._call_api('song/info', au_id)
  313. title = song['title']
  314. statistic = song.get('statistic') or {}
  315. subtitles = None
  316. lyric = song.get('lyric')
  317. if lyric:
  318. subtitles = {
  319. 'origin': [{
  320. 'url': lyric,
  321. }]
  322. }
  323. return {
  324. 'id': au_id,
  325. 'title': title,
  326. 'formats': formats,
  327. 'artist': song.get('author'),
  328. 'comment_count': int_or_none(statistic.get('comment')),
  329. 'description': song.get('intro'),
  330. 'duration': int_or_none(song.get('duration')),
  331. 'subtitles': subtitles,
  332. 'thumbnail': song.get('cover'),
  333. 'timestamp': int_or_none(song.get('passtime')),
  334. 'uploader': song.get('uname'),
  335. 'view_count': int_or_none(statistic.get('play')),
  336. }
  337. class BilibiliAudioAlbumIE(BilibiliAudioBaseIE):
  338. _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/am(?P<id>\d+)'
  339. _TEST = {
  340. 'url': 'https://www.bilibili.com/audio/am10624',
  341. 'info_dict': {
  342. 'id': '10624',
  343. 'title': '每日新曲推荐(每日11:00更新)',
  344. 'description': '每天11:00更新,为你推送最新音乐',
  345. },
  346. 'playlist_count': 19,
  347. }
  348. def _real_extract(self, url):
  349. am_id = self._match_id(url)
  350. songs = self._call_api(
  351. 'song/of-menu', am_id, {'sid': am_id, 'pn': 1, 'ps': 100})['data']
  352. entries = []
  353. for song in songs:
  354. sid = str_or_none(song.get('id'))
  355. if not sid:
  356. continue
  357. entries.append(self.url_result(
  358. 'https://www.bilibili.com/audio/au' + sid,
  359. BilibiliAudioIE.ie_key(), sid))
  360. if entries:
  361. album_data = self._call_api('menu/info', am_id) or {}
  362. album_title = album_data.get('title')
  363. if album_title:
  364. for entry in entries:
  365. entry['album'] = album_title
  366. return self.playlist_result(
  367. entries, am_id, album_title, album_data.get('intro'))
  368. return self.playlist_result(entries, am_id)