]> asedeno.scripts.mit.edu Git - youtube-dl.git/blob - youtube_dl/extractor/bbc.py
37d427a66c8c39f72b157c1c01eb6a9db0a8f1c3
[youtube-dl.git] / youtube_dl / extractor / bbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import functools
5 import itertools
6 import json
7 import re
8
9 from .common import InfoExtractor
10 from ..compat import (
11     compat_etree_Element,
12     compat_HTTPError,
13     compat_parse_qs,
14     compat_str,
15     compat_urllib_parse_urlparse,
16     compat_urlparse,
17 )
18 from ..utils import (
19     ExtractorError,
20     OnDemandPagedList,
21     clean_html,
22     dict_get,
23     float_or_none,
24     get_element_by_class,
25     int_or_none,
26     js_to_json,
27     parse_duration,
28     parse_iso8601,
29     strip_or_none,
30     try_get,
31     unescapeHTML,
32     unified_timestamp,
33     url_or_none,
34     urlencode_postdata,
35     urljoin,
36 )
37
38
39 class BBCCoUkIE(InfoExtractor):
40     IE_NAME = 'bbc.co.uk'
41     IE_DESC = 'BBC iPlayer'
42     _ID_REGEX = r'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})'
43     _VALID_URL = r'''(?x)
44                     https?://
45                         (?:www\.)?bbc\.co\.uk/
46                         (?:
47                             programmes/(?!articles/)|
48                             iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
49                             music/(?:clips|audiovideo/popular)[/#]|
50                             radio/player/|
51                             sounds/play/|
52                             events/[^/]+/play/[^/]+/
53                         )
54                         (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
55                     ''' % _ID_REGEX
56
57     _LOGIN_URL = 'https://account.bbc.com/signin'
58     _NETRC_MACHINE = 'bbc'
59
60     _MEDIA_SELECTOR_URL_TEMPL = 'https://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/%s/vpid/%s'
61     _MEDIA_SETS = [
62         # Provides HQ HLS streams with even better quality that pc mediaset but fails
63         # with geolocation in some cases when it's even not geo restricted at all (e.g.
64         # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
65         'iptv-all',
66         'pc',
67     ]
68
69     _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
70
71     _TESTS = [
72         {
73             'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
74             'info_dict': {
75                 'id': 'b039d07m',
76                 'ext': 'flv',
77                 'title': 'Kaleidoscope, Leonard Cohen',
78                 'description': 'The Canadian poet and songwriter reflects on his musical career.',
79             },
80             'params': {
81                 # rtmp download
82                 'skip_download': True,
83             }
84         },
85         {
86             'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
87             'info_dict': {
88                 'id': 'b00yng1d',
89                 'ext': 'flv',
90                 'title': 'The Man in Black: Series 3: The Printed Name',
91                 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
92                 'duration': 1800,
93             },
94             'params': {
95                 # rtmp download
96                 'skip_download': True,
97             },
98             'skip': 'Episode is no longer available on BBC iPlayer Radio',
99         },
100         {
101             'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
102             'info_dict': {
103                 'id': 'b00yng1d',
104                 'ext': 'flv',
105                 'title': 'The Voice UK: Series 3: Blind Auditions 5',
106                 'description': 'Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.',
107                 'duration': 5100,
108             },
109             'params': {
110                 # rtmp download
111                 'skip_download': True,
112             },
113             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
114         },
115         {
116             'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
117             'info_dict': {
118                 'id': 'b03k3pb7',
119                 'ext': 'flv',
120                 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
121                 'description': '2. Invasion',
122                 'duration': 3600,
123             },
124             'params': {
125                 # rtmp download
126                 'skip_download': True,
127             },
128             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
129         }, {
130             'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
131             'info_dict': {
132                 'id': 'b04v209v',
133                 'ext': 'flv',
134                 'title': 'Pete Tong, The Essential New Tune Special',
135                 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
136                 'duration': 10800,
137             },
138             'params': {
139                 # rtmp download
140                 'skip_download': True,
141             },
142             'skip': 'Episode is no longer available on BBC iPlayer Radio',
143         }, {
144             'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
145             'note': 'Audio',
146             'info_dict': {
147                 'id': 'p022h44j',
148                 'ext': 'flv',
149                 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
150                 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
151                 'duration': 227,
152             },
153             'params': {
154                 # rtmp download
155                 'skip_download': True,
156             }
157         }, {
158             'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
159             'note': 'Video',
160             'info_dict': {
161                 'id': 'p025c103',
162                 'ext': 'flv',
163                 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
164                 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
165                 'duration': 226,
166             },
167             'params': {
168                 # rtmp download
169                 'skip_download': True,
170             }
171         }, {
172             'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
173             'info_dict': {
174                 'id': 'p02n76xf',
175                 'ext': 'flv',
176                 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
177                 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
178                 'duration': 3540,
179             },
180             'params': {
181                 # rtmp download
182                 'skip_download': True,
183             },
184             'skip': 'geolocation',
185         }, {
186             'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
187             'info_dict': {
188                 'id': 'b05zmgw1',
189                 'ext': 'flv',
190                 'description': 'Kirsty Wark and Morgan Quaintance visit the Royal Academy as it prepares for its annual artistic extravaganza, meeting people who have come together to make the show unique.',
191                 'title': 'Royal Academy Summer Exhibition',
192                 'duration': 3540,
193             },
194             'params': {
195                 # rtmp download
196                 'skip_download': True,
197             },
198             'skip': 'geolocation',
199         }, {
200             # iptv-all mediaset fails with geolocation however there is no geo restriction
201             # for this programme at all
202             'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
203             'info_dict': {
204                 'id': 'b06rkms3',
205                 'ext': 'flv',
206                 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
207                 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
208             },
209             'params': {
210                 # rtmp download
211                 'skip_download': True,
212             },
213             'skip': 'Now it\'s really geo-restricted',
214         }, {
215             # compact player (https://github.com/ytdl-org/youtube-dl/issues/8147)
216             'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
217             'info_dict': {
218                 'id': 'p028bfkj',
219                 'ext': 'flv',
220                 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
221                 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
222             },
223             'params': {
224                 # rtmp download
225                 'skip_download': True,
226             },
227         }, {
228             'url': 'https://www.bbc.co.uk/sounds/play/m0007jzb',
229             'note': 'Audio',
230             'info_dict': {
231                 'id': 'm0007jz9',
232                 'ext': 'mp4',
233                 'title': 'BBC Proms, 2019, Prom 34: West–Eastern Divan Orchestra',
234                 'description': "Live BBC Proms. West–Eastern Divan Orchestra with Daniel Barenboim and Martha Argerich.",
235                 'duration': 9840,
236             },
237             'params': {
238                 # rtmp download
239                 'skip_download': True,
240             }
241         }, {
242             'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
243             'only_matching': True,
244         }, {
245             'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
246             'only_matching': True,
247         }, {
248             'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
249             'only_matching': True,
250         }, {
251             'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
252             'only_matching': True,
253         }, {
254             'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
255             'only_matching': True,
256         }, {
257             'url': 'http://www.bbc.co.uk/programmes/w3csv1y9',
258             'only_matching': True,
259         }, {
260             'url': 'https://www.bbc.co.uk/programmes/m00005xn',
261             'only_matching': True,
262         }, {
263             'url': 'https://www.bbc.co.uk/programmes/w172w4dww1jqt5s',
264             'only_matching': True,
265         }]
266
267     def _login(self):
268         username, password = self._get_login_info()
269         if username is None:
270             return
271
272         login_page = self._download_webpage(
273             self._LOGIN_URL, None, 'Downloading signin page')
274
275         login_form = self._hidden_inputs(login_page)
276
277         login_form.update({
278             'username': username,
279             'password': password,
280         })
281
282         post_url = urljoin(self._LOGIN_URL, self._search_regex(
283             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
284             'post url', default=self._LOGIN_URL, group='url'))
285
286         response, urlh = self._download_webpage_handle(
287             post_url, None, 'Logging in', data=urlencode_postdata(login_form),
288             headers={'Referer': self._LOGIN_URL})
289
290         if self._LOGIN_URL in urlh.geturl():
291             error = clean_html(get_element_by_class('form-message', response))
292             if error:
293                 raise ExtractorError(
294                     'Unable to login: %s' % error, expected=True)
295             raise ExtractorError('Unable to log in')
296
297     def _real_initialize(self):
298         self._login()
299
300     class MediaSelectionError(Exception):
301         def __init__(self, id):
302             self.id = id
303
304     def _extract_asx_playlist(self, connection, programme_id):
305         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
306         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
307
308     def _extract_items(self, playlist):
309         return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
310
311     def _extract_medias(self, media_selection):
312         error = media_selection.get('result')
313         if error:
314             raise BBCCoUkIE.MediaSelectionError(error)
315         return media_selection.get('media') or []
316
317     def _extract_connections(self, media):
318         return media.get('connection') or []
319
320     def _get_subtitles(self, media, programme_id):
321         subtitles = {}
322         for connection in self._extract_connections(media):
323             cc_url = url_or_none(connection.get('href'))
324             if not cc_url:
325                 continue
326             captions = self._download_xml(
327                 cc_url, programme_id, 'Downloading captions', fatal=False)
328             if not isinstance(captions, compat_etree_Element):
329                 continue
330             subtitles['en'] = [
331                 {
332                     'url': connection.get('href'),
333                     'ext': 'ttml',
334                 },
335             ]
336             break
337         return subtitles
338
339     def _raise_extractor_error(self, media_selection_error):
340         raise ExtractorError(
341             '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
342             expected=True)
343
344     def _download_media_selector(self, programme_id):
345         last_exception = None
346         for media_set in self._MEDIA_SETS:
347             try:
348                 return self._download_media_selector_url(
349                     self._MEDIA_SELECTOR_URL_TEMPL % (media_set, programme_id), programme_id)
350             except BBCCoUkIE.MediaSelectionError as e:
351                 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
352                     last_exception = e
353                     continue
354                 self._raise_extractor_error(e)
355         self._raise_extractor_error(last_exception)
356
357     def _download_media_selector_url(self, url, programme_id=None):
358         media_selection = self._download_json(
359             url, programme_id, 'Downloading media selection JSON',
360             expected_status=(403, 404))
361         return self._process_media_selector(media_selection, programme_id)
362
363     def _process_media_selector(self, media_selection, programme_id):
364         formats = []
365         subtitles = None
366         urls = []
367
368         for media in self._extract_medias(media_selection):
369             kind = media.get('kind')
370             if kind in ('video', 'audio'):
371                 bitrate = int_or_none(media.get('bitrate'))
372                 encoding = media.get('encoding')
373                 width = int_or_none(media.get('width'))
374                 height = int_or_none(media.get('height'))
375                 file_size = int_or_none(media.get('media_file_size'))
376                 for connection in self._extract_connections(media):
377                     href = connection.get('href')
378                     if href in urls:
379                         continue
380                     if href:
381                         urls.append(href)
382                     conn_kind = connection.get('kind')
383                     protocol = connection.get('protocol')
384                     supplier = connection.get('supplier')
385                     transfer_format = connection.get('transferFormat')
386                     format_id = supplier or conn_kind or protocol
387                     # ASX playlist
388                     if supplier == 'asx':
389                         for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
390                             formats.append({
391                                 'url': ref,
392                                 'format_id': 'ref%s_%s' % (i, format_id),
393                             })
394                     elif transfer_format == 'dash':
395                         formats.extend(self._extract_mpd_formats(
396                             href, programme_id, mpd_id=format_id, fatal=False))
397                     elif transfer_format == 'hls':
398                         formats.extend(self._extract_m3u8_formats(
399                             href, programme_id, ext='mp4', entry_protocol='m3u8_native',
400                             m3u8_id=format_id, fatal=False))
401                     elif transfer_format == 'hds':
402                         formats.extend(self._extract_f4m_formats(
403                             href, programme_id, f4m_id=format_id, fatal=False))
404                     else:
405                         if not supplier and bitrate:
406                             format_id += '-%d' % bitrate
407                         fmt = {
408                             'format_id': format_id,
409                             'filesize': file_size,
410                         }
411                         if kind == 'video':
412                             fmt.update({
413                                 'width': width,
414                                 'height': height,
415                                 'tbr': bitrate,
416                                 'vcodec': encoding,
417                             })
418                         else:
419                             fmt.update({
420                                 'abr': bitrate,
421                                 'acodec': encoding,
422                                 'vcodec': 'none',
423                             })
424                         if protocol in ('http', 'https'):
425                             # Direct link
426                             fmt.update({
427                                 'url': href,
428                             })
429                         elif protocol == 'rtmp':
430                             application = connection.get('application', 'ondemand')
431                             auth_string = connection.get('authString')
432                             identifier = connection.get('identifier')
433                             server = connection.get('server')
434                             fmt.update({
435                                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
436                                 'play_path': identifier,
437                                 'app': '%s?%s' % (application, auth_string),
438                                 'page_url': 'http://www.bbc.co.uk',
439                                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
440                                 'rtmp_live': False,
441                                 'ext': 'flv',
442                             })
443                         else:
444                             continue
445                         formats.append(fmt)
446             elif kind == 'captions':
447                 subtitles = self.extract_subtitles(media, programme_id)
448         return formats, subtitles
449
450     def _download_playlist(self, playlist_id):
451         try:
452             playlist = self._download_json(
453                 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
454                 playlist_id, 'Downloading playlist JSON')
455
456             version = playlist.get('defaultAvailableVersion')
457             if version:
458                 smp_config = version['smpConfig']
459                 title = smp_config['title']
460                 description = smp_config['summary']
461                 for item in smp_config['items']:
462                     kind = item['kind']
463                     if kind not in ('programme', 'radioProgramme'):
464                         continue
465                     programme_id = item.get('vpid')
466                     duration = int_or_none(item.get('duration'))
467                     formats, subtitles = self._download_media_selector(programme_id)
468                 return programme_id, title, description, duration, formats, subtitles
469         except ExtractorError as ee:
470             if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
471                 raise
472
473         # fallback to legacy playlist
474         return self._process_legacy_playlist(playlist_id)
475
476     def _process_legacy_playlist_url(self, url, display_id):
477         playlist = self._download_legacy_playlist_url(url, display_id)
478         return self._extract_from_legacy_playlist(playlist, display_id)
479
480     def _process_legacy_playlist(self, playlist_id):
481         return self._process_legacy_playlist_url(
482             'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
483
484     def _download_legacy_playlist_url(self, url, playlist_id=None):
485         return self._download_xml(
486             url, playlist_id, 'Downloading legacy playlist XML')
487
488     def _extract_from_legacy_playlist(self, playlist, playlist_id):
489         no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
490         if no_items is not None:
491             reason = no_items.get('reason')
492             if reason == 'preAvailability':
493                 msg = 'Episode %s is not yet available' % playlist_id
494             elif reason == 'postAvailability':
495                 msg = 'Episode %s is no longer available' % playlist_id
496             elif reason == 'noMedia':
497                 msg = 'Episode %s is not currently available' % playlist_id
498             else:
499                 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
500             raise ExtractorError(msg, expected=True)
501
502         for item in self._extract_items(playlist):
503             kind = item.get('kind')
504             if kind not in ('programme', 'radioProgramme'):
505                 continue
506             title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
507             description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
508             description = description_el.text if description_el is not None else None
509
510             def get_programme_id(item):
511                 def get_from_attributes(item):
512                     for p in ('identifier', 'group'):
513                         value = item.get(p)
514                         if value and re.match(r'^[pb][\da-z]{7}$', value):
515                             return value
516                 get_from_attributes(item)
517                 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
518                 if mediator is not None:
519                     return get_from_attributes(mediator)
520
521             programme_id = get_programme_id(item)
522             duration = int_or_none(item.get('duration'))
523
524             if programme_id:
525                 formats, subtitles = self._download_media_selector(programme_id)
526             else:
527                 formats, subtitles = self._process_media_selector(item, playlist_id)
528                 programme_id = playlist_id
529
530         return programme_id, title, description, duration, formats, subtitles
531
532     def _real_extract(self, url):
533         group_id = self._match_id(url)
534
535         webpage = self._download_webpage(url, group_id, 'Downloading video page')
536
537         error = self._search_regex(
538             r'<div\b[^>]+\bclass=["\'](?:smp|playout)__message delta["\'][^>]*>\s*([^<]+?)\s*<',
539             webpage, 'error', default=None)
540         if error:
541             raise ExtractorError(error, expected=True)
542
543         programme_id = None
544         duration = None
545
546         tviplayer = self._search_regex(
547             r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
548             webpage, 'player', default=None)
549
550         if tviplayer:
551             player = self._parse_json(tviplayer, group_id).get('player', {})
552             duration = int_or_none(player.get('duration'))
553             programme_id = player.get('vpid')
554
555         if not programme_id:
556             programme_id = self._search_regex(
557                 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
558
559         if programme_id:
560             formats, subtitles = self._download_media_selector(programme_id)
561             title = self._og_search_title(webpage, default=None) or self._html_search_regex(
562                 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
563                  r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
564             description = self._search_regex(
565                 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
566                  r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
567                 webpage, 'description', default=None)
568             if not description:
569                 description = self._html_search_meta('description', webpage)
570         else:
571             programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
572
573         self._sort_formats(formats)
574
575         return {
576             'id': programme_id,
577             'title': title,
578             'description': description,
579             'thumbnail': self._og_search_thumbnail(webpage, default=None),
580             'duration': duration,
581             'formats': formats,
582             'subtitles': subtitles,
583         }
584
585
586 class BBCIE(BBCCoUkIE):
587     IE_NAME = 'bbc'
588     IE_DESC = 'BBC'
589     _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
590
591     _MEDIA_SETS = [
592         'mobile-tablet-main',
593         'pc',
594     ]
595
596     _TESTS = [{
597         # article with multiple videos embedded with data-playable containing vpids
598         'url': 'http://www.bbc.com/news/world-europe-32668511',
599         'info_dict': {
600             'id': 'world-europe-32668511',
601             'title': 'Russia stages massive WW2 parade',
602             'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
603         },
604         'playlist_count': 2,
605     }, {
606         # article with multiple videos embedded with data-playable (more videos)
607         'url': 'http://www.bbc.com/news/business-28299555',
608         'info_dict': {
609             'id': 'business-28299555',
610             'title': 'Farnborough Airshow: Video highlights',
611             'description': 'BBC reports and video highlights at the Farnborough Airshow.',
612         },
613         'playlist_count': 9,
614         'skip': 'Save time',
615     }, {
616         # article with multiple videos embedded with `new SMP()`
617         # broken
618         'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
619         'info_dict': {
620             'id': '3662a707-0af9-3149-963f-47bea720b460',
621             'title': 'BUGGER',
622         },
623         'playlist_count': 18,
624     }, {
625         # single video embedded with data-playable containing vpid
626         'url': 'http://www.bbc.com/news/world-europe-32041533',
627         'info_dict': {
628             'id': 'p02mprgb',
629             'ext': 'mp4',
630             'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
631             'description': 'md5:2868290467291b37feda7863f7a83f54',
632             'duration': 47,
633             'timestamp': 1427219242,
634             'upload_date': '20150324',
635         },
636         'params': {
637             # rtmp download
638             'skip_download': True,
639         }
640     }, {
641         # article with single video embedded with data-playable containing XML playlist
642         # with direct video links as progressiveDownloadUrl (for now these are extracted)
643         # and playlist with f4m and m3u8 as streamingUrl
644         'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
645         'info_dict': {
646             'id': '150615_telabyad_kentin_cogu',
647             'ext': 'mp4',
648             'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
649             'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
650             'timestamp': 1434397334,
651             'upload_date': '20150615',
652         },
653         'params': {
654             'skip_download': True,
655         }
656     }, {
657         # single video embedded with data-playable containing XML playlists (regional section)
658         'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
659         'info_dict': {
660             'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
661             'ext': 'mp4',
662             'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
663             'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
664             'timestamp': 1434713142,
665             'upload_date': '20150619',
666         },
667         'params': {
668             'skip_download': True,
669         }
670     }, {
671         # single video from video playlist embedded with vxp-playlist-data JSON
672         'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
673         'info_dict': {
674             'id': 'p02w6qjc',
675             'ext': 'mp4',
676             'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
677             'duration': 56,
678             'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
679         },
680         'params': {
681             'skip_download': True,
682         }
683     }, {
684         # single video story with digitalData
685         'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
686         'info_dict': {
687             'id': 'p02q6gc4',
688             'ext': 'flv',
689             'title': 'Sri Lanka’s spicy secret',
690             'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
691             'timestamp': 1437674293,
692             'upload_date': '20150723',
693         },
694         'params': {
695             # rtmp download
696             'skip_download': True,
697         }
698     }, {
699         # single video story without digitalData
700         'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
701         'info_dict': {
702             'id': 'p018zqqg',
703             'ext': 'mp4',
704             'title': 'Hyundai Santa Fe Sport: Rock star',
705             'description': 'md5:b042a26142c4154a6e472933cf20793d',
706             'timestamp': 1415867444,
707             'upload_date': '20141113',
708         },
709         'params': {
710             # rtmp download
711             'skip_download': True,
712         }
713     }, {
714         # single video embedded with Morph
715         'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
716         'info_dict': {
717             'id': 'p041vhd0',
718             'ext': 'mp4',
719             'title': "Nigeria v Japan - Men's First Round",
720             'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
721             'duration': 7980,
722             'uploader': 'BBC Sport',
723             'uploader_id': 'bbc_sport',
724         },
725         'params': {
726             # m3u8 download
727             'skip_download': True,
728         },
729         'skip': 'Georestricted to UK',
730     }, {
731         # single video with playlist.sxml URL in playlist param
732         'url': 'http://www.bbc.com/sport/0/football/33653409',
733         'info_dict': {
734             'id': 'p02xycnp',
735             'ext': 'mp4',
736             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
737             'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
738             'duration': 140,
739         },
740         'params': {
741             # rtmp download
742             'skip_download': True,
743         }
744     }, {
745         # article with multiple videos embedded with playlist.sxml in playlist param
746         'url': 'http://www.bbc.com/sport/0/football/34475836',
747         'info_dict': {
748             'id': '34475836',
749             'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
750             'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
751         },
752         'playlist_count': 3,
753     }, {
754         # school report article with single video
755         'url': 'http://www.bbc.co.uk/schoolreport/35744779',
756         'info_dict': {
757             'id': '35744779',
758             'title': 'School which breaks down barriers in Jerusalem',
759         },
760         'playlist_count': 1,
761     }, {
762         # single video with playlist URL from weather section
763         'url': 'http://www.bbc.com/weather/features/33601775',
764         'only_matching': True,
765     }, {
766         # custom redirection to www.bbc.com
767         # also, video with window.__INITIAL_DATA__
768         'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
769         'info_dict': {
770             'id': 'p02xzws1',
771             'ext': 'mp4',
772             'title': "Pluto may have 'nitrogen glaciers'",
773             'description': 'md5:6a95b593f528d7a5f2605221bc56912f',
774             'thumbnail': r're:https?://.+/.+\.jpg',
775             'timestamp': 1437785037,
776             'upload_date': '20150725',
777         },
778     }, {
779         # single video article embedded with data-media-vpid
780         'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
781         'only_matching': True,
782     }, {
783         'url': 'https://www.bbc.co.uk/bbcthree/clip/73d0bbd0-abc3-4cea-b3c0-cdae21905eb1',
784         'info_dict': {
785             'id': 'p06556y7',
786             'ext': 'mp4',
787             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
788             'description': 'md5:4b7dfd063d5a789a1512e99662be3ddd',
789         },
790         'params': {
791             'skip_download': True,
792         }
793     }, {
794         # window.__PRELOADED_STATE__
795         'url': 'https://www.bbc.co.uk/radio/play/b0b9z4yl',
796         'info_dict': {
797             'id': 'b0b9z4vz',
798             'ext': 'mp4',
799             'title': 'Prom 6: An American in Paris and Turangalila',
800             'description': 'md5:51cf7d6f5c8553f197e58203bc78dff8',
801             'uploader': 'Radio 3',
802             'uploader_id': 'bbc_radio_three',
803         },
804     }, {
805         'url': 'http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227',
806         'info_dict': {
807             'id': 'p06w9tws',
808             'ext': 'mp4',
809             'title': 'md5:2fabf12a726603193a2879a055f72514',
810             'description': 'Learn English words and phrases from this story',
811         },
812         'add_ie': [BBCCoUkIE.ie_key()],
813     }, {
814         # BBC Reel
815         'url': 'https://www.bbc.com/reel/video/p07c6sb6/how-positive-thinking-is-harming-your-happiness',
816         'info_dict': {
817             'id': 'p07c6sb9',
818             'ext': 'mp4',
819             'title': 'How positive thinking is harming your happiness',
820             'alt_title': 'The downsides of positive thinking',
821             'description': 'md5:fad74b31da60d83b8265954ee42d85b4',
822             'duration': 235,
823             'thumbnail': r're:https?://.+/p07c9dsr.jpg',
824             'upload_date': '20190604',
825             'categories': ['Psychology'],
826         },
827     }]
828
829     @classmethod
830     def suitable(cls, url):
831         EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerEpisodesIE, BBCCoUkIPlayerGroupIE, BBCCoUkPlaylistIE)
832         return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
833                 else super(BBCIE, cls).suitable(url))
834
835     def _extract_from_media_meta(self, media_meta, video_id):
836         # Direct links to media in media metadata (e.g.
837         # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
838         # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
839         source_files = media_meta.get('sourceFiles')
840         if source_files:
841             return [{
842                 'url': f['url'],
843                 'format_id': format_id,
844                 'ext': f.get('encoding'),
845                 'tbr': float_or_none(f.get('bitrate'), 1000),
846                 'filesize': int_or_none(f.get('filesize')),
847             } for format_id, f in source_files.items() if f.get('url')], []
848
849         programme_id = media_meta.get('externalId')
850         if programme_id:
851             return self._download_media_selector(programme_id)
852
853         # Process playlist.sxml as legacy playlist
854         href = media_meta.get('href')
855         if href:
856             playlist = self._download_legacy_playlist_url(href)
857             _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
858             return formats, subtitles
859
860         return [], []
861
862     def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
863         programme_id, title, description, duration, formats, subtitles = \
864             self._process_legacy_playlist_url(url, playlist_id)
865         self._sort_formats(formats)
866         return {
867             'id': programme_id,
868             'title': title,
869             'description': description,
870             'duration': duration,
871             'timestamp': timestamp,
872             'formats': formats,
873             'subtitles': subtitles,
874         }
875
876     def _real_extract(self, url):
877         playlist_id = self._match_id(url)
878
879         webpage = self._download_webpage(url, playlist_id)
880
881         json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
882         timestamp = json_ld_info.get('timestamp')
883
884         playlist_title = json_ld_info.get('title')
885         if not playlist_title:
886             playlist_title = self._og_search_title(
887                 webpage, default=None) or self._html_search_regex(
888                 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
889             if playlist_title:
890                 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
891
892         playlist_description = json_ld_info.get(
893             'description') or self._og_search_description(webpage, default=None)
894
895         if not timestamp:
896             timestamp = parse_iso8601(self._search_regex(
897                 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
898                  r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
899                  r'"datePublished":\s*"([^"]+)'],
900                 webpage, 'date', default=None))
901
902         entries = []
903
904         # article with multiple videos embedded with playlist.sxml (e.g.
905         # http://www.bbc.com/sport/0/football/34475836)
906         playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
907         playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
908         if playlists:
909             entries = [
910                 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
911                 for playlist_url in playlists]
912
913         # news article with multiple videos embedded with data-playable
914         data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
915         if data_playables:
916             for _, data_playable_json in data_playables:
917                 data_playable = self._parse_json(
918                     unescapeHTML(data_playable_json), playlist_id, fatal=False)
919                 if not data_playable:
920                     continue
921                 settings = data_playable.get('settings', {})
922                 if settings:
923                     # data-playable with video vpid in settings.playlistObject.items (e.g.
924                     # http://www.bbc.com/news/world-us-canada-34473351)
925                     playlist_object = settings.get('playlistObject', {})
926                     if playlist_object:
927                         items = playlist_object.get('items')
928                         if items and isinstance(items, list):
929                             title = playlist_object['title']
930                             description = playlist_object.get('summary')
931                             duration = int_or_none(items[0].get('duration'))
932                             programme_id = items[0].get('vpid')
933                             formats, subtitles = self._download_media_selector(programme_id)
934                             self._sort_formats(formats)
935                             entries.append({
936                                 'id': programme_id,
937                                 'title': title,
938                                 'description': description,
939                                 'timestamp': timestamp,
940                                 'duration': duration,
941                                 'formats': formats,
942                                 'subtitles': subtitles,
943                             })
944                     else:
945                         # data-playable without vpid but with a playlist.sxml URLs
946                         # in otherSettings.playlist (e.g.
947                         # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
948                         playlist = data_playable.get('otherSettings', {}).get('playlist', {})
949                         if playlist:
950                             entry = None
951                             for key in ('streaming', 'progressiveDownload'):
952                                 playlist_url = playlist.get('%sUrl' % key)
953                                 if not playlist_url:
954                                     continue
955                                 try:
956                                     info = self._extract_from_playlist_sxml(
957                                         playlist_url, playlist_id, timestamp)
958                                     if not entry:
959                                         entry = info
960                                     else:
961                                         entry['title'] = info['title']
962                                         entry['formats'].extend(info['formats'])
963                                 except ExtractorError as e:
964                                     # Some playlist URL may fail with 500, at the same time
965                                     # the other one may work fine (e.g.
966                                     # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
967                                     if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
968                                         continue
969                                     raise
970                             if entry:
971                                 self._sort_formats(entry['formats'])
972                                 entries.append(entry)
973
974         if entries:
975             return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
976
977         # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
978         group_id = self._search_regex(
979             r'<div[^>]+\bclass=["\']video["\'][^>]+\bdata-pid=["\'](%s)' % self._ID_REGEX,
980             webpage, 'group id', default=None)
981         if group_id:
982             return self.url_result(
983                 'https://www.bbc.co.uk/programmes/%s' % group_id,
984                 ie=BBCCoUkIE.ie_key())
985
986         # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
987         programme_id = self._search_regex(
988             [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
989              r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
990              r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
991             webpage, 'vpid', default=None)
992
993         if programme_id:
994             formats, subtitles = self._download_media_selector(programme_id)
995             self._sort_formats(formats)
996             # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
997             digital_data = self._parse_json(
998                 self._search_regex(
999                     r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
1000                 programme_id, fatal=False)
1001             page_info = digital_data.get('page', {}).get('pageInfo', {})
1002             title = page_info.get('pageName') or self._og_search_title(webpage)
1003             description = page_info.get('description') or self._og_search_description(webpage)
1004             timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
1005             return {
1006                 'id': programme_id,
1007                 'title': title,
1008                 'description': description,
1009                 'timestamp': timestamp,
1010                 'formats': formats,
1011                 'subtitles': subtitles,
1012             }
1013
1014         # bbc reel (e.g. https://www.bbc.com/reel/video/p07c6sb6/how-positive-thinking-is-harming-your-happiness)
1015         initial_data = self._parse_json(self._html_search_regex(
1016             r'<script[^>]+id=(["\'])initial-data\1[^>]+data-json=(["\'])(?P<json>(?:(?!\2).)+)',
1017             webpage, 'initial data', default='{}', group='json'), playlist_id, fatal=False)
1018         if initial_data:
1019             init_data = try_get(
1020                 initial_data, lambda x: x['initData']['items'][0], dict) or {}
1021             smp_data = init_data.get('smpData') or {}
1022             clip_data = try_get(smp_data, lambda x: x['items'][0], dict) or {}
1023             version_id = clip_data.get('versionID')
1024             if version_id:
1025                 title = smp_data['title']
1026                 formats, subtitles = self._download_media_selector(version_id)
1027                 self._sort_formats(formats)
1028                 image_url = smp_data.get('holdingImageURL')
1029                 display_date = init_data.get('displayDate')
1030                 topic_title = init_data.get('topicTitle')
1031
1032                 return {
1033                     'id': version_id,
1034                     'title': title,
1035                     'formats': formats,
1036                     'alt_title': init_data.get('shortTitle'),
1037                     'thumbnail': image_url.replace('$recipe', 'raw') if image_url else None,
1038                     'description': smp_data.get('summary') or init_data.get('shortSummary'),
1039                     'upload_date': display_date.replace('-', '') if display_date else None,
1040                     'subtitles': subtitles,
1041                     'duration': int_or_none(clip_data.get('duration')),
1042                     'categories': [topic_title] if topic_title else None,
1043                 }
1044
1045         # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
1046         # There are several setPayload calls may be present but the video
1047         # seems to be always related to the first one
1048         morph_payload = self._parse_json(
1049             self._search_regex(
1050                 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
1051                 webpage, 'morph payload', default='{}'),
1052             playlist_id, fatal=False)
1053         if morph_payload:
1054             components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
1055             for component in components:
1056                 if not isinstance(component, dict):
1057                     continue
1058                 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
1059                 if not lead_media:
1060                     continue
1061                 identifiers = lead_media.get('identifiers')
1062                 if not identifiers or not isinstance(identifiers, dict):
1063                     continue
1064                 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
1065                 if not programme_id:
1066                     continue
1067                 title = lead_media.get('title') or self._og_search_title(webpage)
1068                 formats, subtitles = self._download_media_selector(programme_id)
1069                 self._sort_formats(formats)
1070                 description = lead_media.get('summary')
1071                 uploader = lead_media.get('masterBrand')
1072                 uploader_id = lead_media.get('mid')
1073                 duration = None
1074                 duration_d = lead_media.get('duration')
1075                 if isinstance(duration_d, dict):
1076                     duration = parse_duration(dict_get(
1077                         duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
1078                 return {
1079                     'id': programme_id,
1080                     'title': title,
1081                     'description': description,
1082                     'duration': duration,
1083                     'uploader': uploader,
1084                     'uploader_id': uploader_id,
1085                     'formats': formats,
1086                     'subtitles': subtitles,
1087                 }
1088
1089         preload_state = self._parse_json(self._search_regex(
1090             r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
1091             'preload state', default='{}'), playlist_id, fatal=False)
1092         if preload_state:
1093             current_programme = preload_state.get('programmes', {}).get('current') or {}
1094             programme_id = current_programme.get('id')
1095             if current_programme and programme_id and current_programme.get('type') == 'playable_item':
1096                 title = current_programme.get('titles', {}).get('tertiary') or playlist_title
1097                 formats, subtitles = self._download_media_selector(programme_id)
1098                 self._sort_formats(formats)
1099                 synopses = current_programme.get('synopses') or {}
1100                 network = current_programme.get('network') or {}
1101                 duration = int_or_none(
1102                     current_programme.get('duration', {}).get('value'))
1103                 thumbnail = None
1104                 image_url = current_programme.get('image_url')
1105                 if image_url:
1106                     thumbnail = image_url.replace('{recipe}', 'raw')
1107                 return {
1108                     'id': programme_id,
1109                     'title': title,
1110                     'description': dict_get(synopses, ('long', 'medium', 'short')),
1111                     'thumbnail': thumbnail,
1112                     'duration': duration,
1113                     'uploader': network.get('short_title'),
1114                     'uploader_id': network.get('id'),
1115                     'formats': formats,
1116                     'subtitles': subtitles,
1117                 }
1118
1119         bbc3_config = self._parse_json(
1120             self._search_regex(
1121                 r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
1122                 'bbcthree config', default='{}'),
1123             playlist_id, transform_source=js_to_json, fatal=False) or {}
1124         payload = bbc3_config.get('payload') or {}
1125         if payload:
1126             clip = payload.get('currentClip') or {}
1127             clip_vpid = clip.get('vpid')
1128             clip_title = clip.get('title')
1129             if clip_vpid and clip_title:
1130                 formats, subtitles = self._download_media_selector(clip_vpid)
1131                 self._sort_formats(formats)
1132                 return {
1133                     'id': clip_vpid,
1134                     'title': clip_title,
1135                     'thumbnail': dict_get(clip, ('poster', 'imageUrl')),
1136                     'description': clip.get('description'),
1137                     'duration': parse_duration(clip.get('duration')),
1138                     'formats': formats,
1139                     'subtitles': subtitles,
1140                 }
1141             bbc3_playlist = try_get(
1142                 payload, lambda x: x['content']['bbcMedia']['playlist'],
1143                 dict)
1144             if bbc3_playlist:
1145                 playlist_title = bbc3_playlist.get('title') or playlist_title
1146                 thumbnail = bbc3_playlist.get('holdingImageURL')
1147                 entries = []
1148                 for bbc3_item in bbc3_playlist['items']:
1149                     programme_id = bbc3_item.get('versionID')
1150                     if not programme_id:
1151                         continue
1152                     formats, subtitles = self._download_media_selector(programme_id)
1153                     self._sort_formats(formats)
1154                     entries.append({
1155                         'id': programme_id,
1156                         'title': playlist_title,
1157                         'thumbnail': thumbnail,
1158                         'timestamp': timestamp,
1159                         'formats': formats,
1160                         'subtitles': subtitles,
1161                     })
1162                 return self.playlist_result(
1163                     entries, playlist_id, playlist_title, playlist_description)
1164
1165         initial_data = self._parse_json(self._search_regex(
1166             r'window\.__INITIAL_DATA__\s*=\s*({.+?});', webpage,
1167             'preload state', default='{}'), playlist_id, fatal=False)
1168         if initial_data:
1169             def parse_media(media):
1170                 if not media:
1171                     return
1172                 for item in (try_get(media, lambda x: x['media']['items'], list) or []):
1173                     item_id = item.get('id')
1174                     item_title = item.get('title')
1175                     if not (item_id and item_title):
1176                         continue
1177                     formats, subtitles = self._download_media_selector(item_id)
1178                     self._sort_formats(formats)
1179                     item_desc = None
1180                     blocks = try_get(media, lambda x: x['summary']['blocks'], list)
1181                     if blocks:
1182                         summary = []
1183                         for block in blocks:
1184                             text = try_get(block, lambda x: x['model']['text'], compat_str)
1185                             if text:
1186                                 summary.append(text)
1187                         if summary:
1188                             item_desc = '\n\n'.join(summary)
1189                     item_time = None
1190                     for meta in try_get(media, lambda x: x['metadata']['items'], list) or []:
1191                         if try_get(meta, lambda x: x['label']) == 'Published':
1192                             item_time = unified_timestamp(meta.get('timestamp'))
1193                             break
1194                     entries.append({
1195                         'id': item_id,
1196                         'title': item_title,
1197                         'thumbnail': item.get('holdingImageUrl'),
1198                         'formats': formats,
1199                         'subtitles': subtitles,
1200                         'timestamp': item_time,
1201                         'description': strip_or_none(item_desc),
1202                     })
1203             for resp in (initial_data.get('data') or {}).values():
1204                 name = resp.get('name')
1205                 if name == 'media-experience':
1206                     parse_media(try_get(resp, lambda x: x['data']['initialItem']['mediaItem'], dict))
1207                 elif name == 'article':
1208                     for block in (try_get(resp,
1209                                           (lambda x: x['data']['blocks'],
1210                                            lambda x: x['data']['content']['model']['blocks'],),
1211                                           list) or []):
1212                         if block.get('type') != 'media':
1213                             continue
1214                         parse_media(block.get('model'))
1215             return self.playlist_result(
1216                 entries, playlist_id, playlist_title, playlist_description)
1217
1218         def extract_all(pattern):
1219             return list(filter(None, map(
1220                 lambda s: self._parse_json(s, playlist_id, fatal=False),
1221                 re.findall(pattern, webpage))))
1222
1223         # Multiple video article (e.g.
1224         # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
1225         EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
1226         entries = []
1227         for match in extract_all(r'new\s+SMP\(({.+?})\)'):
1228             embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
1229             if embed_url and re.match(EMBED_URL, embed_url):
1230                 entries.append(embed_url)
1231         entries.extend(re.findall(
1232             r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
1233         if entries:
1234             return self.playlist_result(
1235                 [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
1236                 playlist_id, playlist_title, playlist_description)
1237
1238         # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
1239         medias = extract_all(r"data-media-meta='({[^']+})'")
1240
1241         if not medias:
1242             # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
1243             media_asset = self._search_regex(
1244                 r'mediaAssetPage\.init\(\s*({.+?}), "/',
1245                 webpage, 'media asset', default=None)
1246             if media_asset:
1247                 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
1248                 medias = []
1249                 for video in media_asset_page.get('videos', {}).values():
1250                     medias.extend(video.values())
1251
1252         if not medias:
1253             # Multiple video playlist with single `now playing` entry (e.g.
1254             # http://www.bbc.com/news/video_and_audio/must_see/33767813)
1255             vxp_playlist = self._parse_json(
1256                 self._search_regex(
1257                     r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
1258                     webpage, 'playlist data'),
1259                 playlist_id)
1260             playlist_medias = []
1261             for item in vxp_playlist:
1262                 media = item.get('media')
1263                 if not media:
1264                     continue
1265                 playlist_medias.append(media)
1266                 # Download single video if found media with asset id matching the video id from URL
1267                 if item.get('advert', {}).get('assetId') == playlist_id:
1268                     medias = [media]
1269                     break
1270             # Fallback to the whole playlist
1271             if not medias:
1272                 medias = playlist_medias
1273
1274         entries = []
1275         for num, media_meta in enumerate(medias, start=1):
1276             formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1277             if not formats:
1278                 continue
1279             self._sort_formats(formats)
1280
1281             video_id = media_meta.get('externalId')
1282             if not video_id:
1283                 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1284
1285             title = media_meta.get('caption')
1286             if not title:
1287                 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1288
1289             duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1290
1291             images = []
1292             for image in media_meta.get('images', {}).values():
1293                 images.extend(image.values())
1294             if 'image' in media_meta:
1295                 images.append(media_meta['image'])
1296
1297             thumbnails = [{
1298                 'url': image.get('href'),
1299                 'width': int_or_none(image.get('width')),
1300                 'height': int_or_none(image.get('height')),
1301             } for image in images]
1302
1303             entries.append({
1304                 'id': video_id,
1305                 'title': title,
1306                 'thumbnails': thumbnails,
1307                 'duration': duration,
1308                 'timestamp': timestamp,
1309                 'formats': formats,
1310                 'subtitles': subtitles,
1311             })
1312
1313         return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1314
1315
1316 class BBCCoUkArticleIE(InfoExtractor):
1317     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1318     IE_NAME = 'bbc.co.uk:article'
1319     IE_DESC = 'BBC articles'
1320
1321     _TEST = {
1322         'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1323         'info_dict': {
1324             'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1325             'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1326             'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1327         },
1328         'playlist_count': 4,
1329         'add_ie': ['BBCCoUk'],
1330     }
1331
1332     def _real_extract(self, url):
1333         playlist_id = self._match_id(url)
1334
1335         webpage = self._download_webpage(url, playlist_id)
1336
1337         title = self._og_search_title(webpage)
1338         description = self._og_search_description(webpage).strip()
1339
1340         entries = [self.url_result(programme_url) for programme_url in re.findall(
1341             r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
1342
1343         return self.playlist_result(entries, playlist_id, title, description)
1344
1345
1346 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1347     def _entries(self, webpage, url, playlist_id):
1348         single_page = 'page' in compat_urlparse.parse_qs(
1349             compat_urlparse.urlparse(url).query)
1350         for page_num in itertools.count(2):
1351             for video_id in re.findall(
1352                     self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1353                 yield self.url_result(
1354                     self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1355             if single_page:
1356                 return
1357             next_page = self._search_regex(
1358                 r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
1359                 webpage, 'next page url', default=None, group='url')
1360             if not next_page:
1361                 break
1362             webpage = self._download_webpage(
1363                 compat_urlparse.urljoin(url, next_page), playlist_id,
1364                 'Downloading page %d' % page_num, page_num)
1365
1366     def _real_extract(self, url):
1367         playlist_id = self._match_id(url)
1368
1369         webpage = self._download_webpage(url, playlist_id)
1370
1371         title, description = self._extract_title_and_description(webpage)
1372
1373         return self.playlist_result(
1374             self._entries(webpage, url, playlist_id),
1375             playlist_id, title, description)
1376
1377
1378 class BBCCoUkIPlayerPlaylistBaseIE(InfoExtractor):
1379     _VALID_URL_TMPL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/%%s/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1380
1381     @staticmethod
1382     def _get_default(episode, key, default_key='default'):
1383         return try_get(episode, lambda x: x[key][default_key])
1384
1385     def _get_description(self, data):
1386         synopsis = data.get(self._DESCRIPTION_KEY) or {}
1387         return dict_get(synopsis, ('large', 'medium', 'small'))
1388
1389     def _fetch_page(self, programme_id, per_page, series_id, page):
1390         elements = self._get_elements(self._call_api(
1391             programme_id, per_page, page + 1, series_id))
1392         for element in elements:
1393             episode = self._get_episode(element)
1394             episode_id = episode.get('id')
1395             if not episode_id:
1396                 continue
1397             thumbnail = None
1398             image = self._get_episode_image(episode)
1399             if image:
1400                 thumbnail = image.replace('{recipe}', 'raw')
1401             category = self._get_default(episode, 'labels', 'category')
1402             yield {
1403                 '_type': 'url',
1404                 'id': episode_id,
1405                 'title': self._get_episode_field(episode, 'subtitle'),
1406                 'url': 'https://www.bbc.co.uk/iplayer/episode/' + episode_id,
1407                 'thumbnail': thumbnail,
1408                 'description': self._get_description(episode),
1409                 'categories': [category] if category else None,
1410                 'series': self._get_episode_field(episode, 'title'),
1411                 'ie_key': BBCCoUkIE.ie_key(),
1412             }
1413
1414     def _real_extract(self, url):
1415         pid = self._match_id(url)
1416         qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
1417         series_id = qs.get('seriesId', [None])[0]
1418         page = qs.get('page', [None])[0]
1419         per_page = 36 if page else self._PAGE_SIZE
1420         fetch_page = functools.partial(self._fetch_page, pid, per_page, series_id)
1421         entries = fetch_page(int(page) - 1) if page else OnDemandPagedList(fetch_page, self._PAGE_SIZE)
1422         playlist_data = self._get_playlist_data(self._call_api(pid, 1))
1423         return self.playlist_result(
1424             entries, pid, self._get_playlist_title(playlist_data),
1425             self._get_description(playlist_data))
1426
1427
1428 class BBCCoUkIPlayerEpisodesIE(BBCCoUkIPlayerPlaylistBaseIE):
1429     IE_NAME = 'bbc.co.uk:iplayer:episodes'
1430     _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'episodes'
1431     _TESTS = [{
1432         'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1433         'info_dict': {
1434             'id': 'b05rcz9v',
1435             'title': 'The Disappearance',
1436             'description': 'md5:58eb101aee3116bad4da05f91179c0cb',
1437         },
1438         'playlist_mincount': 8,
1439     }, {
1440         # all seasons
1441         'url': 'https://www.bbc.co.uk/iplayer/episodes/b094m5t9/doctor-foster',
1442         'info_dict': {
1443             'id': 'b094m5t9',
1444             'title': 'Doctor Foster',
1445             'description': 'md5:5aa9195fad900e8e14b52acd765a9fd6',
1446         },
1447         'playlist_mincount': 10,
1448     }, {
1449         # explicit season
1450         'url': 'https://www.bbc.co.uk/iplayer/episodes/b094m5t9/doctor-foster?seriesId=b094m6nv',
1451         'info_dict': {
1452             'id': 'b094m5t9',
1453             'title': 'Doctor Foster',
1454             'description': 'md5:5aa9195fad900e8e14b52acd765a9fd6',
1455         },
1456         'playlist_mincount': 5,
1457     }, {
1458         # all pages
1459         'url': 'https://www.bbc.co.uk/iplayer/episodes/m0004c4v/beechgrove',
1460         'info_dict': {
1461             'id': 'm0004c4v',
1462             'title': 'Beechgrove',
1463             'description': 'Gardening show that celebrates Scottish horticulture and growing conditions.',
1464         },
1465         'playlist_mincount': 37,
1466     }, {
1467         # explicit page
1468         'url': 'https://www.bbc.co.uk/iplayer/episodes/m0004c4v/beechgrove?page=2',
1469         'info_dict': {
1470             'id': 'm0004c4v',
1471             'title': 'Beechgrove',
1472             'description': 'Gardening show that celebrates Scottish horticulture and growing conditions.',
1473         },
1474         'playlist_mincount': 1,
1475     }]
1476     _PAGE_SIZE = 100
1477     _DESCRIPTION_KEY = 'synopsis'
1478
1479     def _get_episode_image(self, episode):
1480         return self._get_default(episode, 'image')
1481
1482     def _get_episode_field(self, episode, field):
1483         return self._get_default(episode, field)
1484
1485     @staticmethod
1486     def _get_elements(data):
1487         return data['entities']['results']
1488
1489     @staticmethod
1490     def _get_episode(element):
1491         return element.get('episode') or {}
1492
1493     def _call_api(self, pid, per_page, page=1, series_id=None):
1494         variables = {
1495             'id': pid,
1496             'page': page,
1497             'perPage': per_page,
1498         }
1499         if series_id:
1500             variables['sliceId'] = series_id
1501         return self._download_json(
1502             'https://graph.ibl.api.bbc.co.uk/', pid, headers={
1503                 'Content-Type': 'application/json'
1504             }, data=json.dumps({
1505                 'id': '5692d93d5aac8d796a0305e895e61551',
1506                 'variables': variables,
1507             }).encode('utf-8'))['data']['programme']
1508
1509     @staticmethod
1510     def _get_playlist_data(data):
1511         return data
1512
1513     def _get_playlist_title(self, data):
1514         return self._get_default(data, 'title')
1515
1516
1517 class BBCCoUkIPlayerGroupIE(BBCCoUkIPlayerPlaylistBaseIE):
1518     IE_NAME = 'bbc.co.uk:iplayer:group'
1519     _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'group'
1520     _TESTS = [{
1521         # Available for over a year unlike 30 days for most other programmes
1522         'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1523         'info_dict': {
1524             'id': 'p02tcc32',
1525             'title': 'Bohemian Icons',
1526             'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1527         },
1528         'playlist_mincount': 10,
1529     }, {
1530         # all pages
1531         'url': 'https://www.bbc.co.uk/iplayer/group/p081d7j7',
1532         'info_dict': {
1533             'id': 'p081d7j7',
1534             'title': 'Music in Scotland',
1535             'description': 'Perfomances in Scotland and programmes featuring Scottish acts.',
1536         },
1537         'playlist_mincount': 47,
1538     }, {
1539         # explicit page
1540         'url': 'https://www.bbc.co.uk/iplayer/group/p081d7j7?page=2',
1541         'info_dict': {
1542             'id': 'p081d7j7',
1543             'title': 'Music in Scotland',
1544             'description': 'Perfomances in Scotland and programmes featuring Scottish acts.',
1545         },
1546         'playlist_mincount': 11,
1547     }]
1548     _PAGE_SIZE = 200
1549     _DESCRIPTION_KEY = 'synopses'
1550
1551     def _get_episode_image(self, episode):
1552         return self._get_default(episode, 'images', 'standard')
1553
1554     def _get_episode_field(self, episode, field):
1555         return episode.get(field)
1556
1557     @staticmethod
1558     def _get_elements(data):
1559         return data['elements']
1560
1561     @staticmethod
1562     def _get_episode(element):
1563         return element
1564
1565     def _call_api(self, pid, per_page, page=1, series_id=None):
1566         return self._download_json(
1567             'http://ibl.api.bbc.co.uk/ibl/v1/groups/%s/episodes' % pid,
1568             pid, query={
1569                 'page': page,
1570                 'per_page': per_page,
1571             })['group_episodes']
1572
1573     @staticmethod
1574     def _get_playlist_data(data):
1575         return data['group']
1576
1577     def _get_playlist_title(self, data):
1578         return data.get('title')
1579
1580
1581 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1582     IE_NAME = 'bbc.co.uk:playlist'
1583     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1584     _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1585     _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1586     _TESTS = [{
1587         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1588         'info_dict': {
1589             'id': 'b05rcz9v',
1590             'title': 'The Disappearance - Clips - BBC Four',
1591             'description': 'French thriller serial about a missing teenager.',
1592         },
1593         'playlist_mincount': 7,
1594     }, {
1595         # multipage playlist, explicit page
1596         'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1597         'info_dict': {
1598             'id': 'b00mfl7n',
1599             'title': 'Frozen Planet - Clips - BBC One',
1600             'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1601         },
1602         'playlist_mincount': 24,
1603     }, {
1604         # multipage playlist, all pages
1605         'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1606         'info_dict': {
1607             'id': 'b00mfl7n',
1608             'title': 'Frozen Planet - Clips - BBC One',
1609             'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1610         },
1611         'playlist_mincount': 142,
1612     }, {
1613         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1614         'only_matching': True,
1615     }, {
1616         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1617         'only_matching': True,
1618     }, {
1619         'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1620         'only_matching': True,
1621     }]
1622
1623     def _extract_title_and_description(self, webpage):
1624         title = self._og_search_title(webpage, fatal=False)
1625         description = self._og_search_description(webpage)
1626         return title, description