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.

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