]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/globo.py
[globo] handle login errors
[yt-dlp.git] / youtube_dl / 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
RA
11from ..compat import (
12 compat_HTTPError,
13 compat_str,
14)
8c25f81b
PH
15from ..utils import (
16 ExtractorError,
17 float_or_none,
fffccaaf 18 int_or_none,
26394d02 19 orderedSet,
e7d34c03 20 str_or_none,
8c25f81b 21)
f47754f0
S
22
23
24class GloboIE(InfoExtractor):
25042f73 25 _VALID_URL = r'(?:globo:|https?://.+?\.globo\.com/(?:[^/]+/)*(?:v/(?:[^/]+/)?|videos/))(?P<id>\d{7,})'
db2058f6 26 _LOGGED_IN = False
ad607563 27 _TESTS = [{
ad607563
S
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/',
29 'md5': 'b3ccc801f75cd04a914d51dadb83a78d',
30 'info_dict': {
31 'id': '3607726',
32 'ext': 'mp4',
33 'title': 'Mercedes-Benz GLA passa por teste de colisão na Europa',
34 'duration': 103.204,
35 'uploader': 'Globo.com',
e7d34c03 36 'uploader_id': '265',
264cd00f 37 },
ad607563 38 }, {
264cd00f
S
39 'url': 'http://globoplay.globo.com/v/4581987/',
40 'md5': 'f36a1ecd6a50da1577eee6dd17f67eff',
ad607563 41 'info_dict': {
264cd00f 42 'id': '4581987',
ad607563 43 'ext': 'mp4',
264cd00f
S
44 'title': 'Acidentes de trânsito estão entre as maiores causas de queda de energia em SP',
45 'duration': 137.973,
46 'uploader': 'Rede Globo',
e7d34c03 47 'uploader_id': '196',
264cd00f
S
48 },
49 }, {
50 'url': 'http://canalbrasil.globo.com/programas/sangue-latino/videos/3928201.html',
51 'only_matching': True,
52 }, {
53 'url': 'http://globosatplay.globo.com/globonews/v/4472924/',
54 'only_matching': True,
55 }, {
56 'url': 'http://globotv.globo.com/t/programa/v/clipe-sexo-e-as-negas-adeus/3836166/',
57 'only_matching': True,
58 }, {
59 '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/',
60 'only_matching': True,
5d501a09
S
61 }, {
62 'url': 'http://canaloff.globo.com/programas/desejar-profundo/videos/4518560.html',
63 'only_matching': True,
26394d02
S
64 }, {
65 'url': 'globo:3607726',
66 'only_matching': True,
ad607563 67 }]
f47754f0 68
db2058f6
RA
69 def _real_initialize(self):
70 if self._LOGGED_IN:
71 return
72
73 email, password = self._get_login_info()
74 if email is None:
75 return
76
e5187493
RA
77 try:
78 self._download_json(
79 'https://login.globo.com/api/authentication', None, data=json.dumps({
80 'payload': {
81 'email': email,
82 'password': password,
83 'serviceId': 4654,
84 },
85 }).encode(), headers={
86 'Content-Type': 'application/json; charset=utf-8',
87 })
88 except ExtractorError as e:
89 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
90 resp = self._parse_json(e.cause.read(), None)
91 raise ExtractorError(resp.get('userMessage') or resp['id'], expected=True)
92 raise
db2058f6 93 self._LOGGED_IN = True
f47754f0
S
94
95 def _real_extract(self, url):
96 video_id = self._match_id(url)
97
f47754f0 98 video = self._download_json(
db2058f6
RA
99 'http://api.globovideos.com/videos/%s/playlist' % video_id,
100 video_id)['videos'][0]
f47754f0
S
101
102 title = video['title']
f47754f0
S
103
104 formats = []
f47754f0
S
105 for resource in video['resources']:
106 resource_id = resource.get('_id')
db2058f6
RA
107 resource_url = resource.get('url')
108 if not resource_id or not resource_url:
f47754f0
S
109 continue
110
111 security = self._download_json(
db2058f6
RA
112 'http://security.video.globo.com/videos/%s/hash' % video_id,
113 video_id, 'Downloading security hash for %s' % resource_id, query={
114 'player': 'flash',
115 'version': '17.0.0.132',
116 'resource_id': resource_id,
117 })
f47754f0
S
118
119 security_hash = security.get('hash')
120 if not security_hash:
121 message = security.get('message')
122 if message:
123 raise ExtractorError(
124 '%s returned error: %s' % (self.IE_NAME, message), expected=True)
125 continue
126
127 hash_code = security_hash[:2]
128 received_time = int(security_hash[2:12])
129 received_random = security_hash[12:22]
130 received_md5 = security_hash[22:]
131
db2058f6 132 sign_time = received_time + 86400
f47754f0
S
133 padding = '%010d' % random.randint(1, 10000000000)
134
db2058f6
RA
135 md5_data = (received_md5 + str(sign_time) + padding + '0xFF01DD').encode()
136 signed_md5 = base64.urlsafe_b64encode(hashlib.md5(md5_data).digest()).decode().strip('=')
f47754f0
S
137 signed_hash = hash_code + compat_str(received_time) + received_random + compat_str(sign_time) + padding + signed_md5
138
8c72beb2
S
139 signed_url = '%s?h=%s&k=%s' % (resource_url, signed_hash, 'flash')
140 if resource_id.endswith('m3u8') or resource_url.endswith('.m3u8'):
7e5edcfd 141 formats.extend(self._extract_m3u8_formats(
5d235ca7 142 signed_url, resource_id, 'mp4', entry_protocol='m3u8_native',
7e5edcfd 143 m3u8_id='hls', fatal=False))
db2058f6
RA
144 elif resource_id.endswith('mpd') or resource_url.endswith('.mpd'):
145 formats.extend(self._extract_mpd_formats(
146 signed_url, resource_id, mpd_id='dash', fatal=False))
147 elif resource_id.endswith('manifest') or resource_url.endswith('/manifest'):
148 formats.extend(self._extract_ism_formats(
149 signed_url, resource_id, ism_id='mss', fatal=False))
8c72beb2
S
150 else:
151 formats.append({
152 'url': signed_url,
a4a6b7b8
S
153 'format_id': 'http-%s' % resource_id,
154 'height': int_or_none(resource.get('height')),
8c72beb2 155 })
f47754f0
S
156
157 self._sort_formats(formats)
158
fffccaaf 159 duration = float_or_none(video.get('duration'), 1000)
fffccaaf 160 uploader = video.get('channel')
e7d34c03 161 uploader_id = str_or_none(video.get('channel_id'))
fffccaaf 162
f47754f0
S
163 return {
164 'id': video_id,
165 'title': title,
166 'duration': duration,
167 'uploader': uploader,
168 'uploader_id': uploader_id,
f47754f0 169 'formats': formats
5f6a1245 170 }
ad607563
S
171
172
173class GloboArticleIE(InfoExtractor):
26394d02 174 _VALID_URL = r'https?://.+?\.globo\.com/(?:[^/]+/)*(?P<id>[^/.]+)(?:\.html)?'
ad607563
S
175
176 _VIDEOID_REGEXES = [
177 r'\bdata-video-id=["\'](\d{7,})',
178 r'\bdata-player-videosids=["\'](\d{7,})',
9e5751b9 179 r'\bvideosIDs\s*:\s*["\']?(\d{7,})',
ad607563
S
180 r'\bdata-id=["\'](\d{7,})',
181 r'<div[^>]+\bid=["\'](\d{7,})',
182 ]
183
5d501a09 184 _TESTS = [{
ad607563 185 'url': 'http://g1.globo.com/jornal-nacional/noticia/2014/09/novidade-na-fiscalizacao-de-bagagem-pela-receita-provoca-discussoes.html',
ad607563 186 'info_dict': {
26394d02
S
187 'id': 'novidade-na-fiscalizacao-de-bagagem-pela-receita-provoca-discussoes',
188 'title': 'Novidade na fiscalização de bagagem pela Receita provoca discussões',
189 'description': 'md5:c3c4b4d4c30c32fce460040b1ac46b12',
190 },
191 'playlist_count': 1,
192 }, {
193 'url': 'http://g1.globo.com/pr/parana/noticia/2016/09/mpf-denuncia-lula-marisa-e-mais-seis-na-operacao-lava-jato.html',
194 'info_dict': {
195 'id': 'mpf-denuncia-lula-marisa-e-mais-seis-na-operacao-lava-jato',
196 'title': "Lula era o 'comandante máximo' do esquema da Lava Jato, diz MPF",
197 'description': 'md5:8aa7cc8beda4dc71cc8553e00b77c54c',
198 },
199 'playlist_count': 6,
5d501a09
S
200 }, {
201 'url': 'http://gq.globo.com/Prazeres/Poder/noticia/2015/10/all-o-desafio-assista-ao-segundo-capitulo-da-serie.html',
202 'only_matching': True,
203 }, {
204 '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',
205 'only_matching': True,
9e5751b9
S
206 }, {
207 'url': 'http://oglobo.globo.com/rio/a-amizade-entre-um-entregador-de-farmacia-um-piano-19946271',
208 'only_matching': True,
5d501a09 209 }]
ad607563
S
210
211 @classmethod
212 def suitable(cls, url):
213 return False if GloboIE.suitable(url) else super(GloboArticleIE, cls).suitable(url)
214
215 def _real_extract(self, url):
216 display_id = self._match_id(url)
217 webpage = self._download_webpage(url, display_id)
26394d02
S
218 video_ids = []
219 for video_regex in self._VIDEOID_REGEXES:
220 video_ids.extend(re.findall(video_regex, webpage))
221 entries = [
222 self.url_result('globo:%s' % video_id, GloboIE.ie_key())
223 for video_id in orderedSet(video_ids)]
224 title = self._og_search_title(webpage, fatal=False)
225 description = self._html_search_meta('description', webpage)
226 return self.playlist_result(entries, display_id, title, description)