douyutv.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import hashlib
  2. import time
  3. import urllib
  4. import uuid
  5. from .common import InfoExtractor
  6. from .openload import PhantomJSwrapper
  7. from ..utils import (
  8. ExtractorError,
  9. UserNotLive,
  10. determine_ext,
  11. int_or_none,
  12. js_to_json,
  13. parse_resolution,
  14. str_or_none,
  15. traverse_obj,
  16. unescapeHTML,
  17. url_or_none,
  18. urlencode_postdata,
  19. urljoin,
  20. )
  21. class DouyuBaseIE(InfoExtractor):
  22. def _download_cryptojs_md5(self, video_id):
  23. for url in [
  24. 'https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js',
  25. 'https://cdn.bootcdn.net/ajax/libs/crypto-js/3.1.2/rollups/md5.js',
  26. ]:
  27. js_code = self._download_webpage(
  28. url, video_id, note='Downloading signing dependency', fatal=False)
  29. if js_code:
  30. self.cache.store('douyu', 'crypto-js-md5', js_code)
  31. return js_code
  32. raise ExtractorError('Unable to download JS dependency (crypto-js/md5)')
  33. def _get_cryptojs_md5(self, video_id):
  34. return self.cache.load('douyu', 'crypto-js-md5') or self._download_cryptojs_md5(video_id)
  35. def _calc_sign(self, sign_func, video_id, a):
  36. b = uuid.uuid4().hex
  37. c = round(time.time())
  38. js_script = f'{self._get_cryptojs_md5(video_id)};{sign_func};console.log(ub98484234("{a}","{b}","{c}"))'
  39. phantom = PhantomJSwrapper(self)
  40. result = phantom.execute(js_script, video_id,
  41. note='Executing JS signing script').strip()
  42. return {i: v[0] for i, v in urllib.parse.parse_qs(result).items()}
  43. def _search_js_sign_func(self, webpage, fatal=True):
  44. # The greedy look-behind ensures last possible script tag is matched
  45. return self._search_regex(
  46. r'(?:<script.*)?<script[^>]*>(.*?ub98484234.*?)</script>', webpage, 'JS sign func', fatal=fatal)
  47. class DouyuTVIE(DouyuBaseIE):
  48. IE_DESC = '斗鱼直播'
  49. _VALID_URL = r'https?://(?:www\.)?douyu(?:tv)?\.com/(topic/\w+\?rid=|(?:[^/]+/))*(?P<id>[A-Za-z0-9]+)'
  50. _TESTS = [{
  51. 'url': 'https://www.douyu.com/pigff',
  52. 'info_dict': {
  53. 'id': '24422',
  54. 'display_id': 'pigff',
  55. 'ext': 'mp4',
  56. 'title': 're:^【PIGFF】.* [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  57. 'description': r'≥15级牌子看鱼吧置顶帖进粉丝vx群',
  58. 'thumbnail': str,
  59. 'uploader': 'pigff',
  60. 'is_live': True,
  61. 'live_status': 'is_live',
  62. },
  63. 'params': {
  64. 'skip_download': True,
  65. },
  66. }, {
  67. 'url': 'http://www.douyutv.com/85982',
  68. 'info_dict': {
  69. 'id': '85982',
  70. 'display_id': '85982',
  71. 'ext': 'flv',
  72. 'title': 're:^小漠从零单排记!——CSOL2躲猫猫 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  73. 'description': 'md5:746a2f7a253966a06755a912f0acc0d2',
  74. 'thumbnail': r're:^https?://.*\.png',
  75. 'uploader': 'douyu小漠',
  76. 'is_live': True,
  77. },
  78. 'params': {
  79. 'skip_download': True,
  80. },
  81. 'skip': 'Room not found',
  82. }, {
  83. 'url': 'http://www.douyutv.com/17732',
  84. 'info_dict': {
  85. 'id': '17732',
  86. 'display_id': '17732',
  87. 'ext': 'flv',
  88. 'title': 're:^清晨醒脑!根本停不下来! [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  89. 'description': r're:.*m7show@163\.com.*',
  90. 'thumbnail': r're:^https?://.*\.png',
  91. 'uploader': '7师傅',
  92. 'is_live': True,
  93. },
  94. 'params': {
  95. 'skip_download': True,
  96. },
  97. }, {
  98. 'url': 'https://www.douyu.com/topic/ydxc?rid=6560603',
  99. 'info_dict': {
  100. 'id': '6560603',
  101. 'display_id': '6560603',
  102. 'ext': 'flv',
  103. 'title': 're:^阿余:新年快乐恭喜发财! [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  104. 'description': 're:.*直播时间.*',
  105. 'thumbnail': r're:^https?://.*\.png',
  106. 'uploader': '阿涛皎月Carry',
  107. 'live_status': 'is_live',
  108. },
  109. 'params': {
  110. 'skip_download': True,
  111. },
  112. }, {
  113. 'url': 'http://www.douyu.com/xiaocang',
  114. 'only_matching': True,
  115. }, {
  116. # \"room_id\"
  117. 'url': 'http://www.douyu.com/t/lpl',
  118. 'only_matching': True,
  119. }]
  120. def _get_sign_func(self, room_id, video_id):
  121. return self._download_json(
  122. f'https://www.douyu.com/swf_api/homeH5Enc?rids={room_id}', video_id,
  123. note='Getting signing script')['data'][f'room{room_id}']
  124. def _extract_stream_formats(self, stream_formats):
  125. formats = []
  126. for stream_info in traverse_obj(stream_formats, (..., 'data')):
  127. stream_url = urljoin(
  128. traverse_obj(stream_info, 'rtmp_url'), traverse_obj(stream_info, 'rtmp_live'))
  129. if stream_url:
  130. rate_id = traverse_obj(stream_info, ('rate', {int_or_none}))
  131. rate_info = traverse_obj(stream_info, ('multirates', lambda _, v: v['rate'] == rate_id), get_all=False)
  132. ext = determine_ext(stream_url)
  133. formats.append({
  134. 'url': stream_url,
  135. 'format_id': str_or_none(rate_id),
  136. 'ext': 'mp4' if ext == 'm3u8' else ext,
  137. 'protocol': 'm3u8_native' if ext == 'm3u8' else 'https',
  138. 'quality': rate_id % -10000 if rate_id is not None else None,
  139. **traverse_obj(rate_info, {
  140. 'format': ('name', {str_or_none}),
  141. 'tbr': ('bit', {int_or_none}),
  142. }),
  143. })
  144. return formats
  145. def _real_extract(self, url):
  146. video_id = self._match_id(url)
  147. webpage = self._download_webpage(url, video_id)
  148. room_id = self._search_regex(r'\$ROOM\.room_id\s*=\s*(\d+)', webpage, 'room id')
  149. if self._search_regex(r'"videoLoop"\s*:\s*(\d+)', webpage, 'loop', default='') == '1':
  150. raise UserNotLive('The channel is auto-playing VODs', video_id=video_id)
  151. if self._search_regex(r'\$ROOM\.show_status\s*=\s*(\d+)', webpage, 'status', default='') == '2':
  152. raise UserNotLive(video_id=video_id)
  153. # Grab metadata from API
  154. params = {
  155. 'aid': 'wp',
  156. 'client_sys': 'wp',
  157. 'time': int(time.time()),
  158. }
  159. params['auth'] = hashlib.md5(
  160. f'room/{room_id}?{urllib.parse.urlencode(params)}zNzMV1y4EMxOHS6I5WKm'.encode()).hexdigest()
  161. room = traverse_obj(self._download_json(
  162. f'http://www.douyutv.com/api/v1/room/{room_id}', video_id,
  163. note='Downloading room info', query=params, fatal=False), 'data')
  164. # 1 = live, 2 = offline
  165. if traverse_obj(room, 'show_status') == '2':
  166. raise UserNotLive(video_id=video_id)
  167. js_sign_func = self._search_js_sign_func(webpage, fatal=False) or self._get_sign_func(room_id, video_id)
  168. form_data = {
  169. 'rate': 0,
  170. **self._calc_sign(js_sign_func, video_id, room_id),
  171. }
  172. stream_formats = [self._download_json(
  173. f'https://www.douyu.com/lapi/live/getH5Play/{room_id}',
  174. video_id, note='Downloading livestream format',
  175. data=urlencode_postdata(form_data))]
  176. for rate_id in traverse_obj(stream_formats[0], ('data', 'multirates', ..., 'rate')):
  177. if rate_id != traverse_obj(stream_formats[0], ('data', 'rate')):
  178. form_data['rate'] = rate_id
  179. stream_formats.append(self._download_json(
  180. f'https://www.douyu.com/lapi/live/getH5Play/{room_id}',
  181. video_id, note=f'Downloading livestream format {rate_id}',
  182. data=urlencode_postdata(form_data)))
  183. return {
  184. 'id': room_id,
  185. 'formats': self._extract_stream_formats(stream_formats),
  186. 'is_live': True,
  187. **traverse_obj(room, {
  188. 'display_id': ('url', {str}, {lambda i: i[1:]}),
  189. 'title': ('room_name', {unescapeHTML}),
  190. 'description': ('show_details', {str}),
  191. 'uploader': ('nickname', {str}),
  192. 'thumbnail': ('room_src', {url_or_none}),
  193. }),
  194. }
  195. class DouyuShowIE(DouyuBaseIE):
  196. _VALID_URL = r'https?://v(?:mobile)?\.douyu\.com/show/(?P<id>[0-9a-zA-Z]+)'
  197. _TESTS = [{
  198. 'url': 'https://v.douyu.com/show/mPyq7oVNe5Yv1gLY',
  199. 'info_dict': {
  200. 'id': 'mPyq7oVNe5Yv1gLY',
  201. 'ext': 'mp4',
  202. 'title': '四川人小时候的味道“蒜苗回锅肉”,传统菜不能丢,要常做来吃',
  203. 'duration': 633,
  204. 'thumbnail': str,
  205. 'uploader': '美食作家王刚V',
  206. 'uploader_id': 'OVAO4NVx1m7Q',
  207. 'timestamp': 1661850002,
  208. 'upload_date': '20220830',
  209. 'view_count': int,
  210. 'tags': ['美食', '美食综合'],
  211. },
  212. }, {
  213. 'url': 'https://vmobile.douyu.com/show/rjNBdvnVXNzvE2yw',
  214. 'only_matching': True,
  215. }]
  216. _FORMATS = {
  217. 'super': '原画',
  218. 'high': '超清',
  219. 'normal': '高清',
  220. }
  221. _QUALITIES = {
  222. 'super': -1,
  223. 'high': -2,
  224. 'normal': -3,
  225. }
  226. _RESOLUTIONS = {
  227. 'super': '1920x1080',
  228. 'high': '1280x720',
  229. 'normal': '852x480',
  230. }
  231. def _real_extract(self, url):
  232. url = url.replace('vmobile.', 'v.')
  233. video_id = self._match_id(url)
  234. webpage = self._download_webpage(url, video_id)
  235. video_info = self._search_json(
  236. r'<script>\s*window\.\$DATA\s*=', webpage,
  237. 'video info', video_id, transform_source=js_to_json)
  238. js_sign_func = self._search_js_sign_func(webpage)
  239. form_data = {
  240. 'vid': video_id,
  241. **self._calc_sign(js_sign_func, video_id, video_info['ROOM']['point_id']),
  242. }
  243. url_info = self._download_json(
  244. 'https://v.douyu.com/api/stream/getStreamUrl', video_id,
  245. data=urlencode_postdata(form_data), note='Downloading video formats')
  246. formats = []
  247. for name, url in traverse_obj(url_info, ('data', 'thumb_video', {dict.items}, ...)):
  248. video_url = traverse_obj(url, ('url', {url_or_none}))
  249. if video_url:
  250. ext = determine_ext(video_url)
  251. formats.append({
  252. 'format': self._FORMATS.get(name),
  253. 'format_id': name,
  254. 'url': video_url,
  255. 'quality': self._QUALITIES.get(name),
  256. 'ext': 'mp4' if ext == 'm3u8' else ext,
  257. 'protocol': 'm3u8_native' if ext == 'm3u8' else 'https',
  258. **parse_resolution(self._RESOLUTIONS.get(name)),
  259. })
  260. else:
  261. self.to_screen(
  262. f'"{self._FORMATS.get(name, name)}" format may require logging in. {self._login_hint()}')
  263. return {
  264. 'id': video_id,
  265. 'formats': formats,
  266. **traverse_obj(video_info, ('DATA', {
  267. 'title': ('content', 'title', {str}),
  268. 'uploader': ('content', 'author', {str}),
  269. 'uploader_id': ('content', 'up_id', {str_or_none}),
  270. 'duration': ('content', 'video_duration', {int_or_none}),
  271. 'thumbnail': ('content', 'video_pic', {url_or_none}),
  272. 'timestamp': ('content', 'create_time', {int_or_none}),
  273. 'view_count': ('content', 'view_num', {int_or_none}),
  274. 'tags': ('videoTag', ..., 'tagName', {str}),
  275. })),
  276. }