turner.py 11 KB

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