~facundo/encuentro/trunk

« back to all changes in this revision

Viewing changes to external/youtube-dl/youtube_dl/extractor/dailymotion.py

  • Committer: Facundo Batista
  • Date: 2015-12-27 11:27:15 UTC
  • mto: This revision was merged to the branch mainline in revision 274.
  • Revision ID: facundo@taniquetil.com.ar-20151227112715-ztuasdhqm26hycug
Able to download TEDx.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# coding: utf-8
 
2
from __future__ import unicode_literals
 
3
 
 
4
import re
 
5
import json
 
6
import itertools
 
7
 
 
8
from .common import InfoExtractor
 
9
 
 
10
from ..utils import (
 
11
    determine_ext,
 
12
    error_to_compat_str,
 
13
    ExtractorError,
 
14
    int_or_none,
 
15
    parse_iso8601,
 
16
    sanitized_Request,
 
17
    str_to_int,
 
18
    unescapeHTML,
 
19
)
 
20
 
 
21
 
 
22
class DailymotionBaseInfoExtractor(InfoExtractor):
 
23
    @staticmethod
 
24
    def _build_request(url):
 
25
        """Build a request with the family filter disabled"""
 
26
        request = sanitized_Request(url)
 
27
        request.add_header('Cookie', 'family_filter=off; ff=off')
 
28
        return request
 
29
 
 
30
    def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
 
31
        request = self._build_request(url)
 
32
        return self._download_webpage_handle(request, *args, **kwargs)
 
33
 
 
34
    def _download_webpage_no_ff(self, url, *args, **kwargs):
 
35
        request = self._build_request(url)
 
36
        return self._download_webpage(request, *args, **kwargs)
 
37
 
 
38
 
 
39
class DailymotionIE(DailymotionBaseInfoExtractor):
 
40
    _VALID_URL = r'(?i)(?:https?://)?(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(embed|#)/)?video/(?P<id>[^/?_]+)'
 
41
    IE_NAME = 'dailymotion'
 
42
 
 
43
    _FORMATS = [
 
44
        ('stream_h264_ld_url', 'ld'),
 
45
        ('stream_h264_url', 'standard'),
 
46
        ('stream_h264_hq_url', 'hq'),
 
47
        ('stream_h264_hd_url', 'hd'),
 
48
        ('stream_h264_hd1080_url', 'hd180'),
 
49
    ]
 
50
 
 
51
    _TESTS = [
 
52
        {
 
53
            'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
 
54
            'md5': '2137c41a8e78554bb09225b8eb322406',
 
55
            'info_dict': {
 
56
                'id': 'x2iuewm',
 
57
                'ext': 'mp4',
 
58
                'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
 
59
                'description': 'Several come bundled with the Steam Controller.',
 
60
                'thumbnail': 're:^https?:.*\.(?:jpg|png)$',
 
61
                'duration': 74,
 
62
                'timestamp': 1425657362,
 
63
                'upload_date': '20150306',
 
64
                'uploader': 'IGN',
 
65
                'uploader_id': 'xijv66',
 
66
                'age_limit': 0,
 
67
                'view_count': int,
 
68
                'comment_count': int,
 
69
            }
 
70
        },
 
71
        # Vevo video
 
72
        {
 
73
            'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
 
74
            'info_dict': {
 
75
                'title': 'Roar (Official)',
 
76
                'id': 'USUV71301934',
 
77
                'ext': 'mp4',
 
78
                'uploader': 'Katy Perry',
 
79
                'upload_date': '20130905',
 
80
            },
 
81
            'params': {
 
82
                'skip_download': True,
 
83
            },
 
84
            'skip': 'VEVO is only available in some countries',
 
85
        },
 
86
        # age-restricted video
 
87
        {
 
88
            'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
 
89
            'md5': '0d667a7b9cebecc3c89ee93099c4159d',
 
90
            'info_dict': {
 
91
                'id': 'xyh2zz',
 
92
                'ext': 'mp4',
 
93
                'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
 
94
                'uploader': 'HotWaves1012',
 
95
                'age_limit': 18,
 
96
            }
 
97
        },
 
98
        # geo-restricted, player v5
 
99
        {
 
100
            'url': 'http://www.dailymotion.com/video/xhza0o',
 
101
            'only_matching': True,
 
102
        },
 
103
        # with subtitles
 
104
        {
 
105
            'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
 
106
            'only_matching': True,
 
107
        }
 
108
    ]
 
109
 
 
110
    def _real_extract(self, url):
 
111
        video_id = self._match_id(url)
 
112
 
 
113
        webpage = self._download_webpage_no_ff(
 
114
            'https://www.dailymotion.com/video/%s' % video_id, video_id)
 
115
 
 
116
        age_limit = self._rta_search(webpage)
 
117
 
 
118
        description = self._og_search_description(webpage) or self._html_search_meta(
 
119
            'description', webpage, 'description')
 
120
 
 
121
        view_count = str_to_int(self._search_regex(
 
122
            [r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:(\d+)"',
 
123
             r'video_views_count[^>]+>\s+([\d\.,]+)'],
 
124
            webpage, 'view count', fatal=False))
 
125
        comment_count = int_or_none(self._search_regex(
 
126
            r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
 
127
            webpage, 'comment count', fatal=False))
 
128
 
 
129
        player_v5 = self._search_regex(
 
130
            [r'buildPlayer\(({.+?})\);\n',  # See https://github.com/rg3/youtube-dl/issues/7826
 
131
             r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);',
 
132
             r'buildPlayer\(({.+?})\);'],
 
133
            webpage, 'player v5', default=None)
 
134
        if player_v5:
 
135
            player = self._parse_json(player_v5, video_id)
 
136
            metadata = player['metadata']
 
137
 
 
138
            self._check_error(metadata)
 
139
 
 
140
            formats = []
 
141
            for quality, media_list in metadata['qualities'].items():
 
142
                for media in media_list:
 
143
                    media_url = media.get('url')
 
144
                    if not media_url:
 
145
                        continue
 
146
                    type_ = media.get('type')
 
147
                    if type_ == 'application/vnd.lumberjack.manifest':
 
148
                        continue
 
149
                    ext = determine_ext(media_url)
 
150
                    if type_ == 'application/x-mpegURL' or ext == 'm3u8':
 
151
                        m3u8_formats = self._extract_m3u8_formats(
 
152
                            media_url, video_id, 'mp4', m3u8_id='hls', fatal=False)
 
153
                        if m3u8_formats:
 
154
                            formats.extend(m3u8_formats)
 
155
                    elif type_ == 'application/f4m' or ext == 'f4m':
 
156
                        f4m_formats = self._extract_f4m_formats(
 
157
                            media_url, video_id, preference=-1, f4m_id='hds', fatal=False)
 
158
                        if f4m_formats:
 
159
                            formats.extend(f4m_formats)
 
160
                    else:
 
161
                        f = {
 
162
                            'url': media_url,
 
163
                            'format_id': quality,
 
164
                        }
 
165
                        m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
 
166
                        if m:
 
167
                            f.update({
 
168
                                'width': int(m.group('width')),
 
169
                                'height': int(m.group('height')),
 
170
                            })
 
171
                        formats.append(f)
 
172
            self._sort_formats(formats)
 
173
 
 
174
            title = metadata['title']
 
175
            duration = int_or_none(metadata.get('duration'))
 
176
            timestamp = int_or_none(metadata.get('created_time'))
 
177
            thumbnail = metadata.get('poster_url')
 
178
            uploader = metadata.get('owner', {}).get('screenname')
 
179
            uploader_id = metadata.get('owner', {}).get('id')
 
180
 
 
181
            subtitles = {}
 
182
            subtitles_data = metadata.get('subtitles', {}).get('data', {})
 
183
            if subtitles_data and isinstance(subtitles_data, dict):
 
184
                for subtitle_lang, subtitle in subtitles_data.items():
 
185
                    subtitles[subtitle_lang] = [{
 
186
                        'ext': determine_ext(subtitle_url),
 
187
                        'url': subtitle_url,
 
188
                    } for subtitle_url in subtitle.get('urls', [])]
 
189
 
 
190
            return {
 
191
                'id': video_id,
 
192
                'title': title,
 
193
                'description': description,
 
194
                'thumbnail': thumbnail,
 
195
                'duration': duration,
 
196
                'timestamp': timestamp,
 
197
                'uploader': uploader,
 
198
                'uploader_id': uploader_id,
 
199
                'age_limit': age_limit,
 
200
                'view_count': view_count,
 
201
                'comment_count': comment_count,
 
202
                'formats': formats,
 
203
                'subtitles': subtitles,
 
204
            }
 
205
 
 
206
        # vevo embed
 
207
        vevo_id = self._search_regex(
 
208
            r'<link rel="video_src" href="[^"]*?vevo.com[^"]*?video=(?P<id>[\w]*)',
 
209
            webpage, 'vevo embed', default=None)
 
210
        if vevo_id:
 
211
            return self.url_result('vevo:%s' % vevo_id, 'Vevo')
 
212
 
 
213
        # fallback old player
 
214
        embed_page = self._download_webpage_no_ff(
 
215
            'https://www.dailymotion.com/embed/video/%s' % video_id,
 
216
            video_id, 'Downloading embed page')
 
217
 
 
218
        timestamp = parse_iso8601(self._html_search_meta(
 
219
            'video:release_date', webpage, 'upload date'))
 
220
 
 
221
        info = self._parse_json(
 
222
            self._search_regex(
 
223
                r'var info = ({.*?}),$', embed_page,
 
224
                'video info', flags=re.MULTILINE),
 
225
            video_id)
 
226
 
 
227
        self._check_error(info)
 
228
 
 
229
        formats = []
 
230
        for (key, format_id) in self._FORMATS:
 
231
            video_url = info.get(key)
 
232
            if video_url is not None:
 
233
                m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
 
234
                if m_size is not None:
 
235
                    width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
 
236
                else:
 
237
                    width, height = None, None
 
238
                formats.append({
 
239
                    'url': video_url,
 
240
                    'ext': 'mp4',
 
241
                    'format_id': format_id,
 
242
                    'width': width,
 
243
                    'height': height,
 
244
                })
 
245
        self._sort_formats(formats)
 
246
 
 
247
        # subtitles
 
248
        video_subtitles = self.extract_subtitles(video_id, webpage)
 
249
 
 
250
        title = self._og_search_title(webpage, default=None)
 
251
        if title is None:
 
252
            title = self._html_search_regex(
 
253
                r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
 
254
                'title')
 
255
 
 
256
        return {
 
257
            'id': video_id,
 
258
            'formats': formats,
 
259
            'uploader': info['owner.screenname'],
 
260
            'timestamp': timestamp,
 
261
            'title': title,
 
262
            'description': description,
 
263
            'subtitles': video_subtitles,
 
264
            'thumbnail': info['thumbnail_url'],
 
265
            'age_limit': age_limit,
 
266
            'view_count': view_count,
 
267
            'duration': info['duration']
 
268
        }
 
269
 
 
270
    def _check_error(self, info):
 
271
        if info.get('error') is not None:
 
272
            raise ExtractorError(
 
273
                '%s said: %s' % (self.IE_NAME, info['error']['title']), expected=True)
 
274
 
 
275
    def _get_subtitles(self, video_id, webpage):
 
276
        try:
 
277
            sub_list = self._download_webpage(
 
278
                'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
 
279
                video_id, note=False)
 
280
        except ExtractorError as err:
 
281
            self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
 
282
            return {}
 
283
        info = json.loads(sub_list)
 
284
        if (info['total'] > 0):
 
285
            sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
 
286
            return sub_lang_list
 
287
        self._downloader.report_warning('video doesn\'t have subtitles')
 
288
        return {}
 
289
 
 
290
 
 
291
class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
 
292
    IE_NAME = 'dailymotion:playlist'
 
293
    _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
 
294
    _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
 
295
    _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
 
296
    _TESTS = [{
 
297
        'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
 
298
        'info_dict': {
 
299
            'title': 'SPORT',
 
300
            'id': 'xv4bw_nqtv_sport',
 
301
        },
 
302
        'playlist_mincount': 20,
 
303
    }]
 
304
 
 
305
    def _extract_entries(self, id):
 
306
        video_ids = set()
 
307
        processed_urls = set()
 
308
        for pagenum in itertools.count(1):
 
309
            page_url = self._PAGE_TEMPLATE % (id, pagenum)
 
310
            webpage, urlh = self._download_webpage_handle_no_ff(
 
311
                page_url, id, 'Downloading page %s' % pagenum)
 
312
            if urlh.geturl() in processed_urls:
 
313
                self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
 
314
                    page_url, urlh.geturl()), id)
 
315
                break
 
316
 
 
317
            processed_urls.add(urlh.geturl())
 
318
 
 
319
            for video_id in re.findall(r'data-xid="(.+?)"', webpage):
 
320
                if video_id not in video_ids:
 
321
                    yield self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
 
322
                    video_ids.add(video_id)
 
323
 
 
324
            if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
 
325
                break
 
326
 
 
327
    def _real_extract(self, url):
 
328
        mobj = re.match(self._VALID_URL, url)
 
329
        playlist_id = mobj.group('id')
 
330
        webpage = self._download_webpage(url, playlist_id)
 
331
 
 
332
        return {
 
333
            '_type': 'playlist',
 
334
            'id': playlist_id,
 
335
            'title': self._og_search_title(webpage),
 
336
            'entries': self._extract_entries(playlist_id),
 
337
        }
 
338
 
 
339
 
 
340
class DailymotionUserIE(DailymotionPlaylistIE):
 
341
    IE_NAME = 'dailymotion:user'
 
342
    _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
 
343
    _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
 
344
    _TESTS = [{
 
345
        'url': 'https://www.dailymotion.com/user/nqtv',
 
346
        'info_dict': {
 
347
            'id': 'nqtv',
 
348
            'title': 'Rémi Gaillard',
 
349
        },
 
350
        'playlist_mincount': 100,
 
351
    }, {
 
352
        'url': 'http://www.dailymotion.com/user/UnderProject',
 
353
        'info_dict': {
 
354
            'id': 'UnderProject',
 
355
            'title': 'UnderProject',
 
356
        },
 
357
        'playlist_mincount': 1800,
 
358
        'expected_warnings': [
 
359
            'Stopped at duplicated page',
 
360
        ],
 
361
        'skip': 'Takes too long time',
 
362
    }]
 
363
 
 
364
    def _real_extract(self, url):
 
365
        mobj = re.match(self._VALID_URL, url)
 
366
        user = mobj.group('user')
 
367
        webpage = self._download_webpage(
 
368
            'https://www.dailymotion.com/user/%s' % user, user)
 
369
        full_user = unescapeHTML(self._html_search_regex(
 
370
            r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
 
371
            webpage, 'user'))
 
372
 
 
373
        return {
 
374
            '_type': 'playlist',
 
375
            'id': user,
 
376
            'title': full_user,
 
377
            'entries': self._extract_entries(user),
 
378
        }
 
379
 
 
380
 
 
381
class DailymotionCloudIE(DailymotionBaseInfoExtractor):
 
382
    _VALID_URL_PREFIX = r'http://api\.dmcloud\.net/(?:player/)?embed/'
 
383
    _VALID_URL = r'%s[^/]+/(?P<id>[^/?]+)' % _VALID_URL_PREFIX
 
384
    _VALID_EMBED_URL = r'%s[^/]+/[^\'"]+' % _VALID_URL_PREFIX
 
385
 
 
386
    _TESTS = [{
 
387
        # From http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html
 
388
        # Tested at FranceTvInfo_2
 
389
        'url': 'http://api.dmcloud.net/embed/4e7343f894a6f677b10006b4/556e03339473995ee145930c?auth=1464865870-0-jyhsm84b-ead4c701fb750cf9367bf4447167a3db&autoplay=1',
 
390
        'only_matching': True,
 
391
    }, {
 
392
        # http://www.francetvinfo.fr/societe/larguez-les-amarres-le-cobaturage-se-developpe_980101.html
 
393
        'url': 'http://api.dmcloud.net/player/embed/4e7343f894a6f677b10006b4/559545469473996d31429f06?auth=1467430263-0-90tglw2l-a3a4b64ed41efe48d7fccad85b8b8fda&autoplay=1',
 
394
        'only_matching': True,
 
395
    }]
 
396
 
 
397
    @classmethod
 
398
    def _extract_dmcloud_url(self, webpage):
 
399
        mobj = re.search(r'<iframe[^>]+src=[\'"](%s)[\'"]' % self._VALID_EMBED_URL, webpage)
 
400
        if mobj:
 
401
            return mobj.group(1)
 
402
 
 
403
        mobj = re.search(
 
404
            r'<input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=[\'"](%s)[\'"]' % self._VALID_EMBED_URL,
 
405
            webpage)
 
406
        if mobj:
 
407
            return mobj.group(1)
 
408
 
 
409
    def _real_extract(self, url):
 
410
        video_id = self._match_id(url)
 
411
 
 
412
        webpage = self._download_webpage_no_ff(url, video_id)
 
413
 
 
414
        title = self._html_search_regex(r'<title>([^>]+)</title>', webpage, 'title')
 
415
 
 
416
        video_info = self._parse_json(self._search_regex(
 
417
            r'var\s+info\s*=\s*([^;]+);', webpage, 'video info'), video_id)
 
418
 
 
419
        # TODO: parse ios_url, which is in fact a manifest
 
420
        video_url = video_info['mp4_url']
 
421
 
 
422
        return {
 
423
            'id': video_id,
 
424
            'url': video_url,
 
425
            'title': title,
 
426
            'thumbnail': video_info.get('thumbnail_url'),
 
427
        }