turner.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. xpath_text,
  8. int_or_none,
  9. determine_ext,
  10. float_or_none,
  11. parse_duration,
  12. xpath_attr,
  13. update_url_query,
  14. ExtractorError,
  15. strip_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={}):
  45. video_data = self._download_xml(data_src, video_id)
  46. video_id = video_data.attrib['id']
  47. title = xpath_text(video_data, 'headline', fatal=True)
  48. content_id = xpath_text(video_data, 'contentId') or video_id
  49. # rtmp_src = xpath_text(video_data, 'akamai/src')
  50. # if rtmp_src:
  51. # splited_rtmp_src = rtmp_src.split(',')
  52. # if len(splited_rtmp_src) == 2:
  53. # rtmp_src = splited_rtmp_src[1]
  54. # aifp = xpath_text(video_data, 'akamai/aifp', default='')
  55. urls = []
  56. formats = []
  57. rex = re.compile(
  58. r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?')
  59. # Possible formats locations: files/file, files/groupFiles/files
  60. # and maybe others
  61. for video_file in video_data.findall('.//file'):
  62. video_url = video_file.text.strip()
  63. if not video_url:
  64. continue
  65. ext = determine_ext(video_url)
  66. if video_url.startswith('/mp4:protected/'):
  67. continue
  68. # TODO Correct extraction for these files
  69. # protected_path_data = path_data.get('protected')
  70. # if not protected_path_data or not rtmp_src:
  71. # continue
  72. # protected_path = self._search_regex(
  73. # r'/mp4:(.+)\.[a-z0-9]', video_url, 'secure path')
  74. # auth = self._download_webpage(
  75. # protected_path_data['tokenizer_src'], query={
  76. # 'path': protected_path,
  77. # 'videoId': content_id,
  78. # 'aifp': aifp,
  79. # })
  80. # token = xpath_text(auth, 'token')
  81. # if not token:
  82. # continue
  83. # video_url = rtmp_src + video_url + '?' + token
  84. elif video_url.startswith('/secure/'):
  85. secure_path_data = path_data.get('secure')
  86. if not secure_path_data:
  87. continue
  88. video_url = self._add_akamai_spe_token(
  89. secure_path_data['tokenizer_src'],
  90. secure_path_data['media_src'] + video_url,
  91. content_id, ap_data)
  92. elif not re.match('https?://', video_url):
  93. base_path_data = path_data.get(ext, path_data.get('default', {}))
  94. media_src = base_path_data.get('media_src')
  95. if not media_src:
  96. continue
  97. video_url = media_src + video_url
  98. if video_url in urls:
  99. continue
  100. urls.append(video_url)
  101. format_id = video_file.get('bitrate')
  102. if ext == 'smil':
  103. formats.extend(self._extract_smil_formats(
  104. video_url, video_id, fatal=False))
  105. elif ext == 'm3u8':
  106. m3u8_formats = self._extract_m3u8_formats(
  107. video_url, video_id, 'mp4',
  108. m3u8_id=format_id or 'hls', fatal=False)
  109. if '/secure/' in video_url and '?hdnea=' in video_url:
  110. for f in m3u8_formats:
  111. f['_seekable'] = False
  112. formats.extend(m3u8_formats)
  113. elif ext == 'f4m':
  114. formats.extend(self._extract_f4m_formats(
  115. update_url_query(video_url, {'hdcore': '3.7.0'}),
  116. video_id, f4m_id=format_id or 'hds', fatal=False))
  117. else:
  118. f = {
  119. 'format_id': format_id,
  120. 'url': video_url,
  121. 'ext': ext,
  122. }
  123. mobj = rex.search(format_id + video_url)
  124. if mobj:
  125. f.update({
  126. 'width': int(mobj.group('width')),
  127. 'height': int(mobj.group('height')),
  128. 'tbr': int_or_none(mobj.group('bitrate')),
  129. })
  130. elif isinstance(format_id, compat_str):
  131. if format_id.isdigit():
  132. f['tbr'] = int(format_id)
  133. else:
  134. mobj = re.match(r'ios_(audio|[0-9]+)$', format_id)
  135. if mobj:
  136. if mobj.group(1) == 'audio':
  137. f.update({
  138. 'vcodec': 'none',
  139. 'ext': 'm4a',
  140. })
  141. else:
  142. f['tbr'] = int(mobj.group(1))
  143. formats.append(f)
  144. self._sort_formats(formats)
  145. subtitles = {}
  146. for source in video_data.findall('closedCaptions/source'):
  147. for track in source.findall('track'):
  148. track_url = track.get('url')
  149. if not isinstance(track_url, compat_str) or track_url.endswith('/big'):
  150. continue
  151. lang = track.get('lang') or track.get('label') or 'en'
  152. subtitles.setdefault(lang, []).append({
  153. 'url': track_url,
  154. 'ext': {
  155. 'scc': 'scc',
  156. 'webvtt': 'vtt',
  157. 'smptett': 'tt',
  158. }.get(source.get('format'))
  159. })
  160. thumbnails = [{
  161. 'id': image.get('cut'),
  162. 'url': image.text,
  163. 'width': int_or_none(image.get('width')),
  164. 'height': int_or_none(image.get('height')),
  165. } for image in video_data.findall('images/image')]
  166. is_live = xpath_text(video_data, 'isLive') == 'true'
  167. return {
  168. 'id': video_id,
  169. 'title': self._live_title(title) if is_live else title,
  170. 'formats': formats,
  171. 'subtitles': subtitles,
  172. 'thumbnails': thumbnails,
  173. 'thumbnail': xpath_text(video_data, 'poster'),
  174. 'description': strip_or_none(xpath_text(video_data, 'description')),
  175. 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')),
  176. 'timestamp': self._extract_timestamp(video_data),
  177. 'upload_date': xpath_attr(video_data, 'metas', 'version'),
  178. 'series': xpath_text(video_data, 'showTitle'),
  179. 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')),
  180. 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')),
  181. 'is_live': is_live,
  182. }
  183. def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None):
  184. streams_data = self._download_json(
  185. 'http://medium.ngtv.io/media/%s/tv' % media_id,
  186. media_id)['media']['tv']
  187. duration = None
  188. chapters = []
  189. formats = []
  190. for supported_type in ('unprotected', 'bulkaes'):
  191. stream_data = streams_data.get(supported_type, {})
  192. m3u8_url = stream_data.get('secureUrl') or stream_data.get('url')
  193. if not m3u8_url:
  194. continue
  195. if stream_data.get('playlistProtection') == 'spe':
  196. m3u8_url = self._add_akamai_spe_token(
  197. 'http://token.ngtv.io/token/token_spe',
  198. m3u8_url, media_id, ap_data or {}, tokenizer_query)
  199. formats.extend(self._extract_m3u8_formats(
  200. m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False))
  201. duration = float_or_none(stream_data.get('totalRuntime'))
  202. if not chapters:
  203. for chapter in stream_data.get('contentSegments', []):
  204. start_time = float_or_none(chapter.get('start'))
  205. chapter_duration = float_or_none(chapter.get('duration'))
  206. if start_time is None or chapter_duration is None:
  207. continue
  208. chapters.append({
  209. 'start_time': start_time,
  210. 'end_time': start_time + chapter_duration,
  211. })
  212. self._sort_formats(formats)
  213. return {
  214. 'formats': formats,
  215. 'chapters': chapters,
  216. 'duration': duration,
  217. }