logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

globo.py (9793B)


  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. _NETRC_MACHINE = 'globo'
  23. _TESTS = [{
  24. 'url': 'http://g1.globo.com/carros/autoesporte/videos/t/exclusivos-do-g1/v/mercedes-benz-gla-passa-por-teste-de-colisao-na-europa/3607726/',
  25. 'md5': 'b3ccc801f75cd04a914d51dadb83a78d',
  26. 'info_dict': {
  27. 'id': '3607726',
  28. 'ext': 'mp4',
  29. 'title': 'Mercedes-Benz GLA passa por teste de colisão na Europa',
  30. 'duration': 103.204,
  31. 'uploader': 'Globo.com',
  32. 'uploader_id': '265',
  33. },
  34. }, {
  35. 'url': 'http://globoplay.globo.com/v/4581987/',
  36. 'md5': 'f36a1ecd6a50da1577eee6dd17f67eff',
  37. 'info_dict': {
  38. 'id': '4581987',
  39. 'ext': 'mp4',
  40. 'title': 'Acidentes de trânsito estão entre as maiores causas de queda de energia em SP',
  41. 'duration': 137.973,
  42. 'uploader': 'Rede Globo',
  43. 'uploader_id': '196',
  44. },
  45. }, {
  46. 'url': 'http://canalbrasil.globo.com/programas/sangue-latino/videos/3928201.html',
  47. 'only_matching': True,
  48. }, {
  49. 'url': 'http://globosatplay.globo.com/globonews/v/4472924/',
  50. 'only_matching': True,
  51. }, {
  52. 'url': 'http://globotv.globo.com/t/programa/v/clipe-sexo-e-as-negas-adeus/3836166/',
  53. 'only_matching': True,
  54. }, {
  55. '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/',
  56. 'only_matching': True,
  57. }, {
  58. 'url': 'http://canaloff.globo.com/programas/desejar-profundo/videos/4518560.html',
  59. 'only_matching': True,
  60. }, {
  61. 'url': 'globo:3607726',
  62. 'only_matching': True,
  63. }]
  64. def _real_initialize(self):
  65. email, password = self._get_login_info()
  66. if email is None:
  67. return
  68. try:
  69. glb_id = (self._download_json(
  70. 'https://login.globo.com/api/authentication', None, data=json.dumps({
  71. 'payload': {
  72. 'email': email,
  73. 'password': password,
  74. 'serviceId': 4654,
  75. },
  76. }).encode(), headers={
  77. 'Content-Type': 'application/json; charset=utf-8',
  78. }) or {}).get('glbId')
  79. if glb_id:
  80. self._set_cookie('.globo.com', 'GLBID', glb_id)
  81. except ExtractorError as e:
  82. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  83. resp = self._parse_json(e.cause.read(), None)
  84. raise ExtractorError(resp.get('userMessage') or resp['id'], expected=True)
  85. raise
  86. def _real_extract(self, url):
  87. video_id = self._match_id(url)
  88. video = self._download_json(
  89. 'http://api.globovideos.com/videos/%s/playlist' % video_id,
  90. video_id)['videos'][0]
  91. if video.get('encrypted') is True:
  92. raise ExtractorError('This video is DRM protected.', expected=True)
  93. title = video['title']
  94. formats = []
  95. subtitles = {}
  96. for resource in video['resources']:
  97. resource_id = resource.get('_id')
  98. resource_url = resource.get('url')
  99. resource_type = resource.get('type')
  100. if not resource_url or (resource_type == 'media' and not resource_id) or resource_type not in ('subtitle', 'media'):
  101. continue
  102. if resource_type == 'subtitle':
  103. subtitles.setdefault(resource.get('language') or 'por', []).append({
  104. 'url': resource_url,
  105. })
  106. continue
  107. security = self._download_json(
  108. 'http://security.video.globo.com/videos/%s/hash' % video_id,
  109. video_id, 'Downloading security hash for %s' % resource_id, query={
  110. 'player': 'desktop',
  111. 'version': '5.19.1',
  112. 'resource_id': resource_id,
  113. })
  114. security_hash = security.get('hash')
  115. if not security_hash:
  116. message = security.get('message')
  117. if message:
  118. raise ExtractorError(
  119. '%s returned error: %s' % (self.IE_NAME, message), expected=True)
  120. continue
  121. hash_code = security_hash[:2]
  122. padding = '%010d' % random.randint(1, 10000000000)
  123. if hash_code in ('04', '14'):
  124. received_time = security_hash[3:13]
  125. received_md5 = security_hash[24:]
  126. hash_prefix = security_hash[:23]
  127. elif hash_code in ('02', '12', '03', '13'):
  128. received_time = security_hash[2:12]
  129. received_md5 = security_hash[22:]
  130. padding += '1'
  131. hash_prefix = '05' + security_hash[:22]
  132. padded_sign_time = compat_str(int(received_time) + 86400) + padding
  133. md5_data = (received_md5 + padded_sign_time + '0xAC10FD').encode()
  134. signed_md5 = base64.urlsafe_b64encode(hashlib.md5(md5_data).digest()).decode().strip('=')
  135. signed_hash = hash_prefix + padded_sign_time + signed_md5
  136. 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 '')
  137. if resource_id.endswith('m3u8') or resource_url.endswith('.m3u8'):
  138. formats.extend(self._extract_m3u8_formats(
  139. signed_url, resource_id, 'mp4', entry_protocol='m3u8_native',
  140. m3u8_id='hls', fatal=False))
  141. elif resource_id.endswith('mpd') or resource_url.endswith('.mpd'):
  142. formats.extend(self._extract_mpd_formats(
  143. signed_url, resource_id, mpd_id='dash', fatal=False))
  144. elif resource_id.endswith('manifest') or resource_url.endswith('/manifest'):
  145. formats.extend(self._extract_ism_formats(
  146. signed_url, resource_id, ism_id='mss', fatal=False))
  147. else:
  148. formats.append({
  149. 'url': signed_url,
  150. 'format_id': 'http-%s' % resource_id,
  151. 'height': int_or_none(resource.get('height')),
  152. })
  153. self._sort_formats(formats)
  154. duration = float_or_none(video.get('duration'), 1000)
  155. uploader = video.get('channel')
  156. uploader_id = str_or_none(video.get('channel_id'))
  157. return {
  158. 'id': video_id,
  159. 'title': title,
  160. 'duration': duration,
  161. 'uploader': uploader,
  162. 'uploader_id': uploader_id,
  163. 'formats': formats,
  164. 'subtitles': subtitles,
  165. }
  166. class GloboArticleIE(InfoExtractor):
  167. _VALID_URL = r'https?://.+?\.globo\.com/(?:[^/]+/)*(?P<id>[^/.]+)(?:\.html)?'
  168. _VIDEOID_REGEXES = [
  169. r'\bdata-video-id=["\'](\d{7,})',
  170. r'\bdata-player-videosids=["\'](\d{7,})',
  171. r'\bvideosIDs\s*:\s*["\']?(\d{7,})',
  172. r'\bdata-id=["\'](\d{7,})',
  173. r'<div[^>]+\bid=["\'](\d{7,})',
  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. @classmethod
  202. def suitable(cls, url):
  203. return False if GloboIE.suitable(url) else super(GloboArticleIE, cls).suitable(url)
  204. def _real_extract(self, url):
  205. display_id = self._match_id(url)
  206. webpage = self._download_webpage(url, display_id)
  207. video_ids = []
  208. for video_regex in self._VIDEOID_REGEXES:
  209. video_ids.extend(re.findall(video_regex, webpage))
  210. entries = [
  211. self.url_result('globo:%s' % video_id, GloboIE.ie_key())
  212. for video_id in orderedSet(video_ids)]
  213. title = self._og_search_title(webpage, fatal=False)
  214. description = self._html_search_meta('description', webpage)
  215. return self.playlist_result(entries, display_id, title, description)