You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

253 lines
10 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import uuid
  4. import xml.etree.ElementTree as etree
  5. import json
  6. import re
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_str,
  10. compat_etree_register_namespace,
  11. )
  12. from ..utils import (
  13. extract_attributes,
  14. xpath_with_ns,
  15. xpath_element,
  16. xpath_text,
  17. int_or_none,
  18. parse_duration,
  19. ExtractorError,
  20. determine_ext,
  21. )
  22. class ITVIE(InfoExtractor):
  23. _VALID_URL = r'https?://(?:www\.)?itv\.com/hub/[^/]+/(?P<id>[0-9a-zA-Z]+)'
  24. _GEO_COUNTRIES = ['GB']
  25. _TESTS = [{
  26. 'url': 'http://www.itv.com/hub/mr-bean-animated-series/2a2936a0053',
  27. 'info_dict': {
  28. 'id': '2a2936a0053',
  29. 'ext': 'flv',
  30. 'title': 'Home Movie',
  31. },
  32. 'params': {
  33. # rtmp download
  34. 'skip_download': True,
  35. },
  36. }, {
  37. # unavailable via data-playlist-url
  38. 'url': 'https://www.itv.com/hub/through-the-keyhole/2a2271a0033',
  39. 'only_matching': True,
  40. }]
  41. def _real_extract(self, url):
  42. video_id = self._match_id(url)
  43. webpage = self._download_webpage(url, video_id)
  44. params = extract_attributes(self._search_regex(
  45. r'(?s)(<[^>]+id="video"[^>]*>)', webpage, 'params'))
  46. ns_map = {
  47. 'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
  48. 'tem': 'http://tempuri.org/',
  49. 'itv': 'http://schemas.datacontract.org/2004/07/Itv.BB.Mercury.Common.Types',
  50. 'com': 'http://schemas.itv.com/2009/05/Common',
  51. }
  52. for ns, full_ns in ns_map.items():
  53. compat_etree_register_namespace(ns, full_ns)
  54. def _add_ns(name):
  55. return xpath_with_ns(name, ns_map)
  56. def _add_sub_element(element, name):
  57. return etree.SubElement(element, _add_ns(name))
  58. production_id = (
  59. params.get('data-video-autoplay-id') or
  60. '%s#001' % (
  61. params.get('data-video-episode-id') or
  62. video_id.replace('a', '/')))
  63. req_env = etree.Element(_add_ns('soapenv:Envelope'))
  64. _add_sub_element(req_env, 'soapenv:Header')
  65. body = _add_sub_element(req_env, 'soapenv:Body')
  66. get_playlist = _add_sub_element(body, ('tem:GetPlaylist'))
  67. request = _add_sub_element(get_playlist, 'tem:request')
  68. _add_sub_element(request, 'itv:ProductionId').text = production_id
  69. _add_sub_element(request, 'itv:RequestGuid').text = compat_str(uuid.uuid4()).upper()
  70. vodcrid = _add_sub_element(request, 'itv:Vodcrid')
  71. _add_sub_element(vodcrid, 'com:Id')
  72. _add_sub_element(request, 'itv:Partition')
  73. user_info = _add_sub_element(get_playlist, 'tem:userInfo')
  74. _add_sub_element(user_info, 'itv:Broadcaster').text = 'Itv'
  75. _add_sub_element(user_info, 'itv:DM')
  76. _add_sub_element(user_info, 'itv:RevenueScienceValue')
  77. _add_sub_element(user_info, 'itv:SessionId')
  78. _add_sub_element(user_info, 'itv:SsoToken')
  79. _add_sub_element(user_info, 'itv:UserToken')
  80. site_info = _add_sub_element(get_playlist, 'tem:siteInfo')
  81. _add_sub_element(site_info, 'itv:AdvertisingRestriction').text = 'None'
  82. _add_sub_element(site_info, 'itv:AdvertisingSite').text = 'ITV'
  83. _add_sub_element(site_info, 'itv:AdvertisingType').text = 'Any'
  84. _add_sub_element(site_info, 'itv:Area').text = 'ITVPLAYER.VIDEO'
  85. _add_sub_element(site_info, 'itv:Category')
  86. _add_sub_element(site_info, 'itv:Platform').text = 'DotCom'
  87. _add_sub_element(site_info, 'itv:Site').text = 'ItvCom'
  88. device_info = _add_sub_element(get_playlist, 'tem:deviceInfo')
  89. _add_sub_element(device_info, 'itv:ScreenSize').text = 'Big'
  90. player_info = _add_sub_element(get_playlist, 'tem:playerInfo')
  91. _add_sub_element(player_info, 'itv:Version').text = '2'
  92. headers = self.geo_verification_headers()
  93. headers.update({
  94. 'Content-Type': 'text/xml; charset=utf-8',
  95. 'SOAPAction': 'http://tempuri.org/PlaylistService/GetPlaylist',
  96. })
  97. info = self._search_json_ld(webpage, video_id, default={})
  98. formats = []
  99. subtitles = {}
  100. def extract_subtitle(sub_url):
  101. ext = determine_ext(sub_url, 'ttml')
  102. subtitles.setdefault('en', []).append({
  103. 'url': sub_url,
  104. 'ext': 'ttml' if ext == 'xml' else ext,
  105. })
  106. resp_env = self._download_xml(
  107. params['data-playlist-url'], video_id,
  108. headers=headers, data=etree.tostring(req_env))
  109. playlist = xpath_element(resp_env, './/Playlist')
  110. if playlist is None:
  111. fault_code = xpath_text(resp_env, './/faultcode')
  112. fault_string = xpath_text(resp_env, './/faultstring')
  113. if fault_code == 'InvalidGeoRegion':
  114. self.raise_geo_restricted(
  115. msg=fault_string, countries=self._GEO_COUNTRIES)
  116. elif fault_code != 'InvalidEntity':
  117. raise ExtractorError(
  118. '%s said: %s' % (self.IE_NAME, fault_string), expected=True)
  119. info.update({
  120. 'title': self._og_search_title(webpage),
  121. 'episode_title': params.get('data-video-episode'),
  122. 'series': params.get('data-video-title'),
  123. })
  124. else:
  125. title = xpath_text(playlist, 'EpisodeTitle', default=None)
  126. info.update({
  127. 'title': title,
  128. 'episode_title': title,
  129. 'episode_number': int_or_none(xpath_text(playlist, 'EpisodeNumber')),
  130. 'series': xpath_text(playlist, 'ProgrammeTitle'),
  131. 'duration': parse_duration(xpath_text(playlist, 'Duration')),
  132. })
  133. video_element = xpath_element(playlist, 'VideoEntries/Video', fatal=True)
  134. media_files = xpath_element(video_element, 'MediaFiles', fatal=True)
  135. rtmp_url = media_files.attrib['base']
  136. for media_file in media_files.findall('MediaFile'):
  137. play_path = xpath_text(media_file, 'URL')
  138. if not play_path:
  139. continue
  140. tbr = int_or_none(media_file.get('bitrate'), 1000)
  141. f = {
  142. 'format_id': 'rtmp' + ('-%d' % tbr if tbr else ''),
  143. 'play_path': play_path,
  144. # Providing this swfVfy allows to avoid truncated downloads
  145. 'player_url': 'http://www.itv.com/mercury/Mercury_VideoPlayer.swf',
  146. 'page_url': url,
  147. 'tbr': tbr,
  148. 'ext': 'flv',
  149. }
  150. app = self._search_regex(
  151. 'rtmpe?://[^/]+/(.+)$', rtmp_url, 'app', default=None)
  152. if app:
  153. f.update({
  154. 'url': rtmp_url.split('?', 1)[0],
  155. 'app': app,
  156. })
  157. else:
  158. f['url'] = rtmp_url
  159. formats.append(f)
  160. for caption_url in video_element.findall('ClosedCaptioningURIs/URL'):
  161. if caption_url.text:
  162. extract_subtitle(caption_url.text)
  163. ios_playlist_url = params.get('data-video-playlist') or params.get('data-video-id')
  164. hmac = params.get('data-video-hmac')
  165. if ios_playlist_url and hmac and re.match(r'https?://', ios_playlist_url):
  166. headers = self.geo_verification_headers()
  167. headers.update({
  168. 'Accept': 'application/vnd.itv.vod.playlist.v2+json',
  169. 'Content-Type': 'application/json',
  170. 'hmac': hmac.upper(),
  171. })
  172. ios_playlist = self._download_json(
  173. ios_playlist_url, video_id, data=json.dumps({
  174. 'user': {
  175. 'itvUserId': '',
  176. 'entitlements': [],
  177. 'token': ''
  178. },
  179. 'device': {
  180. 'manufacturer': 'Safari',
  181. 'model': '5',
  182. 'os': {
  183. 'name': 'Windows NT',
  184. 'version': '6.1',
  185. 'type': 'desktop'
  186. }
  187. },
  188. 'client': {
  189. 'version': '4.1',
  190. 'id': 'browser'
  191. },
  192. 'variantAvailability': {
  193. 'featureset': {
  194. 'min': ['hls', 'aes', 'outband-webvtt'],
  195. 'max': ['hls', 'aes', 'outband-webvtt']
  196. },
  197. 'platformTag': 'dotcom'
  198. }
  199. }).encode(), headers=headers, fatal=False)
  200. if ios_playlist:
  201. video_data = ios_playlist.get('Playlist', {}).get('Video', {})
  202. ios_base_url = video_data.get('Base')
  203. for media_file in video_data.get('MediaFiles', []):
  204. href = media_file.get('Href')
  205. if not href:
  206. continue
  207. if ios_base_url:
  208. href = ios_base_url + href
  209. ext = determine_ext(href)
  210. if ext == 'm3u8':
  211. formats.extend(self._extract_m3u8_formats(
  212. href, video_id, 'mp4', entry_protocol='m3u8_native',
  213. m3u8_id='hls', fatal=False))
  214. else:
  215. formats.append({
  216. 'url': href,
  217. })
  218. subs = video_data.get('Subtitles')
  219. if isinstance(subs, list):
  220. for sub in subs:
  221. if not isinstance(sub, dict):
  222. continue
  223. href = sub.get('Href')
  224. if isinstance(href, compat_str):
  225. extract_subtitle(href)
  226. if not info.get('duration'):
  227. info['duration'] = parse_duration(video_data.get('Duration'))
  228. self._sort_formats(formats)
  229. info.update({
  230. 'id': video_id,
  231. 'formats': formats,
  232. 'subtitles': subtitles,
  233. })
  234. return info