globo.py 8.7 KB

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