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.

313 lines
12 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. try_get,
  12. )
  13. class YandexMusicBaseIE(InfoExtractor):
  14. @staticmethod
  15. def _handle_error(response):
  16. if isinstance(response, dict):
  17. error = response.get('error')
  18. if error:
  19. raise ExtractorError(error, expected=True)
  20. if response.get('type') == 'captcha' or 'captcha' in response:
  21. YandexMusicBaseIE._raise_captcha()
  22. @staticmethod
  23. def _raise_captcha():
  24. raise ExtractorError(
  25. 'YandexMusic has considered youtube-dl requests automated and '
  26. 'asks you to solve a CAPTCHA. You can either wait for some '
  27. 'time until unblocked and optionally use --sleep-interval '
  28. 'in future or alternatively you can go to https://music.yandex.ru/ '
  29. 'solve CAPTCHA, then export cookies and pass cookie file to '
  30. 'youtube-dl with --cookies',
  31. expected=True)
  32. def _download_webpage_handle(self, *args, **kwargs):
  33. webpage = super(YandexMusicBaseIE, self)._download_webpage_handle(*args, **kwargs)
  34. if 'Нам очень жаль, но запросы, поступившие с вашего IP-адреса, похожи на автоматические.' in webpage:
  35. self._raise_captcha()
  36. return webpage
  37. def _download_json(self, *args, **kwargs):
  38. response = super(YandexMusicBaseIE, self)._download_json(*args, **kwargs)
  39. self._handle_error(response)
  40. return response
  41. class YandexMusicTrackIE(YandexMusicBaseIE):
  42. IE_NAME = 'yandexmusic:track'
  43. IE_DESC = 'Яндекс.Музыка - Трек'
  44. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<album_id>\d+)/track/(?P<id>\d+)'
  45. _TESTS = [{
  46. 'url': 'http://music.yandex.ru/album/540508/track/4878838',
  47. 'md5': 'f496818aa2f60b6c0062980d2e00dc20',
  48. 'info_dict': {
  49. 'id': '4878838',
  50. 'ext': 'mp3',
  51. 'title': 'Carlo Ambrosio & Fabio Di Bari - Gypsy Eyes 1',
  52. 'filesize': 4628061,
  53. 'duration': 193.04,
  54. 'track': 'Gypsy Eyes 1',
  55. 'album': 'Gypsy Soul',
  56. 'album_artist': 'Carlo Ambrosio',
  57. 'artist': 'Carlo Ambrosio & Fabio Di Bari',
  58. 'release_year': 2009,
  59. },
  60. 'skip': 'Travis CI servers blocked by YandexMusic',
  61. }, {
  62. # multiple disks
  63. 'url': 'http://music.yandex.ru/album/3840501/track/705105',
  64. 'md5': 'ebe7b4e2ac7ac03fe11c19727ca6153e',
  65. 'info_dict': {
  66. 'id': '705105',
  67. 'ext': 'mp3',
  68. 'title': 'Hooverphonic - Sometimes',
  69. 'filesize': 5743386,
  70. 'duration': 239.27,
  71. 'track': 'Sometimes',
  72. 'album': 'The Best of Hooverphonic',
  73. 'album_artist': 'Hooverphonic',
  74. 'artist': 'Hooverphonic',
  75. 'release_year': 2016,
  76. 'genre': 'pop',
  77. 'disc_number': 2,
  78. 'track_number': 9,
  79. },
  80. 'skip': 'Travis CI servers blocked by YandexMusic',
  81. }]
  82. def _real_extract(self, url):
  83. mobj = re.match(self._VALID_URL, url)
  84. album_id, track_id = mobj.group('album_id'), mobj.group('id')
  85. track = self._download_json(
  86. 'http://music.yandex.ru/handlers/track.jsx?track=%s:%s' % (track_id, album_id),
  87. track_id, 'Downloading track JSON')['track']
  88. track_title = track['title']
  89. download_data = self._download_json(
  90. 'https://music.yandex.ru/api/v2.1/handlers/track/%s:%s/web-album_track-track-track-main/download/m' % (track_id, album_id),
  91. track_id, 'Downloading track location url JSON',
  92. headers={'X-Retpath-Y': url})
  93. fd_data = self._download_json(
  94. download_data['src'], track_id,
  95. 'Downloading track location JSON',
  96. query={'format': 'json'})
  97. key = hashlib.md5(('XGRlBW9FXlekgbPrRHuSiA' + fd_data['path'][1:] + fd_data['s']).encode('utf-8')).hexdigest()
  98. storage = track['storageDir'].split('.')
  99. f_url = 'http://%s/get-mp3/%s/%s?track-id=%s ' % (fd_data['host'], key, fd_data['ts'] + fd_data['path'], storage[1])
  100. thumbnail = None
  101. cover_uri = track.get('albums', [{}])[0].get('coverUri')
  102. if cover_uri:
  103. thumbnail = cover_uri.replace('%%', 'orig')
  104. if not thumbnail.startswith('http'):
  105. thumbnail = 'http://' + thumbnail
  106. track_info = {
  107. 'id': track_id,
  108. 'ext': 'mp3',
  109. 'url': f_url,
  110. 'filesize': int_or_none(track.get('fileSize')),
  111. 'duration': float_or_none(track.get('durationMs'), 1000),
  112. 'thumbnail': thumbnail,
  113. 'track': track_title,
  114. 'acodec': download_data.get('codec'),
  115. 'abr': int_or_none(download_data.get('bitrate')),
  116. }
  117. def extract_artist_name(artist):
  118. decomposed = artist.get('decomposed')
  119. if not isinstance(decomposed, list):
  120. return artist['name']
  121. parts = [artist['name']]
  122. for element in decomposed:
  123. if isinstance(element, dict) and element.get('name'):
  124. parts.append(element['name'])
  125. elif isinstance(element, compat_str):
  126. parts.append(element)
  127. return ''.join(parts)
  128. def extract_artist(artist_list):
  129. if artist_list and isinstance(artist_list, list):
  130. artists_names = [extract_artist_name(a) for a in artist_list if a.get('name')]
  131. if artists_names:
  132. return ', '.join(artists_names)
  133. albums = track.get('albums')
  134. if albums and isinstance(albums, list):
  135. album = albums[0]
  136. if isinstance(album, dict):
  137. year = album.get('year')
  138. disc_number = int_or_none(try_get(
  139. album, lambda x: x['trackPosition']['volume']))
  140. track_number = int_or_none(try_get(
  141. album, lambda x: x['trackPosition']['index']))
  142. track_info.update({
  143. 'album': album.get('title'),
  144. 'album_artist': extract_artist(album.get('artists')),
  145. 'release_year': int_or_none(year),
  146. 'genre': album.get('genre'),
  147. 'disc_number': disc_number,
  148. 'track_number': track_number,
  149. })
  150. track_artist = extract_artist(track.get('artists'))
  151. if track_artist:
  152. track_info.update({
  153. 'artist': track_artist,
  154. 'title': '%s - %s' % (track_artist, track_title),
  155. })
  156. else:
  157. track_info['title'] = track_title
  158. return track_info
  159. class YandexMusicPlaylistBaseIE(YandexMusicBaseIE):
  160. def _build_playlist(self, tracks):
  161. return [
  162. self.url_result(
  163. 'http://music.yandex.ru/album/%s/track/%s' % (track['albums'][0]['id'], track['id']))
  164. for track in tracks if track.get('albums') and isinstance(track.get('albums'), list)]
  165. class YandexMusicAlbumIE(YandexMusicPlaylistBaseIE):
  166. IE_NAME = 'yandexmusic:album'
  167. IE_DESC = 'Яндекс.Музыка - Альбом'
  168. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<id>\d+)/?(\?|$)'
  169. _TESTS = [{
  170. 'url': 'http://music.yandex.ru/album/540508',
  171. 'info_dict': {
  172. 'id': '540508',
  173. 'title': 'Carlo Ambrosio - Gypsy Soul (2009)',
  174. },
  175. 'playlist_count': 50,
  176. 'skip': 'Travis CI servers blocked by YandexMusic',
  177. }, {
  178. 'url': 'https://music.yandex.ru/album/3840501',
  179. 'info_dict': {
  180. 'id': '3840501',
  181. 'title': 'Hooverphonic - The Best of Hooverphonic (2016)',
  182. },
  183. 'playlist_count': 33,
  184. 'skip': 'Travis CI servers blocked by YandexMusic',
  185. }]
  186. def _real_extract(self, url):
  187. album_id = self._match_id(url)
  188. album = self._download_json(
  189. 'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id,
  190. album_id, 'Downloading album JSON')
  191. entries = self._build_playlist([track for volume in album['volumes'] for track in volume])
  192. title = '%s - %s' % (album['artists'][0]['name'], album['title'])
  193. year = album.get('year')
  194. if year:
  195. title += ' (%s)' % year
  196. return self.playlist_result(entries, compat_str(album['id']), title)
  197. class YandexMusicPlaylistIE(YandexMusicPlaylistBaseIE):
  198. IE_NAME = 'yandexmusic:playlist'
  199. IE_DESC = 'Яндекс.Музыка - Плейлист'
  200. _VALID_URL = r'https?://music\.yandex\.(?P<tld>ru|kz|ua|by)/users/(?P<user>[^/]+)/playlists/(?P<id>\d+)'
  201. _TESTS = [{
  202. 'url': 'http://music.yandex.ru/users/music.partners/playlists/1245',
  203. 'info_dict': {
  204. 'id': '1245',
  205. 'title': 'Что слушают Enter Shikari',
  206. 'description': 'md5:3b9f27b0efbe53f2ee1e844d07155cc9',
  207. },
  208. 'playlist_count': 6,
  209. 'skip': 'Travis CI servers blocked by YandexMusic',
  210. }, {
  211. # playlist exceeding the limit of 150 tracks shipped with webpage (see
  212. # https://github.com/ytdl-org/youtube-dl/issues/6666)
  213. 'url': 'https://music.yandex.ru/users/ya.playlist/playlists/1036',
  214. 'info_dict': {
  215. 'id': '1036',
  216. 'title': 'Музыка 90-х',
  217. },
  218. 'playlist_mincount': 300,
  219. 'skip': 'Travis CI servers blocked by YandexMusic',
  220. }]
  221. def _real_extract(self, url):
  222. mobj = re.match(self._VALID_URL, url)
  223. tld = mobj.group('tld')
  224. user = mobj.group('user')
  225. playlist_id = mobj.group('id')
  226. playlist = self._download_json(
  227. 'https://music.yandex.%s/handlers/playlist.jsx' % tld,
  228. playlist_id, 'Downloading missing tracks JSON',
  229. fatal=False,
  230. headers={
  231. 'Referer': url,
  232. 'X-Requested-With': 'XMLHttpRequest',
  233. 'X-Retpath-Y': url,
  234. },
  235. query={
  236. 'owner': user,
  237. 'kinds': playlist_id,
  238. 'light': 'true',
  239. 'lang': tld,
  240. 'external-domain': 'music.yandex.%s' % tld,
  241. 'overembed': 'false',
  242. })['playlist']
  243. tracks = playlist['tracks']
  244. track_ids = [compat_str(track_id) for track_id in playlist['trackIds']]
  245. # tracks dictionary shipped with playlist.jsx API is limited to 150 tracks,
  246. # missing tracks should be retrieved manually.
  247. if len(tracks) < len(track_ids):
  248. present_track_ids = set([
  249. compat_str(track['id'])
  250. for track in tracks if track.get('id')])
  251. missing_track_ids = [
  252. track_id for track_id in track_ids
  253. if track_id not in present_track_ids]
  254. missing_tracks = self._download_json(
  255. 'https://music.yandex.%s/handlers/track-entries.jsx' % tld,
  256. playlist_id, 'Downloading missing tracks JSON',
  257. fatal=False,
  258. headers={
  259. 'Referer': url,
  260. 'X-Requested-With': 'XMLHttpRequest',
  261. },
  262. query={
  263. 'entries': ','.join(missing_track_ids),
  264. 'lang': tld,
  265. 'external-domain': 'music.yandex.%s' % tld,
  266. 'overembed': 'false',
  267. 'strict': 'true',
  268. })
  269. if missing_tracks:
  270. tracks.extend(missing_tracks)
  271. return self.playlist_result(
  272. self._build_playlist(tracks),
  273. compat_str(playlist_id),
  274. playlist.get('title'), playlist.get('description'))