youtube-dl

Another place where youtube-dl lives on
git clone git://git.oshgnacknak.de/youtube-dl.git
Log | Files | Refs | README | LICENSE

rai.py (18246B)


      1 # coding: utf-8
      2 from __future__ import unicode_literals
      3 
      4 import re
      5 
      6 from .common import InfoExtractor
      7 from ..compat import (
      8     compat_urlparse,
      9     compat_str,
     10 )
     11 from ..utils import (
     12     ExtractorError,
     13     determine_ext,
     14     find_xpath_attr,
     15     fix_xml_ampersands,
     16     GeoRestrictedError,
     17     int_or_none,
     18     parse_duration,
     19     remove_start,
     20     strip_or_none,
     21     try_get,
     22     unified_strdate,
     23     unified_timestamp,
     24     update_url_query,
     25     urljoin,
     26     xpath_text,
     27 )
     28 
     29 
     30 class RaiBaseIE(InfoExtractor):
     31     _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
     32     _GEO_COUNTRIES = ['IT']
     33     _GEO_BYPASS = False
     34 
     35     def _extract_relinker_info(self, relinker_url, video_id):
     36         if not re.match(r'https?://', relinker_url):
     37             return {'formats': [{'url': relinker_url}]}
     38 
     39         formats = []
     40         geoprotection = None
     41         is_live = None
     42         duration = None
     43 
     44         for platform in ('mon', 'flash', 'native'):
     45             relinker = self._download_xml(
     46                 relinker_url, video_id,
     47                 note='Downloading XML metadata for platform %s' % platform,
     48                 transform_source=fix_xml_ampersands,
     49                 query={'output': 45, 'pl': platform},
     50                 headers=self.geo_verification_headers())
     51 
     52             if not geoprotection:
     53                 geoprotection = xpath_text(
     54                     relinker, './geoprotection', default=None) == 'Y'
     55 
     56             if not is_live:
     57                 is_live = xpath_text(
     58                     relinker, './is_live', default=None) == 'Y'
     59             if not duration:
     60                 duration = parse_duration(xpath_text(
     61                     relinker, './duration', default=None))
     62 
     63             url_elem = find_xpath_attr(relinker, './url', 'type', 'content')
     64             if url_elem is None:
     65                 continue
     66 
     67             media_url = url_elem.text
     68 
     69             # This does not imply geo restriction (e.g.
     70             # http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
     71             if '/video_no_available.mp4' in media_url:
     72                 continue
     73 
     74             ext = determine_ext(media_url)
     75             if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
     76                 continue
     77 
     78             if ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
     79                 formats.extend(self._extract_m3u8_formats(
     80                     media_url, video_id, 'mp4', 'm3u8_native',
     81                     m3u8_id='hls', fatal=False))
     82             elif ext == 'f4m' or platform == 'flash':
     83                 manifest_url = update_url_query(
     84                     media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
     85                     {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
     86                 formats.extend(self._extract_f4m_formats(
     87                     manifest_url, video_id, f4m_id='hds', fatal=False))
     88             else:
     89                 bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
     90                 formats.append({
     91                     'url': media_url,
     92                     'tbr': bitrate if bitrate > 0 else None,
     93                     'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
     94                 })
     95 
     96         if not formats and geoprotection is True:
     97             self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
     98 
     99         return dict((k, v) for k, v in {
    100             'is_live': is_live,
    101             'duration': duration,
    102             'formats': formats,
    103         }.items() if v is not None)
    104 
    105     @staticmethod
    106     def _extract_subtitles(url, video_data):
    107         STL_EXT = 'stl'
    108         SRT_EXT = 'srt'
    109         subtitles = {}
    110         subtitles_array = video_data.get('subtitlesArray') or []
    111         for k in ('subtitles', 'subtitlesUrl'):
    112             subtitles_array.append({'url': video_data.get(k)})
    113         for subtitle in subtitles_array:
    114             sub_url = subtitle.get('url')
    115             if sub_url and isinstance(sub_url, compat_str):
    116                 sub_lang = subtitle.get('language') or 'it'
    117                 sub_url = urljoin(url, sub_url)
    118                 sub_ext = determine_ext(sub_url, SRT_EXT)
    119                 subtitles.setdefault(sub_lang, []).append({
    120                     'ext': sub_ext,
    121                     'url': sub_url,
    122                 })
    123                 if STL_EXT == sub_ext:
    124                     subtitles[sub_lang].append({
    125                         'ext': SRT_EXT,
    126                         'url': sub_url[:-len(STL_EXT)] + SRT_EXT,
    127                     })
    128         return subtitles
    129 
    130 
    131 class RaiPlayIE(RaiBaseIE):
    132     _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s))\.(?:html|json)' % RaiBaseIE._UUID_RE
    133     _TESTS = [{
    134         'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
    135         'md5': '8970abf8caf8aef4696e7b1f2adfc696',
    136         'info_dict': {
    137             'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
    138             'ext': 'mp4',
    139             'title': 'Report del 07/04/2014',
    140             'alt_title': 'St 2013/14 - Espresso nel caffè - 07/04/2014',
    141             'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
    142             'thumbnail': r're:^https?://.*\.jpg$',
    143             'uploader': 'Rai Gulp',
    144             'duration': 6160,
    145             'series': 'Report',
    146             'season': '2013/14',
    147             'subtitles': {
    148                 'it': 'count:2',
    149             },
    150         },
    151         'params': {
    152             'skip_download': True,
    153         },
    154     }, {
    155         'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
    156         'only_matching': True,
    157     }, {
    158         # subtitles at 'subtitlesArray' key (see #27698)
    159         'url': 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html',
    160         'only_matching': True,
    161     }]
    162 
    163     def _real_extract(self, url):
    164         base, video_id = re.match(self._VALID_URL, url).groups()
    165 
    166         media = self._download_json(
    167             base + '.json', video_id, 'Downloading video JSON')
    168 
    169         title = media['name']
    170 
    171         video = media['video']
    172 
    173         relinker_info = self._extract_relinker_info(video['content_url'], video_id)
    174         self._sort_formats(relinker_info['formats'])
    175 
    176         thumbnails = []
    177         for _, value in media.get('images', {}).items():
    178             if value:
    179                 thumbnails.append({
    180                     'url': urljoin(url, value),
    181                 })
    182 
    183         date_published = media.get('date_published')
    184         time_published = media.get('time_published')
    185         if date_published and time_published:
    186             date_published += ' ' + time_published
    187 
    188         subtitles = self._extract_subtitles(url, video)
    189 
    190         program_info = media.get('program_info') or {}
    191         season = media.get('season')
    192 
    193         info = {
    194             'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
    195             'display_id': video_id,
    196             'title': self._live_title(title) if relinker_info.get(
    197                 'is_live') else title,
    198             'alt_title': strip_or_none(media.get('subtitle')),
    199             'description': media.get('description'),
    200             'uploader': strip_or_none(media.get('channel')),
    201             'creator': strip_or_none(media.get('editor') or None),
    202             'duration': parse_duration(video.get('duration')),
    203             'timestamp': unified_timestamp(date_published),
    204             'thumbnails': thumbnails,
    205             'series': program_info.get('name'),
    206             'season_number': int_or_none(season),
    207             'season': season if (season and not season.isdigit()) else None,
    208             'episode': media.get('episode_title'),
    209             'episode_number': int_or_none(media.get('episode')),
    210             'subtitles': subtitles,
    211         }
    212 
    213         info.update(relinker_info)
    214         return info
    215 
    216 
    217 class RaiPlayLiveIE(RaiPlayIE):
    218     _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
    219     _TESTS = [{
    220         'url': 'http://www.raiplay.it/dirette/rainews24',
    221         'info_dict': {
    222             'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
    223             'display_id': 'rainews24',
    224             'ext': 'mp4',
    225             'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
    226             'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
    227             'uploader': 'Rai News 24',
    228             'creator': 'Rai News 24',
    229             'is_live': True,
    230         },
    231         'params': {
    232             'skip_download': True,
    233         },
    234     }]
    235 
    236 
    237 class RaiPlayPlaylistIE(InfoExtractor):
    238     _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))'
    239     _TESTS = [{
    240         'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
    241         'info_dict': {
    242             'id': 'nondirloalmiocapo',
    243             'title': 'Non dirlo al mio capo',
    244             'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
    245         },
    246         'playlist_mincount': 12,
    247     }]
    248 
    249     def _real_extract(self, url):
    250         base, playlist_id = re.match(self._VALID_URL, url).groups()
    251 
    252         program = self._download_json(
    253             base + '.json', playlist_id, 'Downloading program JSON')
    254 
    255         entries = []
    256         for b in (program.get('blocks') or []):
    257             for s in (b.get('sets') or []):
    258                 s_id = s.get('id')
    259                 if not s_id:
    260                     continue
    261                 medias = self._download_json(
    262                     '%s/%s.json' % (base, s_id), s_id,
    263                     'Downloading content set JSON', fatal=False)
    264                 if not medias:
    265                     continue
    266                 for m in (medias.get('items') or []):
    267                     path_id = m.get('path_id')
    268                     if not path_id:
    269                         continue
    270                     video_url = urljoin(url, path_id)
    271                     entries.append(self.url_result(
    272                         video_url, ie=RaiPlayIE.ie_key(),
    273                         video_id=RaiPlayIE._match_id(video_url)))
    274 
    275         return self.playlist_result(
    276             entries, playlist_id, program.get('name'),
    277             try_get(program, lambda x: x['program_info']['description']))
    278 
    279 
    280 class RaiIE(RaiBaseIE):
    281     _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
    282     _TESTS = [{
    283         # var uniquename = "ContentItem-..."
    284         # data-id="ContentItem-..."
    285         'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
    286         'info_dict': {
    287             'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
    288             'ext': 'mp4',
    289             'title': 'TG PRIMO TEMPO',
    290             'thumbnail': r're:^https?://.*\.jpg$',
    291             'duration': 1758,
    292             'upload_date': '20140612',
    293         },
    294         'skip': 'This content is available only in Italy',
    295     }, {
    296         # with ContentItem in many metas
    297         'url': 'http://www.rainews.it/dl/rainews/media/Weekend-al-cinema-da-Hollywood-arriva-il-thriller-di-Tate-Taylor-La-ragazza-del-treno-1632c009-c843-4836-bb65-80c33084a64b.html',
    298         'info_dict': {
    299             'id': '1632c009-c843-4836-bb65-80c33084a64b',
    300             'ext': 'mp4',
    301             'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
    302             'description': 'I film in uscita questa settimana.',
    303             'thumbnail': r're:^https?://.*\.png$',
    304             'duration': 833,
    305             'upload_date': '20161103',
    306         }
    307     }, {
    308         # with ContentItem in og:url
    309         'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
    310         'md5': '6865dd00cf0bbf5772fdd89d59bd768a',
    311         'info_dict': {
    312             'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
    313             'ext': 'mp4',
    314             'title': 'TG1 ore 20:00 del 03/11/2016',
    315             'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
    316             'thumbnail': r're:^https?://.*\.jpg$',
    317             'duration': 2214,
    318             'upload_date': '20161103',
    319         }
    320     }, {
    321         # initEdizione('ContentItem-...'
    322         'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
    323         'info_dict': {
    324             'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
    325             'ext': 'mp4',
    326             'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
    327             'duration': 2274,
    328             'upload_date': '20170401',
    329         },
    330         'skip': 'Changes daily',
    331     }, {
    332         # HLS live stream with ContentItem in og:url
    333         'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
    334         'info_dict': {
    335             'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
    336             'ext': 'mp4',
    337             'title': 'La diretta di Rainews24',
    338         },
    339         'params': {
    340             'skip_download': True,
    341         },
    342     }, {
    343         # ContentItem in iframe (see #12652) and subtitle at 'subtitlesUrl' key
    344         'url': 'http://www.presadiretta.rai.it/dl/portali/site/puntata/ContentItem-3ed19d13-26c2-46ff-a551-b10828262f1b.html',
    345         'info_dict': {
    346             'id': '1ad6dc64-444a-42a4-9bea-e5419ad2f5fd',
    347             'ext': 'mp4',
    348             'title': 'Partiti acchiappavoti - Presa diretta del 13/09/2015',
    349             'description': 'md5:d291b03407ec505f95f27970c0b025f4',
    350             'upload_date': '20150913',
    351             'subtitles': {
    352                 'it': 'count:2',
    353             },
    354         },
    355         'params': {
    356             'skip_download': True,
    357         },
    358     }, {
    359         # Direct MMS URL
    360         'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
    361         'only_matching': True,
    362     }, {
    363         'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
    364         'only_matching': True,
    365     }]
    366 
    367     def _extract_from_content_id(self, content_id, url):
    368         media = self._download_json(
    369             'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
    370             content_id, 'Downloading video JSON')
    371 
    372         title = media['name'].strip()
    373 
    374         media_type = media['type']
    375         if 'Audio' in media_type:
    376             relinker_info = {
    377                 'formats': [{
    378                     'format_id': media.get('formatoAudio'),
    379                     'url': media['audioUrl'],
    380                     'ext': media.get('formatoAudio'),
    381                 }]
    382             }
    383         elif 'Video' in media_type:
    384             relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
    385         else:
    386             raise ExtractorError('not a media file')
    387 
    388         self._sort_formats(relinker_info['formats'])
    389 
    390         thumbnails = []
    391         for image_type in ('image', 'image_medium', 'image_300'):
    392             thumbnail_url = media.get(image_type)
    393             if thumbnail_url:
    394                 thumbnails.append({
    395                     'url': compat_urlparse.urljoin(url, thumbnail_url),
    396                 })
    397 
    398         subtitles = self._extract_subtitles(url, media)
    399 
    400         info = {
    401             'id': content_id,
    402             'title': title,
    403             'description': strip_or_none(media.get('desc')),
    404             'thumbnails': thumbnails,
    405             'uploader': media.get('author'),
    406             'upload_date': unified_strdate(media.get('date')),
    407             'duration': parse_duration(media.get('length')),
    408             'subtitles': subtitles,
    409         }
    410 
    411         info.update(relinker_info)
    412 
    413         return info
    414 
    415     def _real_extract(self, url):
    416         video_id = self._match_id(url)
    417 
    418         webpage = self._download_webpage(url, video_id)
    419 
    420         content_item_id = None
    421 
    422         content_item_url = self._html_search_meta(
    423             ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
    424              'twitter:player', 'jsonlink'), webpage, default=None)
    425         if content_item_url:
    426             content_item_id = self._search_regex(
    427                 r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
    428                 'content item id', default=None)
    429 
    430         if not content_item_id:
    431             content_item_id = self._search_regex(
    432                 r'''(?x)
    433                     (?:
    434                         (?:initEdizione|drawMediaRaiTV)\(|
    435                         <(?:[^>]+\bdata-id|var\s+uniquename)=|
    436                         <iframe[^>]+\bsrc=
    437                     )
    438                     (["\'])
    439                     (?:(?!\1).)*\bContentItem-(?P<id>%s)
    440                 ''' % self._UUID_RE,
    441                 webpage, 'content item id', default=None, group='id')
    442 
    443         content_item_ids = set()
    444         if content_item_id:
    445             content_item_ids.add(content_item_id)
    446         if video_id not in content_item_ids:
    447             content_item_ids.add(video_id)
    448 
    449         for content_item_id in content_item_ids:
    450             try:
    451                 return self._extract_from_content_id(content_item_id, url)
    452             except GeoRestrictedError:
    453                 raise
    454             except ExtractorError:
    455                 pass
    456 
    457         relinker_url = self._proto_relative_url(self._search_regex(
    458             r'''(?x)
    459                 (?:
    460                     var\s+videoURL|
    461                     mediaInfo\.mediaUri
    462                 )\s*=\s*
    463                 ([\'"])
    464                 (?P<url>
    465                     (?:https?:)?
    466                     //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
    467                     (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
    468             ''',
    469             webpage, 'relinker URL', group='url'))
    470 
    471         relinker_info = self._extract_relinker_info(
    472             urljoin(url, relinker_url), video_id)
    473         self._sort_formats(relinker_info['formats'])
    474 
    475         title = self._search_regex(
    476             r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
    477             webpage, 'title', group='title',
    478             default=None) or self._og_search_title(webpage)
    479 
    480         info = {
    481             'id': video_id,
    482             'title': title,
    483         }
    484 
    485         info.update(relinker_info)
    486 
    487         return info