[mixcloud] improved extraction of user description
[youtube-dl] / youtube_dl / extractor / mixcloud.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7     compat_urllib_parse_unquote,
8     compat_urllib_request
9 )
10 from ..utils import (
11     ExtractorError,
12     HEADRequest,
13     NO_DEFAULT,
14     parse_count,
15     str_to_int,
16     clean_html
17 )
18
19
20 class MixcloudIE(InfoExtractor):
21     _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([^/]+)/(?!stream|uploads|favorites|listens|playlists)([^/]+)'
22     IE_NAME = 'mixcloud'
23
24     _TESTS = [{
25         'url': 'http://www.mixcloud.com/dholbach/cryptkeeper/',
26         'info_dict': {
27             'id': 'dholbach-cryptkeeper',
28             'ext': 'm4a',
29             'title': 'Cryptkeeper',
30             'description': 'After quite a long silence from myself, finally another Drum\'n\'Bass mix with my favourite current dance floor bangers.',
31             'uploader': 'Daniel Holbach',
32             'uploader_id': 'dholbach',
33             'thumbnail': 're:https?://.*\.jpg',
34             'view_count': int,
35             'like_count': int,
36         },
37     }, {
38         'url': 'http://www.mixcloud.com/gillespeterson/caribou-7-inch-vinyl-mix-chat/',
39         'info_dict': {
40             'id': 'gillespeterson-caribou-7-inch-vinyl-mix-chat',
41             'ext': 'mp3',
42             'title': 'Caribou 7 inch Vinyl Mix & Chat',
43             'description': 'md5:2b8aec6adce69f9d41724647c65875e8',
44             'uploader': 'Gilles Peterson Worldwide',
45             'uploader_id': 'gillespeterson',
46             'thumbnail': 're:https?://.*/images/',
47             'view_count': int,
48             'like_count': int,
49         },
50     }]
51
52     def _check_url(self, url, track_id, ext):
53         try:
54             # We only want to know if the request succeed
55             # don't download the whole file
56             self._request_webpage(
57                 HEADRequest(url), track_id,
58                 'Trying %s URL' % ext)
59             return True
60         except ExtractorError:
61             return False
62
63     def _real_extract(self, url):
64         mobj = re.match(self._VALID_URL, url)
65         uploader = mobj.group(1)
66         cloudcast_name = mobj.group(2)
67         track_id = compat_urllib_parse_unquote('-'.join((uploader, cloudcast_name)))
68
69         webpage = self._download_webpage(url, track_id)
70
71         message = self._html_search_regex(
72             r'(?s)<div[^>]+class="global-message cloudcast-disabled-notice-light"[^>]*>(.+?)<(?:a|/div)',
73             webpage, 'error message', default=None)
74
75         preview_url = self._search_regex(
76             r'\s(?:data-preview-url|m-preview)="([^"]+)"',
77             webpage, 'preview url', default=None if message else NO_DEFAULT)
78
79         if message:
80             raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
81
82         song_url = re.sub(r'audiocdn(\d+)', r'stream\1', preview_url)
83         song_url = song_url.replace('/previews/', '/c/originals/')
84         if not self._check_url(song_url, track_id, 'mp3'):
85             song_url = song_url.replace('.mp3', '.m4a').replace('originals/', 'm4a/64/')
86             if not self._check_url(song_url, track_id, 'm4a'):
87                 raise ExtractorError('Unable to extract track url')
88
89         PREFIX = (
90             r'm-play-on-spacebar[^>]+'
91             r'(?:\s+[a-zA-Z0-9-]+(?:="[^"]+")?)*?\s+')
92         title = self._html_search_regex(
93             PREFIX + r'm-title="([^"]+)"', webpage, 'title')
94         thumbnail = self._proto_relative_url(self._html_search_regex(
95             PREFIX + r'm-thumbnail-url="([^"]+)"', webpage, 'thumbnail',
96             fatal=False))
97         uploader = self._html_search_regex(
98             PREFIX + r'm-owner-name="([^"]+)"',
99             webpage, 'uploader', fatal=False)
100         uploader_id = self._search_regex(
101             r'\s+"profile": "([^"]+)",', webpage, 'uploader id', fatal=False)
102         description = self._og_search_description(webpage)
103         like_count = parse_count(self._search_regex(
104             r'\bbutton-favorite[^>]+>.*?<span[^>]+class=["\']toggle-number[^>]+>\s*([^<]+)',
105             webpage, 'like count', fatal=False))
106         view_count = str_to_int(self._search_regex(
107             [r'<meta itemprop="interactionCount" content="UserPlays:([0-9]+)"',
108              r'/listeners/?">([0-9,.]+)</a>'],
109             webpage, 'play count', fatal=False))
110
111         return {
112             'id': track_id,
113             'title': title,
114             'url': song_url,
115             'description': description,
116             'thumbnail': thumbnail,
117             'uploader': uploader,
118             'uploader_id': uploader_id,
119             'view_count': view_count,
120             'like_count': like_count,
121         }
122
123
124 class MixcloudUserIE(InfoExtractor):
125     """
126     Information extractor for Mixcloud users.
127     It can retrieve a list of a user's uploads, favorites or listens.
128     """
129
130     _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
131     IE_NAME = 'mixcloud:user'
132
133     _TESTS = [{
134         'url': 'http://www.mixcloud.com/dholbach/',
135         'info_dict': {
136             'id': 'dholbach/uploads',
137             'title': 'Daniel Holbach (uploads)',
138             'description': 'md5:327af72d1efeb404a8216c27240d1370',
139         },
140         'playlist_mincount': 11
141     }, {
142         'url': 'http://www.mixcloud.com/dholbach/uploads/',
143         'info_dict': {
144             'id': 'dholbach/uploads',
145             'title': 'Daniel Holbach (uploads)',
146             'description': 'md5:327af72d1efeb404a8216c27240d1370',
147         },
148         'playlist_mincount': 11
149     }, {
150         'url': 'http://www.mixcloud.com/dholbach/favorites/',
151         'info_dict': {
152             'id': 'dholbach/favorites',
153             'title': 'Daniel Holbach (favorites)',
154             'description': 'md5:327af72d1efeb404a8216c27240d1370',
155         },
156         'playlist_mincount': 244
157     }, {
158         'url': 'http://www.mixcloud.com/dholbach/listens/',
159         'info_dict': {
160             'id': 'dholbach/listens',
161             'title': 'Daniel Holbach (listens)',
162             'description': 'md5:327af72d1efeb404a8216c27240d1370',
163         },
164         'playlist_mincount': 846
165     }]
166
167     def _fetch_tracks(self, base_url, video_id, dl_note=None, dl_errnote=None):
168         # retrieve all fragments of a list of tracks with fake AJAX calls
169         track_urls = []
170         current_page = 1
171         while True:
172             # fake a AJAX request to retrieve a list fragment
173             page_url = base_url + "?page=%d&list=main&_ajax=1" % current_page
174             req = compat_urllib_request.Request(page_url, headers={"X-Requested-With": "XMLHttpRequest"})
175             resp = self._download_webpage(req, video_id, note=dl_note + " (page %d)" % current_page, errnote=dl_errnote)
176
177             # extract all track URLs from fragment
178             urls = re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', resp)
179             # clean up URLs
180             urls = map(clean_html, urls)
181             # create absolute URLs
182             urls = map(lambda u: "https://www.mixcloud.com" + u, urls)
183             track_urls.extend(urls)
184
185             # advance to next fragment, if any
186             if " m-next-page-url=" in resp:
187                 current_page += 1
188             else:
189                 break
190
191         return track_urls
192
193     def _handle_track_urls(self, urls):
194         return map(lambda u: self.url_result(u, "Mixcloud"), urls)
195
196     def _get_user_description(self, page_content):
197         return self._html_search_regex(
198             r'<div class="description-text">.*?<p>(.*?)</p></div></div></div>',
199             page_content,
200             "user description",
201             fatal=False)
202
203     def _get_username(self, page_content):
204         return self._og_search_title(page_content)
205
206     def _real_extract(self, url):
207         mobj = re.match(self._VALID_URL, url)
208         user_id = mobj.group("user")
209         list_type = mobj.group("type")
210
211         # if only a profile URL was supplied, default to download all uploads
212         if list_type is None:
213             list_type = "uploads"
214
215         video_id = "%s/%s" % (user_id, list_type)
216
217         # download the user's profile to retrieve some metadata
218         profile = self._download_webpage("https://www.mixcloud.com/%s/" % user_id,
219                                          video_id,
220                                          note="Downloading user profile",
221                                          errnote="Unable to download user profile")
222
223         username = self._get_username(profile)
224         description = self._get_user_description(profile)
225
226         # retrieve all page fragments of uploads, favorites or listens
227         track_urls = self._fetch_tracks(
228             "https://www.mixcloud.com/%s/%s/" % (user_id, list_type),
229             video_id,
230             dl_note="Downloading list of %s" % list_type,
231             dl_errnote="Unable to download list of %s" % list_type)
232
233         # let MixcloudIE handle each track URL
234         entries = self._handle_track_urls(track_urls)
235
236         return {
237             '_type': 'playlist',
238             'entries': entries,
239             'title': "%s (%s)" % (username, list_type),
240             'id': video_id,
241             "description": description
242         }
243
244
245 class MixcloudPlaylistIE(MixcloudUserIE):
246     """
247     Information extractor for Mixcloud playlists.
248     """
249
250     _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
251     IE_NAME = 'mixcloud:playlist'
252
253     _TESTS = [{
254         'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
255         'info_dict': {
256             'id': 'RedBullThre3style/playlists/tokyo-finalists-2015',
257             'title': 'National Champions 2015',
258             'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
259         },
260         'playlist_mincount': 16
261     }, {
262         'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
263         'info_dict': {
264             'id': 'maxvibes/playlists/jazzcat-on-ness-radio',
265             'title': 'Jazzcat on Ness Radio',
266             'description': 'md5:7bbbf0d6359a0b8cda85224be0f8f263',
267         },
268         'playlist_mincount': 23
269     }]
270
271     def _get_playlist_title(self, page_content):
272         return self._html_search_regex(
273             r'<span class="main-list-title list-playlist-title ">(?P<title>.*?)</span>',
274             page_content,
275             "playlist title",
276             group="title",
277             fatal=True
278         )
279
280     def _real_extract(self, url):
281         mobj = re.match(self._VALID_URL, url)
282         user_id = mobj.group("user")
283         playlist_id = mobj.group("playlist")
284         video_id = "%s/playlists/%s" % (user_id, playlist_id)
285
286         # download the playlist page to retrieve some metadata
287         profile = self._download_webpage(url,
288                                          user_id,
289                                          note="Downloading playlist page",
290                                          errnote="Unable to download playlist page")
291
292         description = self._get_user_description(profile)
293         playlist_title = self._get_playlist_title(profile)
294
295         # retrieve all page fragments of playlist
296         track_urls = self._fetch_tracks(
297             "https://www.mixcloud.com/%s/playlists/%s/" % (user_id, playlist_id),
298             video_id,
299             dl_note="Downloading tracklist of %s" % playlist_title,
300             dl_errnote="Unable to tracklist of %s" % playlist_title)
301
302         # let MixcloudIE handle each track
303         entries = self._handle_track_urls(track_urls)
304
305         return {
306             '_type': 'playlist',
307             'entries': entries,
308             'title': playlist_title,
309             'id': video_id,
310             "description": description
311         }