globo.py 9.9 KB

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