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.

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