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