logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

ximalaya.py (9585B)


  1. import base64
  2. import math
  3. import time
  4. from .common import InfoExtractor
  5. from .videa import VideaIE
  6. from ..utils import (
  7. InAdvancePagedList,
  8. int_or_none,
  9. str_or_none,
  10. traverse_obj,
  11. try_call,
  12. update_url_query,
  13. )
  14. class XimalayaBaseIE(InfoExtractor):
  15. _GEO_COUNTRIES = ['CN']
  16. class XimalayaIE(XimalayaBaseIE):
  17. IE_NAME = 'ximalaya'
  18. IE_DESC = '喜马拉雅FM'
  19. _VALID_URL = r'https?://(?:www\.|m\.)?ximalaya\.com/(?:(?P<uid>\d+)/)?sound/(?P<id>[0-9]+)'
  20. _TESTS = [
  21. {
  22. 'url': 'http://www.ximalaya.com/sound/47740352/',
  23. 'info_dict': {
  24. 'id': '47740352',
  25. 'ext': 'm4a',
  26. 'uploader': '小彬彬爱听书',
  27. 'uploader_id': '61425525',
  28. 'uploader_url': 'http://www.ximalaya.com/zhubo/61425525/',
  29. 'title': '261.唐诗三百首.卷八.送孟浩然之广陵.李白',
  30. 'description': 'contains:《送孟浩然之广陵》\n作者:李白\n故人西辞黄鹤楼,烟花三月下扬州。\n孤帆远影碧空尽,惟见长江天际流。',
  31. 'thumbnail': r're:^https?://.*\.jpg',
  32. 'thumbnails': [
  33. {
  34. 'name': 'cover_url',
  35. 'url': r're:^https?://.*\.jpg',
  36. },
  37. {
  38. 'name': 'cover_url_142',
  39. 'url': r're:^https?://.*\.jpg',
  40. 'width': 180,
  41. 'height': 180,
  42. },
  43. ],
  44. 'categories': ['其他'],
  45. 'duration': 93,
  46. 'view_count': int,
  47. 'like_count': int,
  48. },
  49. },
  50. {
  51. 'url': 'http://m.ximalaya.com/61425525/sound/47740352/',
  52. 'info_dict': {
  53. 'id': '47740352',
  54. 'ext': 'm4a',
  55. 'uploader': '小彬彬爱听书',
  56. 'uploader_id': '61425525',
  57. 'uploader_url': 'http://www.ximalaya.com/zhubo/61425525/',
  58. 'title': '261.唐诗三百首.卷八.送孟浩然之广陵.李白',
  59. 'description': 'contains:《送孟浩然之广陵》\n作者:李白\n故人西辞黄鹤楼,烟花三月下扬州。\n孤帆远影碧空尽,惟见长江天际流。',
  60. 'thumbnail': r're:^https?://.*\.jpg',
  61. 'thumbnails': [
  62. {
  63. 'name': 'cover_url',
  64. 'url': r're:^https?://.*\.jpg',
  65. },
  66. {
  67. 'name': 'cover_url_142',
  68. 'url': r're:^https?://.*\.jpg',
  69. 'width': 180,
  70. 'height': 180,
  71. },
  72. ],
  73. 'categories': ['人文'],
  74. 'duration': 93,
  75. 'view_count': int,
  76. 'like_count': int,
  77. },
  78. },
  79. {
  80. # VIP-restricted audio
  81. 'url': 'https://www.ximalaya.com/sound/562111701',
  82. 'only_matching': True,
  83. },
  84. ]
  85. @staticmethod
  86. def _decrypt_filename(file_id, seed):
  87. cgstr = ''
  88. key = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\:._-1234567890'
  89. for _ in key:
  90. seed = float(int(211 * seed + 30031) % 65536)
  91. r = int(seed / 65536 * len(key))
  92. cgstr += key[r]
  93. key = key.replace(key[r], '')
  94. parts = file_id.split('*')
  95. filename = ''.join(cgstr[int(part)] for part in parts if part.isdecimal())
  96. if not filename.startswith('/'):
  97. filename = '/' + filename
  98. return filename
  99. @staticmethod
  100. def _decrypt_url_params(encrypted_params):
  101. params = VideaIE.rc4(
  102. base64.b64decode(encrypted_params), 'xkt3a41psizxrh9l').split('-')
  103. # sign, token, timestamp
  104. return params[1], params[2], params[3]
  105. def _real_extract(self, url):
  106. scheme = 'https' if url.startswith('https') else 'http'
  107. audio_id = self._match_id(url)
  108. audio_info = self._download_json(
  109. f'{scheme}://m.ximalaya.com/tracks/{audio_id}.json', audio_id,
  110. 'Downloading info json', 'Unable to download info file')
  111. formats = []
  112. # NOTE: VIP-restricted audio
  113. if audio_info.get('is_paid'):
  114. ts = int(time.time())
  115. vip_info = self._download_json(
  116. f'{scheme}://mpay.ximalaya.com/mobile/track/pay/{audio_id}/{ts}',
  117. audio_id, 'Downloading VIP info json', 'Unable to download VIP info file',
  118. query={'device': 'pc', 'isBackend': 'true', '_': ts})
  119. filename = self._decrypt_filename(vip_info['fileId'], vip_info['seed'])
  120. sign, token, timestamp = self._decrypt_url_params(vip_info['ep'])
  121. vip_url = update_url_query(
  122. f'{vip_info["domain"]}/download/{vip_info["apiVersion"]}{filename}', {
  123. 'sign': sign,
  124. 'token': token,
  125. 'timestamp': timestamp,
  126. 'buy_key': vip_info['buyKey'],
  127. 'duration': vip_info['duration'],
  128. })
  129. fmt = {
  130. 'format_id': 'vip',
  131. 'url': vip_url,
  132. 'vcodec': 'none',
  133. }
  134. if '_preview_' in vip_url:
  135. self.report_warning(
  136. f'This tracks requires a VIP account. Using a sample instead. {self._login_hint()}')
  137. fmt.update({
  138. 'format_note': 'Sample',
  139. 'preference': -10,
  140. **traverse_obj(vip_info, {
  141. 'filesize': ('sampleLength', {int_or_none}),
  142. 'duration': ('sampleDuration', {int_or_none}),
  143. }),
  144. })
  145. else:
  146. fmt.update(traverse_obj(vip_info, {
  147. 'filesize': ('totalLength', {int_or_none}),
  148. 'duration': ('duration', {int_or_none}),
  149. }))
  150. fmt['abr'] = try_call(lambda: fmt['filesize'] * 8 / fmt['duration'] / 1024)
  151. formats.append(fmt)
  152. formats.extend([{
  153. 'format_id': f'{bps}k',
  154. 'url': audio_info[k],
  155. 'abr': bps,
  156. 'vcodec': 'none',
  157. } for bps, k in ((24, 'play_path_32'), (64, 'play_path_64')) if audio_info.get(k)])
  158. thumbnails = []
  159. for k in audio_info:
  160. # cover pics kyes like: cover_url', 'cover_url_142'
  161. if k.startswith('cover_url'):
  162. thumbnail = {'name': k, 'url': audio_info[k]}
  163. if k == 'cover_url_142':
  164. thumbnail['width'] = 180
  165. thumbnail['height'] = 180
  166. thumbnails.append(thumbnail)
  167. audio_uploader_id = audio_info.get('uid')
  168. audio_description = try_call(
  169. lambda: audio_info['intro'].replace('\r\n\r\n\r\n ', '\n').replace('\r\n', '\n'))
  170. return {
  171. 'id': audio_id,
  172. 'uploader': audio_info.get('nickname'),
  173. 'uploader_id': str_or_none(audio_uploader_id),
  174. 'uploader_url': f'{scheme}://www.ximalaya.com/zhubo/{audio_uploader_id}/' if audio_uploader_id else None,
  175. 'title': audio_info['title'],
  176. 'thumbnails': thumbnails,
  177. 'description': audio_description,
  178. 'categories': list(filter(None, [audio_info.get('category_name')])),
  179. 'duration': audio_info.get('duration'),
  180. 'view_count': audio_info.get('play_count'),
  181. 'like_count': audio_info.get('favorites_count'),
  182. 'formats': formats,
  183. }
  184. class XimalayaAlbumIE(XimalayaBaseIE):
  185. IE_NAME = 'ximalaya:album'
  186. IE_DESC = '喜马拉雅FM 专辑'
  187. _VALID_URL = r'https?://(?:www\.|m\.)?ximalaya\.com/(?:\d+/)?album/(?P<id>[0-9]+)'
  188. _TESTS = [{
  189. 'url': 'http://www.ximalaya.com/61425525/album/5534601/',
  190. 'info_dict': {
  191. 'title': '唐诗三百首(含赏析)',
  192. 'id': '5534601',
  193. },
  194. 'playlist_mincount': 323,
  195. }, {
  196. 'url': 'https://www.ximalaya.com/album/6912905',
  197. 'info_dict': {
  198. 'title': '埃克哈特《修炼当下的力量》',
  199. 'id': '6912905',
  200. },
  201. 'playlist_mincount': 41,
  202. }]
  203. def _real_extract(self, url):
  204. playlist_id = self._match_id(url)
  205. first_page = self._fetch_page(playlist_id, 1)
  206. page_count = math.ceil(first_page['trackTotalCount'] / first_page['pageSize'])
  207. entries = InAdvancePagedList(
  208. lambda idx: self._get_entries(self._fetch_page(playlist_id, idx + 1) if idx else first_page),
  209. page_count, first_page['pageSize'])
  210. title = traverse_obj(first_page, ('tracks', 0, 'albumTitle'), expected_type=str)
  211. return self.playlist_result(entries, playlist_id, title)
  212. def _fetch_page(self, playlist_id, page_idx):
  213. return self._download_json(
  214. 'https://www.ximalaya.com/revision/album/v1/getTracksList',
  215. playlist_id, note=f'Downloading tracks list page {page_idx}',
  216. query={'albumId': playlist_id, 'pageNum': page_idx})['data']
  217. def _get_entries(self, page_data):
  218. for e in page_data['tracks']:
  219. yield self.url_result(
  220. self._proto_relative_url(f'//www.ximalaya.com{e["url"]}'),
  221. XimalayaIE, e.get('trackId'), e.get('title'))