[globo] fix format extraction(closes #20319)
[youtube-dl] / youtube_dl / extractor / globo.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import hashlib
6 import json
7 import random
8 import re
9
10 from .common import InfoExtractor
11 from ..compat import (
12     compat_HTTPError,
13     compat_str,
14 )
15 from ..utils import (
16     ExtractorError,
17     float_or_none,
18     int_or_none,
19     orderedSet,
20     str_or_none,
21 )
22
23
24 class GloboIE(InfoExtractor):
25     _VALID_URL = r'(?:globo:|https?://.+?\.globo\.com/(?:[^/]+/)*(?:v/(?:[^/]+/)?|videos/))(?P<id>\d{7,})'
26     _NETRC_MACHINE = 'globo'
27     _TESTS = [{
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',
36             'uploader_id': '265',
37         },
38     }, {
39         'url': 'http://globoplay.globo.com/v/4581987/',
40         'md5': 'f36a1ecd6a50da1577eee6dd17f67eff',
41         'info_dict': {
42             'id': '4581987',
43             'ext': 'mp4',
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',
47             'uploader_id': '196',
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,
61     }, {
62         'url': 'http://canaloff.globo.com/programas/desejar-profundo/videos/4518560.html',
63         'only_matching': True,
64     }, {
65         'url': 'globo:3607726',
66         'only_matching': True,
67     }]
68
69     def _real_initialize(self):
70         email, password = self._get_login_info()
71         if email is None:
72             return
73
74         try:
75             glb_id = (self._download_json(
76                 'https://login.globo.com/api/authentication', None, data=json.dumps({
77                     'payload': {
78                         'email': email,
79                         'password': password,
80                         'serviceId': 4654,
81                     },
82                 }).encode(), headers={
83                     'Content-Type': 'application/json; charset=utf-8',
84                 }) or {}).get('glbId')
85             if glb_id:
86                 self._set_cookie('.globo.com', 'GLBID', glb_id)
87         except ExtractorError as e:
88             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
89                 resp = self._parse_json(e.cause.read(), None)
90                 raise ExtractorError(resp.get('userMessage') or resp['id'], expected=True)
91             raise
92
93     def _real_extract(self, url):
94         video_id = self._match_id(url)
95
96         video = self._download_json(
97             'http://api.globovideos.com/videos/%s/playlist' % video_id,
98             video_id)['videos'][0]
99         if video.get('encrypted') is True:
100             raise ExtractorError('This video is DRM protected.', expected=True)
101
102         title = video['title']
103
104         formats = []
105         for resource in video['resources']:
106             resource_id = resource.get('_id')
107             resource_url = resource.get('url')
108             if not resource_id or not resource_url:
109                 continue
110
111             security = self._download_json(
112                 'http://security.video.globo.com/videos/%s/hash' % video_id,
113                 video_id, 'Downloading security hash for %s' % resource_id, query={
114                     'player': 'desktop',
115                     'version': '5.19.1',
116                     'resource_id': resource_id,
117                 })
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             assert security_hash[:2] in ('04', '14')
128             received_time = security_hash[3:13]
129             received_md5 = security_hash[24:]
130
131             sign_time = compat_str(int(received_time) + 86400)
132             padding = '%010d' % random.randint(1, 10000000000)
133
134             md5_data = (received_md5 + sign_time + padding + '0xAC10FD').encode()
135             signed_md5 = base64.urlsafe_b64encode(hashlib.md5(md5_data).digest()).decode().strip('=')
136             signed_hash = security_hash[:23] + sign_time + padding + signed_md5
137
138             signed_url = '%s?h=%s&k=html5&a=%s&u=%s' % (resource_url, signed_hash, 'F' if video.get('subscriber_only') else 'A', security.get('user') or '')
139             if resource_id.endswith('m3u8') or resource_url.endswith('.m3u8'):
140                 formats.extend(self._extract_m3u8_formats(
141                     signed_url, resource_id, 'mp4', entry_protocol='m3u8_native',
142                     m3u8_id='hls', fatal=False))
143             elif resource_id.endswith('mpd') or resource_url.endswith('.mpd'):
144                 formats.extend(self._extract_mpd_formats(
145                     signed_url, resource_id, mpd_id='dash', fatal=False))
146             elif resource_id.endswith('manifest') or resource_url.endswith('/manifest'):
147                 formats.extend(self._extract_ism_formats(
148                     signed_url, resource_id, ism_id='mss', fatal=False))
149             else:
150                 formats.append({
151                     'url': signed_url,
152                     'format_id': 'http-%s' % resource_id,
153                     'height': int_or_none(resource.get('height')),
154                 })
155
156         self._sort_formats(formats)
157
158         duration = float_or_none(video.get('duration'), 1000)
159         uploader = video.get('channel')
160         uploader_id = str_or_none(video.get('channel_id'))
161
162         return {
163             'id': video_id,
164             'title': title,
165             'duration': duration,
166             'uploader': uploader,
167             'uploader_id': uploader_id,
168             'formats': formats
169         }
170
171
172 class GloboArticleIE(InfoExtractor):
173     _VALID_URL = r'https?://.+?\.globo\.com/(?:[^/]+/)*(?P<id>[^/.]+)(?:\.html)?'
174
175     _VIDEOID_REGEXES = [
176         r'\bdata-video-id=["\'](\d{7,})',
177         r'\bdata-player-videosids=["\'](\d{7,})',
178         r'\bvideosIDs\s*:\s*["\']?(\d{7,})',
179         r'\bdata-id=["\'](\d{7,})',
180         r'<div[^>]+\bid=["\'](\d{7,})',
181     ]
182
183     _TESTS = [{
184         'url': 'http://g1.globo.com/jornal-nacional/noticia/2014/09/novidade-na-fiscalizacao-de-bagagem-pela-receita-provoca-discussoes.html',
185         'info_dict': {
186             'id': 'novidade-na-fiscalizacao-de-bagagem-pela-receita-provoca-discussoes',
187             'title': 'Novidade na fiscalização de bagagem pela Receita provoca discussões',
188             'description': 'md5:c3c4b4d4c30c32fce460040b1ac46b12',
189         },
190         'playlist_count': 1,
191     }, {
192         'url': 'http://g1.globo.com/pr/parana/noticia/2016/09/mpf-denuncia-lula-marisa-e-mais-seis-na-operacao-lava-jato.html',
193         'info_dict': {
194             'id': 'mpf-denuncia-lula-marisa-e-mais-seis-na-operacao-lava-jato',
195             'title': "Lula era o 'comandante máximo' do esquema da Lava Jato, diz MPF",
196             'description': 'md5:8aa7cc8beda4dc71cc8553e00b77c54c',
197         },
198         'playlist_count': 6,
199     }, {
200         'url': 'http://gq.globo.com/Prazeres/Poder/noticia/2015/10/all-o-desafio-assista-ao-segundo-capitulo-da-serie.html',
201         'only_matching': True,
202     }, {
203         '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',
204         'only_matching': True,
205     }, {
206         'url': 'http://oglobo.globo.com/rio/a-amizade-entre-um-entregador-de-farmacia-um-piano-19946271',
207         'only_matching': True,
208     }]
209
210     @classmethod
211     def suitable(cls, url):
212         return False if GloboIE.suitable(url) else super(GloboArticleIE, cls).suitable(url)
213
214     def _real_extract(self, url):
215         display_id = self._match_id(url)
216         webpage = self._download_webpage(url, display_id)
217         video_ids = []
218         for video_regex in self._VIDEOID_REGEXES:
219             video_ids.extend(re.findall(video_regex, webpage))
220         entries = [
221             self.url_result('globo:%s' % video_id, GloboIE.ie_key())
222             for video_id in orderedSet(video_ids)]
223         title = self._og_search_title(webpage, fatal=False)
224         description = self._html_search_meta('description', webpage)
225         return self.playlist_result(entries, display_id, title, description)