[mediaset] extract unprotected M3U and MPD manifests(closes #17204)
[youtube-dl] / youtube_dl / extractor / mediaset.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .theplatform import ThePlatformBaseIE
7 from ..compat import (
8     compat_parse_qs,
9     compat_str,
10     compat_urllib_parse_urlparse,
11 )
12 from ..utils import (
13     ExtractorError,
14     int_or_none,
15     update_url_query,
16 )
17
18
19 class MediasetIE(ThePlatformBaseIE):
20     _TP_TLD = 'eu'
21     _VALID_URL = r'''(?x)
22                     (?:
23                         mediaset:|
24                         https?://
25                             (?:(?:www|static3)\.)?mediasetplay\.mediaset\.it/
26                             (?:
27                                 (?:video|on-demand)/(?:[^/]+/)+[^/]+_|
28                                 player/index\.html\?.*?\bprogramGuid=
29                             )
30                     )(?P<id>[0-9A-Z]{16})
31                     '''
32     _TESTS = [{
33         # full episode
34         'url': 'https://www.mediasetplay.mediaset.it/video/hellogoodbye/quarta-puntata_FAFU000000661824',
35         'md5': '9b75534d42c44ecef7bf1ffeacb7f85d',
36         'info_dict': {
37             'id': 'FAFU000000661824',
38             'ext': 'mp4',
39             'title': 'Quarta puntata',
40             'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
41             'thumbnail': r're:^https?://.*\.jpg$',
42             'duration': 1414.26,
43             'upload_date': '20161107',
44             'series': 'Hello Goodbye',
45             'timestamp': 1478532900,
46             'uploader': 'Rete 4',
47             'uploader_id': 'R4',
48         },
49     }, {
50         'url': 'https://www.mediasetplay.mediaset.it/video/matrix/puntata-del-25-maggio_F309013801000501',
51         'md5': '288532f0ad18307705b01e581304cd7b',
52         'info_dict': {
53             'id': 'F309013801000501',
54             'ext': 'mp4',
55             'title': 'Puntata del 25 maggio',
56             'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
57             'thumbnail': r're:^https?://.*\.jpg$',
58             'duration': 6565.007,
59             'upload_date': '20180526',
60             'series': 'Matrix',
61             'timestamp': 1527326245,
62             'uploader': 'Canale 5',
63             'uploader_id': 'C5',
64         },
65     }, {
66         # clip
67         'url': 'https://www.mediasetplay.mediaset.it/video/gogglebox/un-grande-classico-della-commedia-sexy_FAFU000000661680',
68         'only_matching': True,
69     }, {
70         # iframe simple
71         'url': 'https://static3.mediasetplay.mediaset.it/player/index.html?appKey=5ad3966b1de1c4000d5cec48&programGuid=FAFU000000665924&id=665924',
72         'only_matching': True,
73     }, {
74         # iframe twitter (from http://www.wittytv.it/se-prima-mi-fidavo-zero/)
75         'url': 'https://static3.mediasetplay.mediaset.it/player/index.html?appKey=5ad3966b1de1c4000d5cec48&programGuid=FAFU000000665104&id=665104',
76         'only_matching': True,
77     }, {
78         'url': 'mediaset:FAFU000000665924',
79         'only_matching': True,
80     }]
81
82     @staticmethod
83     def _extract_urls(ie, webpage):
84         def _qs(url):
85             return compat_parse_qs(compat_urllib_parse_urlparse(url).query)
86
87         def _program_guid(qs):
88             return qs.get('programGuid', [None])[0]
89
90         entries = []
91         for mobj in re.finditer(
92                 r'<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//(?:www\.)?video\.mediaset\.it/player/playerIFrame(?:Twitter)?\.shtml.*?)\1',
93                 webpage):
94             embed_url = mobj.group('url')
95             embed_qs = _qs(embed_url)
96             program_guid = _program_guid(embed_qs)
97             if program_guid:
98                 entries.append(embed_url)
99                 continue
100             video_id = embed_qs.get('id', [None])[0]
101             if not video_id:
102                 continue
103             urlh = ie._request_webpage(
104                 embed_url, video_id, note='Following embed URL redirect')
105             embed_url = compat_str(urlh.geturl())
106             program_guid = _program_guid(_qs(embed_url))
107             if program_guid:
108                 entries.append(embed_url)
109         return entries
110
111     def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
112         for video in smil.findall(self._xpath_ns('.//video', namespace)):
113             video.attrib['src'] = re.sub(r'(https?://vod05)t(-mediaset-it\.akamaized\.net/.+?.mpd)\?.+', r'\1\2', video.attrib['src'])
114         return super()._parse_smil_formats(smil, smil_url, video_id, namespace, f4m_params, transform_rtmp_url)
115
116     def _real_extract(self, url):
117         guid = self._match_id(url)
118         tp_path = 'PR1GhC/media/guid/2702976343/' + guid
119         info = self._extract_theplatform_metadata(tp_path, guid)
120
121         formats = []
122         subtitles = {}
123         first_e = None
124         for asset_type in ('SD', 'HD'):
125             # TODO: fixup ISM+none manifest URLs
126             for f in ('MPEG4', 'MPEG-DASH+none', 'M3U+none'):
127                 try:
128                     tp_formats, tp_subtitles = self._extract_theplatform_smil(
129                         update_url_query('http://link.theplatform.%s/s/%s' % (self._TP_TLD, tp_path), {
130                             'mbr': 'true',
131                             'formats': f,
132                             'assetTypes': asset_type,
133                         }), guid, 'Downloading %s %s SMIL data' % (f.split('+')[0], asset_type))
134                 except ExtractorError as e:
135                     if not first_e:
136                         first_e = e
137                     break
138                 for tp_f in tp_formats:
139                     tp_f['quality'] = 1 if asset_type == 'HD' else 0
140                 formats.extend(tp_formats)
141                 subtitles = self._merge_subtitles(subtitles, tp_subtitles)
142         if first_e and not formats:
143             raise first_e
144         self._sort_formats(formats)
145
146         fields = []
147         for templ, repls in (('tvSeason%sNumber', ('', 'Episode')), ('mediasetprogram$%s', ('brandTitle', 'numberOfViews', 'publishInfo'))):
148             fields.extend(templ % repl for repl in repls)
149         feed_data = self._download_json(
150             'https://feed.entertainment.tv.theplatform.eu/f/PR1GhC/mediaset-prod-all-programs/guid/-/' + guid,
151             guid, fatal=False, query={'fields': ','.join(fields)})
152         if feed_data:
153             publish_info = feed_data.get('mediasetprogram$publishInfo') or {}
154             info.update({
155                 'episode_number': int_or_none(feed_data.get('tvSeasonEpisodeNumber')),
156                 'season_number': int_or_none(feed_data.get('tvSeasonNumber')),
157                 'series': feed_data.get('mediasetprogram$brandTitle'),
158                 'uploader': publish_info.get('description'),
159                 'uploader_id': publish_info.get('channel'),
160                 'view_count': int_or_none(feed_data.get('mediasetprogram$numberOfViews')),
161             })
162
163         info.update({
164             'id': guid,
165             'formats': formats,
166             'subtitles': subtitles,
167         })
168         return info