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.

263 lines
9.8 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. key = hashlib.md5(('XGRlBW9FXlekgbPrRHuSiA' + data['path'][1:] + data['s']).encode('utf-8')).hexdigest()
  67. storage = storage_dir.split('.')
  68. return ('http://%s/get-mp3/%s/%s?track-id=%s&from=service-10-track&similarities-experiment=default'
  69. % (data['host'], key, data['ts'] + data['path'], storage[1]))
  70. def _get_track_info(self, track):
  71. thumbnail = None
  72. cover_uri = track.get('albums', [{}])[0].get('coverUri')
  73. if cover_uri:
  74. thumbnail = cover_uri.replace('%%', 'orig')
  75. if not thumbnail.startswith('http'):
  76. thumbnail = 'http://' + thumbnail
  77. track_title = track['title']
  78. track_info = {
  79. 'id': track['id'],
  80. 'ext': 'mp3',
  81. 'url': self._get_track_url(track['storageDir'], track['id']),
  82. 'filesize': int_or_none(track.get('fileSize')),
  83. 'duration': float_or_none(track.get('durationMs'), 1000),
  84. 'thumbnail': thumbnail,
  85. 'track': track_title,
  86. }
  87. def extract_artist(artist_list):
  88. if artist_list and isinstance(artist_list, list):
  89. artists_names = [a['name'] for a in artist_list if a.get('name')]
  90. if artists_names:
  91. return ', '.join(artists_names)
  92. albums = track.get('albums')
  93. if albums and isinstance(albums, list):
  94. album = albums[0]
  95. if isinstance(album, dict):
  96. year = album.get('year')
  97. track_info.update({
  98. 'album': album.get('title'),
  99. 'album_artist': extract_artist(album.get('artists')),
  100. 'release_year': compat_str(year) if year else None,
  101. })
  102. track_artist = extract_artist(track.get('artists'))
  103. if track_artist:
  104. track_info.update({
  105. 'artist': track_artist,
  106. 'title': '%s - %s' % (track_artist, track_title),
  107. })
  108. else:
  109. track_info['title'] = track_title
  110. return track_info
  111. def _real_extract(self, url):
  112. mobj = re.match(self._VALID_URL, url)
  113. album_id, track_id = mobj.group('album_id'), mobj.group('id')
  114. track = self._download_json(
  115. 'http://music.yandex.ru/handlers/track.jsx?track=%s:%s' % (track_id, album_id),
  116. track_id, 'Downloading track JSON')['track']
  117. return self._get_track_info(track)
  118. class YandexMusicPlaylistBaseIE(YandexMusicBaseIE):
  119. def _build_playlist(self, tracks):
  120. return [
  121. self.url_result(
  122. 'http://music.yandex.ru/album/%s/track/%s' % (track['albums'][0]['id'], track['id']))
  123. for track in tracks if track.get('albums') and isinstance(track.get('albums'), list)]
  124. class YandexMusicAlbumIE(YandexMusicPlaylistBaseIE):
  125. IE_NAME = 'yandexmusic:album'
  126. IE_DESC = 'Яндекс.Музыка - Альбом'
  127. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<id>\d+)/?(\?|$)'
  128. _TEST = {
  129. 'url': 'http://music.yandex.ru/album/540508',
  130. 'info_dict': {
  131. 'id': '540508',
  132. 'title': 'Carlo Ambrosio - Gypsy Soul (2009)',
  133. },
  134. 'playlist_count': 50,
  135. 'skip': 'Travis CI servers blocked by YandexMusic',
  136. }
  137. def _real_extract(self, url):
  138. album_id = self._match_id(url)
  139. album = self._download_json(
  140. 'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id,
  141. album_id, 'Downloading album JSON')
  142. entries = self._build_playlist(album['volumes'][0])
  143. title = '%s - %s' % (album['artists'][0]['name'], album['title'])
  144. year = album.get('year')
  145. if year:
  146. title += ' (%s)' % year
  147. return self.playlist_result(entries, compat_str(album['id']), title)
  148. class YandexMusicPlaylistIE(YandexMusicPlaylistBaseIE):
  149. IE_NAME = 'yandexmusic:playlist'
  150. IE_DESC = 'Яндекс.Музыка - Плейлист'
  151. _VALID_URL = r'https?://music\.yandex\.(?P<tld>ru|kz|ua|by)/users/(?P<user>[^/]+)/playlists/(?P<id>\d+)'
  152. _TESTS = [{
  153. 'url': 'http://music.yandex.ru/users/music.partners/playlists/1245',
  154. 'info_dict': {
  155. 'id': '1245',
  156. 'title': 'Что слушают Enter Shikari',
  157. 'description': 'md5:3b9f27b0efbe53f2ee1e844d07155cc9',
  158. },
  159. 'playlist_count': 6,
  160. 'skip': 'Travis CI servers blocked by YandexMusic',
  161. }, {
  162. # playlist exceeding the limit of 150 tracks shipped with webpage (see
  163. # https://github.com/rg3/youtube-dl/issues/6666)
  164. 'url': 'https://music.yandex.ru/users/ya.playlist/playlists/1036',
  165. 'info_dict': {
  166. 'id': '1036',
  167. 'title': 'Музыка 90-х',
  168. },
  169. 'playlist_mincount': 300,
  170. 'skip': 'Travis CI servers blocked by YandexMusic',
  171. }]
  172. def _real_extract(self, url):
  173. mobj = re.match(self._VALID_URL, url)
  174. tld = mobj.group('tld')
  175. user = mobj.group('user')
  176. playlist_id = mobj.group('id')
  177. playlist = self._download_json(
  178. 'https://music.yandex.%s/handlers/playlist.jsx' % tld,
  179. playlist_id, 'Downloading missing tracks JSON',
  180. fatal=False,
  181. headers={
  182. 'Referer': url,
  183. 'X-Requested-With': 'XMLHttpRequest',
  184. 'X-Retpath-Y': url,
  185. },
  186. query={
  187. 'owner': user,
  188. 'kinds': playlist_id,
  189. 'light': 'true',
  190. 'lang': tld,
  191. 'external-domain': 'music.yandex.%s' % tld,
  192. 'overembed': 'false',
  193. })['playlist']
  194. tracks, track_ids = playlist['tracks'], map(compat_str, playlist['trackIds'])
  195. # tracks dictionary shipped with playlist.jsx API is limited to 150 tracks,
  196. # missing tracks should be retrieved manually.
  197. if len(tracks) < len(track_ids):
  198. present_track_ids = set([
  199. compat_str(track['id'])
  200. for track in tracks if track.get('id')])
  201. missing_track_ids = [
  202. track_id for track_id in track_ids
  203. if track_id not in present_track_ids]
  204. missing_tracks = self._download_json(
  205. 'https://music.yandex.%s/handlers/track-entries.jsx' % tld,
  206. playlist_id, 'Downloading missing tracks JSON',
  207. fatal=False,
  208. headers={
  209. 'Referer': url,
  210. 'X-Requested-With': 'XMLHttpRequest',
  211. },
  212. query={
  213. 'entries': ','.join(missing_track_ids),
  214. 'lang': tld,
  215. 'external-domain': 'music.yandex.%s' % tld,
  216. 'overembed': 'false',
  217. 'strict': 'true',
  218. })
  219. if missing_tracks:
  220. tracks.extend(missing_tracks)
  221. return self.playlist_result(
  222. self._build_playlist(tracks),
  223. compat_str(playlist_id),
  224. playlist.get('title'), playlist.get('description'))