]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/globo.py
[youtube] De-prioritize auto-generated thumbnails
[yt-dlp.git] / yt_dlp / extractor / globo.py
CommitLineData
db2058f6
RA
1import base64
2import hashlib
3import json
f47754f0 4import random
26394d02 5import re
f47754f0
S
6
7from .common import InfoExtractor
e5187493 8from ..compat import (
e5187493
RA
9 compat_str,
10)
8c25f81b 11from ..utils import (
63c3ee4f 12 HEADRequest,
8c25f81b
PH
13 ExtractorError,
14 float_or_none,
26394d02 15 orderedSet,
e7d34c03 16 str_or_none,
b89378a6 17 try_get,
8c25f81b 18)
f47754f0
S
19
20
21class GloboIE(InfoExtractor):
25042f73 22 _VALID_URL = r'(?:globo:|https?://.+?\.globo\.com/(?:[^/]+/)*(?:v/(?:[^/]+/)?|videos/))(?P<id>\d{7,})'
d81ffc3a 23 _NETRC_MACHINE = 'globo'
ad607563 24 _TESTS = [{
ad607563 25 'url': 'http://g1.globo.com/carros/autoesporte/videos/t/exclusivos-do-g1/v/mercedes-benz-gla-passa-por-teste-de-colisao-na-europa/3607726/',
ad607563
S
26 'info_dict': {
27 'id': '3607726',
28 'ext': 'mp4',
29 'title': 'Mercedes-Benz GLA passa por teste de colisão na Europa',
30 'duration': 103.204,
b89378a6
AG
31 'uploader': 'G1',
32 'uploader_id': '2015',
33 },
34 'params': {
35 'skip_download': True,
264cd00f 36 },
ad607563 37 }, {
264cd00f 38 'url': 'http://globoplay.globo.com/v/4581987/',
ad607563 39 'info_dict': {
264cd00f 40 'id': '4581987',
ad607563 41 'ext': 'mp4',
264cd00f
S
42 'title': 'Acidentes de trânsito estão entre as maiores causas de queda de energia em SP',
43 'duration': 137.973,
44 'uploader': 'Rede Globo',
e7d34c03 45 'uploader_id': '196',
264cd00f 46 },
b89378a6
AG
47 'params': {
48 'skip_download': True,
49 },
264cd00f
S
50 }, {
51 'url': 'http://canalbrasil.globo.com/programas/sangue-latino/videos/3928201.html',
52 'only_matching': True,
53 }, {
54 'url': 'http://globosatplay.globo.com/globonews/v/4472924/',
55 'only_matching': True,
56 }, {
57 'url': 'http://globotv.globo.com/t/programa/v/clipe-sexo-e-as-negas-adeus/3836166/',
58 'only_matching': True,
59 }, {
60 'url': 'http://globotv.globo.com/canal-brasil/sangue-latino/t/todos-os-videos/v/ator-e-diretor-argentino-ricado-darin-fala-sobre-utopias-e-suas-perdas/3928201/',
61 'only_matching': True,
5d501a09
S
62 }, {
63 'url': 'http://canaloff.globo.com/programas/desejar-profundo/videos/4518560.html',
64 'only_matching': True,
26394d02
S
65 }, {
66 'url': 'globo:3607726',
67 'only_matching': True,
63c3ee4f
B
68 }, {
69 'url': 'https://globoplay.globo.com/v/10248083/',
70 'info_dict': {
71 'id': '10248083',
72 'ext': 'mp4',
73 'title': 'Melhores momentos: Equador 1 x 1 Brasil pelas Eliminatórias da Copa do Mundo 2022',
74 'duration': 530.964,
75 'uploader': 'SporTV',
76 'uploader_id': '698',
77 },
78 'params': {
79 'skip_download': True,
80 },
ad607563 81 }]
f47754f0 82
f47754f0
S
83 def _real_extract(self, url):
84 video_id = self._match_id(url)
85
63c3ee4f
B
86 self._request_webpage(
87 HEADRequest('https://globo-ab.globo.com/v2/selected-alternatives?experiments=player-isolated-experiment-02&skipImpressions=true'),
88 video_id, 'Getting cookies')
89
f47754f0 90 video = self._download_json(
db2058f6
RA
91 'http://api.globovideos.com/videos/%s/playlist' % video_id,
92 video_id)['videos'][0]
a06916d9 93 if not self.get_param('allow_unplayable_formats') and video.get('encrypted') is True:
88acdbc2 94 self.report_drm(video_id)
f47754f0
S
95
96 title = video['title']
f47754f0
S
97
98 formats = []
b89378a6 99 security = self._download_json(
63c3ee4f 100 'https://playback.video.globo.com/v2/video-session', video_id, 'Downloading security hash for %s' % video_id,
b89378a6
AG
101 headers={'content-type': 'application/json'}, data=json.dumps({
102 "player_type": "desktop",
103 "video_id": video_id,
104 "quality": "max",
105 "content_protection": "widevine",
106 "vsid": "581b986b-4c40-71f0-5a58-803e579d5fa2",
107 "tz": "-3.0:00"
108 }).encode())
109
63c3ee4f
B
110 self._request_webpage(HEADRequest(security['sources'][0]['url_template']), video_id, 'Getting locksession cookie')
111
112 security_hash = security['sources'][0]['token']
b89378a6
AG
113 if not security_hash:
114 message = security.get('message')
115 if message:
116 raise ExtractorError(
117 '%s returned error: %s' % (self.IE_NAME, message), expected=True)
118
119 hash_code = security_hash[:2]
120 padding = '%010d' % random.randint(1, 10000000000)
121 if hash_code in ('04', '14'):
122 received_time = security_hash[3:13]
123 received_md5 = security_hash[24:]
124 hash_prefix = security_hash[:23]
125 elif hash_code in ('02', '12', '03', '13'):
126 received_time = security_hash[2:12]
127 received_md5 = security_hash[22:]
128 padding += '1'
129 hash_prefix = '05' + security_hash[:22]
130
131 padded_sign_time = compat_str(int(received_time) + 86400) + padding
132 md5_data = (received_md5 + padded_sign_time + '0xAC10FD').encode()
133 signed_md5 = base64.urlsafe_b64encode(hashlib.md5(md5_data).digest()).decode().strip('=')
134 signed_hash = hash_prefix + padded_sign_time + signed_md5
63c3ee4f 135 source = security['sources'][0]['url_parts']
b89378a6
AG
136 resource_url = source['scheme'] + '://' + source['domain'] + source['path']
137 signed_url = '%s?h=%s&k=html5&a=%s' % (resource_url, signed_hash, 'F' if video.get('subscriber_only') else 'A')
138
3f047fc4
F
139 fmts, subtitles = self._extract_m3u8_formats_and_subtitles(
140 signed_url, video_id, 'mp4', entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)
141 formats.extend(fmts)
b89378a6
AG
142 self._sort_formats(formats)
143
f47754f0 144 for resource in video['resources']:
b89378a6 145 if resource.get('type') == 'subtitle':
30eb05cb 146 subtitles.setdefault(resource.get('language') or 'por', []).append({
b89378a6 147 'url': resource.get('url'),
30eb05cb 148 })
b89378a6
AG
149 subs = try_get(security, lambda x: x['source']['subtitles'], expected_type=dict) or {}
150 for sub_lang, sub_url in subs.items():
151 if sub_url:
152 subtitles.setdefault(sub_lang or 'por', []).append({
153 'url': sub_url,
db2058f6 154 })
b89378a6
AG
155 subs = try_get(security, lambda x: x['source']['subtitles_webvtt'], expected_type=dict) or {}
156 for sub_lang, sub_url in subs.items():
157 if sub_url:
158 subtitles.setdefault(sub_lang or 'por', []).append({
159 'url': sub_url,
8c72beb2 160 })
f47754f0 161
fffccaaf 162 duration = float_or_none(video.get('duration'), 1000)
fffccaaf 163 uploader = video.get('channel')
e7d34c03 164 uploader_id = str_or_none(video.get('channel_id'))
fffccaaf 165
f47754f0
S
166 return {
167 'id': video_id,
168 'title': title,
169 'duration': duration,
170 'uploader': uploader,
171 'uploader_id': uploader_id,
30eb05cb
RA
172 'formats': formats,
173 'subtitles': subtitles,
5f6a1245 174 }
ad607563
S
175
176
177class GloboArticleIE(InfoExtractor):
26394d02 178 _VALID_URL = r'https?://.+?\.globo\.com/(?:[^/]+/)*(?P<id>[^/.]+)(?:\.html)?'
ad607563
S
179
180 _VIDEOID_REGEXES = [
181 r'\bdata-video-id=["\'](\d{7,})',
182 r'\bdata-player-videosids=["\'](\d{7,})',
9e5751b9 183 r'\bvideosIDs\s*:\s*["\']?(\d{7,})',
ad607563
S
184 r'\bdata-id=["\'](\d{7,})',
185 r'<div[^>]+\bid=["\'](\d{7,})',
17b18388 186 r'<bs-player[^>]+\bvideoid=["\'](\d{8,})',
ad607563
S
187 ]
188
5d501a09 189 _TESTS = [{
ad607563 190 'url': 'http://g1.globo.com/jornal-nacional/noticia/2014/09/novidade-na-fiscalizacao-de-bagagem-pela-receita-provoca-discussoes.html',
ad607563 191 'info_dict': {
26394d02
S
192 'id': 'novidade-na-fiscalizacao-de-bagagem-pela-receita-provoca-discussoes',
193 'title': 'Novidade na fiscalização de bagagem pela Receita provoca discussões',
194 'description': 'md5:c3c4b4d4c30c32fce460040b1ac46b12',
195 },
196 'playlist_count': 1,
197 }, {
198 'url': 'http://g1.globo.com/pr/parana/noticia/2016/09/mpf-denuncia-lula-marisa-e-mais-seis-na-operacao-lava-jato.html',
199 'info_dict': {
200 'id': 'mpf-denuncia-lula-marisa-e-mais-seis-na-operacao-lava-jato',
201 'title': "Lula era o 'comandante máximo' do esquema da Lava Jato, diz MPF",
202 'description': 'md5:8aa7cc8beda4dc71cc8553e00b77c54c',
203 },
204 'playlist_count': 6,
5d501a09
S
205 }, {
206 'url': 'http://gq.globo.com/Prazeres/Poder/noticia/2015/10/all-o-desafio-assista-ao-segundo-capitulo-da-serie.html',
207 'only_matching': True,
208 }, {
209 'url': 'http://gshow.globo.com/programas/tv-xuxa/O-Programa/noticia/2014/01/xuxa-e-junno-namoram-muuuito-em-luau-de-zeze-di-camargo-e-luciano.html',
210 'only_matching': True,
9e5751b9
S
211 }, {
212 'url': 'http://oglobo.globo.com/rio/a-amizade-entre-um-entregador-de-farmacia-um-piano-19946271',
213 'only_matching': True,
17b18388
B
214 }, {
215 'url': 'https://ge.globo.com/video/ta-na-area-como-foi-assistir-ao-jogo-do-palmeiras-que-a-globo-nao-passou-10287094.ghtml',
216 'info_dict': {
217 'id': 'ta-na-area-como-foi-assistir-ao-jogo-do-palmeiras-que-a-globo-nao-passou-10287094',
218 'title': 'Tá na Área: como foi assistir ao jogo do Palmeiras que a Globo não passou',
219 'description': 'md5:2d089d036c4c9675117d3a56f8c61739',
220 },
221 'playlist_count': 1,
5d501a09 222 }]
ad607563
S
223
224 @classmethod
225 def suitable(cls, url):
226 return False if GloboIE.suitable(url) else super(GloboArticleIE, cls).suitable(url)
227
228 def _real_extract(self, url):
229 display_id = self._match_id(url)
230 webpage = self._download_webpage(url, display_id)
26394d02
S
231 video_ids = []
232 for video_regex in self._VIDEOID_REGEXES:
233 video_ids.extend(re.findall(video_regex, webpage))
234 entries = [
235 self.url_result('globo:%s' % video_id, GloboIE.ie_key())
236 for video_id in orderedSet(video_ids)]
17b18388 237 title = self._og_search_title(webpage)
26394d02
S
238 description = self._html_search_meta('description', webpage)
239 return self.playlist_result(entries, display_id, title, description)