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