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.

269 lines
10 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import hashlib
  5. from .common import InfoExtractor
  6. from ..compat import compat_str
  7. from ..utils import (
  8. ExtractorError,
  9. int_or_none,
  10. float_or_none,
  11. )
  12. class YandexMusicBaseIE(InfoExtractor):
  13. @staticmethod
  14. def _handle_error(response):
  15. if isinstance(response, dict):
  16. error = response.get('error')
  17. if error:
  18. raise ExtractorError(error, expected=True)
  19. if response.get('type') == 'captcha' or 'captcha' in response:
  20. YandexMusicBaseIE._raise_captcha()
  21. @staticmethod
  22. def _raise_captcha():
  23. raise ExtractorError(
  24. 'YandexMusic has considered youtube-dl requests automated and '
  25. 'asks you to solve a CAPTCHA. You can either wait for some '
  26. 'time until unblocked and optionally use --sleep-interval '
  27. 'in future or alternatively you can go to https://music.yandex.ru/ '
  28. 'solve CAPTCHA, then export cookies and pass cookie file to '
  29. 'youtube-dl with --cookies',
  30. expected=True)
  31. def _download_webpage(self, *args, **kwargs):
  32. webpage = super(YandexMusicBaseIE, self)._download_webpage(*args, **kwargs)
  33. if 'Нам очень жаль, но запросы, поступившие с вашего IP-адреса, похожи на автоматические.' in webpage:
  34. self._raise_captcha()
  35. return webpage
  36. def _download_json(self, *args, **kwargs):
  37. response = super(YandexMusicBaseIE, self)._download_json(*args, **kwargs)
  38. self._handle_error(response)
  39. return response
  40. class YandexMusicTrackIE(YandexMusicBaseIE):
  41. IE_NAME = 'yandexmusic:track'
  42. IE_DESC = 'Яндекс.Музыка - Трек'
  43. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<album_id>\d+)/track/(?P<id>\d+)'
  44. _TEST = {
  45. 'url': 'http://music.yandex.ru/album/540508/track/4878838',
  46. 'md5': 'f496818aa2f60b6c0062980d2e00dc20',
  47. 'info_dict': {
  48. 'id': '4878838',
  49. 'ext': 'mp3',
  50. 'title': 'Carlo Ambrosio & Fabio Di Bari, Carlo Ambrosio - Gypsy Eyes 1',
  51. 'filesize': 4628061,
  52. 'duration': 193.04,
  53. 'track': 'Gypsy Eyes 1',
  54. 'album': 'Gypsy Soul',
  55. 'album_artist': 'Carlo Ambrosio',
  56. 'artist': 'Carlo Ambrosio & Fabio Di Bari, Carlo Ambrosio',
  57. 'release_year': '2009',
  58. },
  59. 'skip': 'Travis CI servers blocked by YandexMusic',
  60. }
  61. def _get_track_url(self, storage_dir, track_id):
  62. data = self._download_json(
  63. 'http://music.yandex.ru/api/v1.5/handlers/api-jsonp.jsx?action=getTrackSrc&p=download-info/%s'
  64. % storage_dir,
  65. track_id, 'Downloading track location JSON')
  66. # Each string is now wrapped in a list, this is probably only temporarily thus
  67. # supporting both scenarios (see https://github.com/rg3/youtube-dl/issues/10193)
  68. for k, v in data.items():
  69. if v and isinstance(v, list):
  70. data[k] = v[0]
  71. key = hashlib.md5(('XGRlBW9FXlekgbPrRHuSiA' + data['path'][1:] + data['s']).encode('utf-8')).hexdigest()
  72. storage = storage_dir.split('.')
  73. return ('http://%s/get-mp3/%s/%s?track-id=%s&from=service-10-track&similarities-experiment=default'
  74. % (data['host'], key, data['ts'] + data['path'], storage[1]))
  75. def _get_track_info(self, track):
  76. thumbnail = None
  77. cover_uri = track.get('albums', [{}])[0].get('coverUri')
  78. if cover_uri:
  79. thumbnail = cover_uri.replace('%%', 'orig')
  80. if not thumbnail.startswith('http'):
  81. thumbnail = 'http://' + thumbnail
  82. track_title = track['title']
  83. track_info = {
  84. 'id': track['id'],
  85. 'ext': 'mp3',
  86. 'url': self._get_track_url(track['storageDir'], track['id']),
  87. 'filesize': int_or_none(track.get('fileSize')),
  88. 'duration': float_or_none(track.get('durationMs'), 1000),
  89. 'thumbnail': thumbnail,
  90. 'track': track_title,
  91. }
  92. def extract_artist(artist_list):
  93. if artist_list and isinstance(artist_list, list):
  94. artists_names = [a['name'] for a in artist_list if a.get('name')]
  95. if artists_names:
  96. return ', '.join(artists_names)
  97. albums = track.get('albums')
  98. if albums and isinstance(albums, list):
  99. album = albums[0]
  100. if isinstance(album, dict):
  101. year = album.get('year')
  102. track_info.update({
  103. 'album': album.get('title'),
  104. 'album_artist': extract_artist(album.get('artists')),
  105. 'release_year': compat_str(year) if year else None,
  106. })
  107. track_artist = extract_artist(track.get('artists'))
  108. if track_artist:
  109. track_info.update({
  110. 'artist': track_artist,
  111. 'title': '%s - %s' % (track_artist, track_title),
  112. })
  113. else:
  114. track_info['title'] = track_title
  115. return track_info
  116. def _real_extract(self, url):
  117. mobj = re.match(self._VALID_URL, url)
  118. album_id, track_id = mobj.group('album_id'), mobj.group('id')
  119. track = self._download_json(
  120. 'http://music.yandex.ru/handlers/track.jsx?track=%s:%s' % (track_id, album_id),
  121. track_id, 'Downloading track JSON')['track']
  122. return self._get_track_info(track)
  123. class YandexMusicPlaylistBaseIE(YandexMusicBaseIE):
  124. def _build_playlist(self, tracks):
  125. return [
  126. self.url_result(
  127. 'http://music.yandex.ru/album/%s/track/%s' % (track['albums'][0]['id'], track['id']))
  128. for track in tracks if track.get('albums') and isinstance(track.get('albums'), list)]
  129. class YandexMusicAlbumIE(YandexMusicPlaylistBaseIE):
  130. IE_NAME = 'yandexmusic:album'
  131. IE_DESC = 'Яндекс.Музыка - Альбом'
  132. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<id>\d+)/?(\?|$)'
  133. _TEST = {
  134. 'url': 'http://music.yandex.ru/album/540508',
  135. 'info_dict': {
  136. 'id': '540508',
  137. 'title': 'Carlo Ambrosio - Gypsy Soul (2009)',
  138. },
  139. 'playlist_count': 50,
  140. 'skip': 'Travis CI servers blocked by YandexMusic',
  141. }
  142. def _real_extract(self, url):
  143. album_id = self._match_id(url)
  144. album = self._download_json(
  145. 'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id,
  146. album_id, 'Downloading album JSON')
  147. entries = self._build_playlist(album['volumes'][0])
  148. title = '%s - %s' % (album['artists'][0]['name'], album['title'])
  149. year = album.get('year')
  150. if year:
  151. title += ' (%s)' % year
  152. return self.playlist_result(entries, compat_str(album['id']), title)
  153. class YandexMusicPlaylistIE(YandexMusicPlaylistBaseIE):
  154. IE_NAME = 'yandexmusic:playlist'
  155. IE_DESC = 'Яндекс.Музыка - Плейлист'
  156. _VALID_URL = r'https?://music\.yandex\.(?P<tld>ru|kz|ua|by)/users/(?P<user>[^/]+)/playlists/(?P<id>\d+)'
  157. _TESTS = [{
  158. 'url': 'http://music.yandex.ru/users/music.partners/playlists/1245',
  159. 'info_dict': {
  160. 'id': '1245',
  161. 'title': 'Что слушают Enter Shikari',
  162. 'description': 'md5:3b9f27b0efbe53f2ee1e844d07155cc9',
  163. },
  164. 'playlist_count': 6,
  165. 'skip': 'Travis CI servers blocked by YandexMusic',
  166. }, {
  167. # playlist exceeding the limit of 150 tracks shipped with webpage (see
  168. # https://github.com/rg3/youtube-dl/issues/6666)
  169. 'url': 'https://music.yandex.ru/users/ya.playlist/playlists/1036',
  170. 'info_dict': {
  171. 'id': '1036',
  172. 'title': 'Музыка 90-х',
  173. },
  174. 'playlist_mincount': 300,
  175. 'skip': 'Travis CI servers blocked by YandexMusic',
  176. }]
  177. def _real_extract(self, url):
  178. mobj = re.match(self._VALID_URL, url)
  179. tld = mobj.group('tld')
  180. user = mobj.group('user')
  181. playlist_id = mobj.group('id')
  182. playlist = self._download_json(
  183. 'https://music.yandex.%s/handlers/playlist.jsx' % tld,
  184. playlist_id, 'Downloading missing tracks JSON',
  185. fatal=False,
  186. headers={
  187. 'Referer': url,
  188. 'X-Requested-With': 'XMLHttpRequest',
  189. 'X-Retpath-Y': url,
  190. },
  191. query={
  192. 'owner': user,
  193. 'kinds': playlist_id,
  194. 'light': 'true',
  195. 'lang': tld,
  196. 'external-domain': 'music.yandex.%s' % tld,
  197. 'overembed': 'false',
  198. })['playlist']
  199. tracks, track_ids = playlist['tracks'], map(compat_str, playlist['trackIds'])
  200. # tracks dictionary shipped with playlist.jsx API is limited to 150 tracks,
  201. # missing tracks should be retrieved manually.
  202. if len(tracks) < len(track_ids):
  203. present_track_ids = set([
  204. compat_str(track['id'])
  205. for track in tracks if track.get('id')])
  206. missing_track_ids = [
  207. track_id for track_id in track_ids
  208. if track_id not in present_track_ids]
  209. missing_tracks = self._download_json(
  210. 'https://music.yandex.%s/handlers/track-entries.jsx' % tld,
  211. playlist_id, 'Downloading missing tracks JSON',
  212. fatal=False,
  213. headers={
  214. 'Referer': url,
  215. 'X-Requested-With': 'XMLHttpRequest',
  216. },
  217. query={
  218. 'entries': ','.join(missing_track_ids),
  219. 'lang': tld,
  220. 'external-domain': 'music.yandex.%s' % tld,
  221. 'overembed': 'false',
  222. 'strict': 'true',
  223. })
  224. if missing_tracks:
  225. tracks.extend(missing_tracks)
  226. return self.playlist_result(
  227. self._build_playlist(tracks),
  228. compat_str(playlist_id),
  229. playlist.get('title'), playlist.get('description'))