logo

youtube-dl

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

turner.py (11115B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .adobepass import AdobePassIE
  5. from ..compat import compat_str
  6. from ..utils import (
  7. fix_xml_ampersands,
  8. xpath_text,
  9. int_or_none,
  10. determine_ext,
  11. float_or_none,
  12. parse_duration,
  13. xpath_attr,
  14. update_url_query,
  15. ExtractorError,
  16. strip_or_none,
  17. url_or_none,
  18. )
  19. class TurnerBaseIE(AdobePassIE):
  20. _AKAMAI_SPE_TOKEN_CACHE = {}
  21. def _extract_timestamp(self, video_data):
  22. return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts'))
  23. def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None):
  24. secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*'
  25. token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path)
  26. if not token:
  27. query = {
  28. 'path': secure_path,
  29. }
  30. if custom_tokenizer_query:
  31. query.update(custom_tokenizer_query)
  32. else:
  33. query['videoId'] = content_id
  34. if ap_data.get('auth_required'):
  35. query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name'])
  36. auth = self._download_xml(
  37. tokenizer_src, content_id, query=query)
  38. error_msg = xpath_text(auth, 'error/msg')
  39. if error_msg:
  40. raise ExtractorError(error_msg, expected=True)
  41. token = xpath_text(auth, 'token')
  42. if not token:
  43. return video_url
  44. self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token
  45. return video_url + '?hdnea=' + token
  46. def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}, fatal=False):
  47. video_data = self._download_xml(
  48. data_src, video_id,
  49. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  50. fatal=fatal)
  51. if not video_data:
  52. return {}
  53. video_id = video_data.attrib['id']
  54. title = xpath_text(video_data, 'headline', fatal=True)
  55. content_id = xpath_text(video_data, 'contentId') or video_id
  56. # rtmp_src = xpath_text(video_data, 'akamai/src')
  57. # if rtmp_src:
  58. # split_rtmp_src = rtmp_src.split(',')
  59. # if len(split_rtmp_src) == 2:
  60. # rtmp_src = split_rtmp_src[1]
  61. # aifp = xpath_text(video_data, 'akamai/aifp', default='')
  62. urls = []
  63. formats = []
  64. thumbnails = []
  65. subtitles = {}
  66. rex = re.compile(
  67. r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?')
  68. # Possible formats locations: files/file, files/groupFiles/files
  69. # and maybe others
  70. for video_file in video_data.findall('.//file'):
  71. video_url = url_or_none(video_file.text.strip())
  72. if not video_url:
  73. continue
  74. ext = determine_ext(video_url)
  75. if video_url.startswith('/mp4:protected/'):
  76. continue
  77. # TODO Correct extraction for these files
  78. # protected_path_data = path_data.get('protected')
  79. # if not protected_path_data or not rtmp_src:
  80. # continue
  81. # protected_path = self._search_regex(
  82. # r'/mp4:(.+)\.[a-z0-9]', video_url, 'secure path')
  83. # auth = self._download_webpage(
  84. # protected_path_data['tokenizer_src'], query={
  85. # 'path': protected_path,
  86. # 'videoId': content_id,
  87. # 'aifp': aifp,
  88. # })
  89. # token = xpath_text(auth, 'token')
  90. # if not token:
  91. # continue
  92. # video_url = rtmp_src + video_url + '?' + token
  93. elif video_url.startswith('/secure/'):
  94. secure_path_data = path_data.get('secure')
  95. if not secure_path_data:
  96. continue
  97. video_url = self._add_akamai_spe_token(
  98. secure_path_data['tokenizer_src'],
  99. secure_path_data['media_src'] + video_url,
  100. content_id, ap_data)
  101. elif not re.match('https?://', video_url):
  102. base_path_data = path_data.get(ext, path_data.get('default', {}))
  103. media_src = base_path_data.get('media_src')
  104. if not media_src:
  105. continue
  106. video_url = media_src + video_url
  107. if video_url in urls:
  108. continue
  109. urls.append(video_url)
  110. format_id = video_file.get('bitrate')
  111. if ext in ('scc', 'srt', 'vtt'):
  112. subtitles.setdefault('en', []).append({
  113. 'ext': ext,
  114. 'url': video_url,
  115. })
  116. elif ext == 'png':
  117. thumbnails.append({
  118. 'id': format_id,
  119. 'url': video_url,
  120. })
  121. elif ext == 'smil':
  122. formats.extend(self._extract_smil_formats(
  123. video_url, video_id, fatal=False))
  124. elif re.match(r'https?://[^/]+\.akamaihd\.net/[iz]/', video_url):
  125. formats.extend(self._extract_akamai_formats(
  126. video_url, video_id, {
  127. 'hds': path_data.get('f4m', {}).get('host'),
  128. # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com
  129. # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com
  130. # ssl.cdn.turner.com
  131. 'http': 'pmd.cdn.turner.com',
  132. }))
  133. elif ext == 'm3u8':
  134. m3u8_formats = self._extract_m3u8_formats(
  135. video_url, video_id, 'mp4',
  136. m3u8_id=format_id or 'hls', fatal=False)
  137. if '/secure/' in video_url and '?hdnea=' in video_url:
  138. for f in m3u8_formats:
  139. f['_seekable'] = False
  140. formats.extend(m3u8_formats)
  141. elif ext == 'f4m':
  142. formats.extend(self._extract_f4m_formats(
  143. update_url_query(video_url, {'hdcore': '3.7.0'}),
  144. video_id, f4m_id=format_id or 'hds', fatal=False))
  145. else:
  146. f = {
  147. 'format_id': format_id,
  148. 'url': video_url,
  149. 'ext': ext,
  150. }
  151. mobj = rex.search(video_url)
  152. if mobj:
  153. f.update({
  154. 'width': int(mobj.group('width')),
  155. 'height': int(mobj.group('height')),
  156. 'tbr': int_or_none(mobj.group('bitrate')),
  157. })
  158. elif isinstance(format_id, compat_str):
  159. if format_id.isdigit():
  160. f['tbr'] = int(format_id)
  161. else:
  162. mobj = re.match(r'ios_(audio|[0-9]+)$', format_id)
  163. if mobj:
  164. if mobj.group(1) == 'audio':
  165. f.update({
  166. 'vcodec': 'none',
  167. 'ext': 'm4a',
  168. })
  169. else:
  170. f['tbr'] = int(mobj.group(1))
  171. formats.append(f)
  172. self._sort_formats(formats)
  173. for source in video_data.findall('closedCaptions/source'):
  174. for track in source.findall('track'):
  175. track_url = url_or_none(track.get('url'))
  176. if not track_url or track_url.endswith('/big'):
  177. continue
  178. lang = track.get('lang') or track.get('label') or 'en'
  179. subtitles.setdefault(lang, []).append({
  180. 'url': track_url,
  181. 'ext': {
  182. 'scc': 'scc',
  183. 'webvtt': 'vtt',
  184. 'smptett': 'tt',
  185. }.get(source.get('format'))
  186. })
  187. thumbnails.extend({
  188. 'id': image.get('cut') or image.get('name'),
  189. 'url': image.text,
  190. 'width': int_or_none(image.get('width')),
  191. 'height': int_or_none(image.get('height')),
  192. } for image in video_data.findall('images/image'))
  193. is_live = xpath_text(video_data, 'isLive') == 'true'
  194. return {
  195. 'id': video_id,
  196. 'title': self._live_title(title) if is_live else title,
  197. 'formats': formats,
  198. 'subtitles': subtitles,
  199. 'thumbnails': thumbnails,
  200. 'thumbnail': xpath_text(video_data, 'poster'),
  201. 'description': strip_or_none(xpath_text(video_data, 'description')),
  202. 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')),
  203. 'timestamp': self._extract_timestamp(video_data),
  204. 'upload_date': xpath_attr(video_data, 'metas', 'version'),
  205. 'series': xpath_text(video_data, 'showTitle'),
  206. 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')),
  207. 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')),
  208. 'is_live': is_live,
  209. }
  210. def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None):
  211. streams_data = self._download_json(
  212. 'http://medium.ngtv.io/media/%s/tv' % media_id,
  213. media_id)['media']['tv']
  214. duration = None
  215. chapters = []
  216. formats = []
  217. for supported_type in ('unprotected', 'bulkaes'):
  218. stream_data = streams_data.get(supported_type, {})
  219. m3u8_url = stream_data.get('secureUrl') or stream_data.get('url')
  220. if not m3u8_url:
  221. continue
  222. if stream_data.get('playlistProtection') == 'spe':
  223. m3u8_url = self._add_akamai_spe_token(
  224. 'http://token.ngtv.io/token/token_spe',
  225. m3u8_url, media_id, ap_data or {}, tokenizer_query)
  226. formats.extend(self._extract_m3u8_formats(
  227. m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False))
  228. duration = float_or_none(stream_data.get('totalRuntime'))
  229. if not chapters:
  230. for chapter in stream_data.get('contentSegments', []):
  231. start_time = float_or_none(chapter.get('start'))
  232. chapter_duration = float_or_none(chapter.get('duration'))
  233. if start_time is None or chapter_duration is None:
  234. continue
  235. chapters.append({
  236. 'start_time': start_time,
  237. 'end_time': start_time + chapter_duration,
  238. })
  239. self._sort_formats(formats)
  240. return {
  241. 'formats': formats,
  242. 'chapters': chapters,
  243. 'duration': duration,
  244. }