turner.py 11 KB

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