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.

217 lines
8.7 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. req_env = etree.Element(_add_ns('soapenv:Envelope'))
  54. _add_sub_element(req_env, 'soapenv:Header')
  55. body = _add_sub_element(req_env, 'soapenv:Body')
  56. get_playlist = _add_sub_element(body, ('tem:GetPlaylist'))
  57. request = _add_sub_element(get_playlist, 'tem:request')
  58. _add_sub_element(request, 'itv:ProductionId').text = params['data-video-id']
  59. _add_sub_element(request, 'itv:RequestGuid').text = compat_str(uuid.uuid4()).upper()
  60. vodcrid = _add_sub_element(request, 'itv:Vodcrid')
  61. _add_sub_element(vodcrid, 'com:Id')
  62. _add_sub_element(request, 'itv:Partition')
  63. user_info = _add_sub_element(get_playlist, 'tem:userInfo')
  64. _add_sub_element(user_info, 'itv:Broadcaster').text = 'Itv'
  65. _add_sub_element(user_info, 'itv:DM')
  66. _add_sub_element(user_info, 'itv:RevenueScienceValue')
  67. _add_sub_element(user_info, 'itv:SessionId')
  68. _add_sub_element(user_info, 'itv:SsoToken')
  69. _add_sub_element(user_info, 'itv:UserToken')
  70. site_info = _add_sub_element(get_playlist, 'tem:siteInfo')
  71. _add_sub_element(site_info, 'itv:AdvertisingRestriction').text = 'None'
  72. _add_sub_element(site_info, 'itv:AdvertisingSite').text = 'ITV'
  73. _add_sub_element(site_info, 'itv:AdvertisingType').text = 'Any'
  74. _add_sub_element(site_info, 'itv:Area').text = 'ITVPLAYER.VIDEO'
  75. _add_sub_element(site_info, 'itv:Category')
  76. _add_sub_element(site_info, 'itv:Platform').text = 'DotCom'
  77. _add_sub_element(site_info, 'itv:Site').text = 'ItvCom'
  78. device_info = _add_sub_element(get_playlist, 'tem:deviceInfo')
  79. _add_sub_element(device_info, 'itv:ScreenSize').text = 'Big'
  80. player_info = _add_sub_element(get_playlist, 'tem:playerInfo')
  81. _add_sub_element(player_info, 'itv:Version').text = '2'
  82. headers = self.geo_verification_headers()
  83. headers.update({
  84. 'Content-Type': 'text/xml; charset=utf-8',
  85. 'SOAPAction': 'http://tempuri.org/PlaylistService/GetPlaylist',
  86. })
  87. resp_env = self._download_xml(
  88. params['data-playlist-url'], video_id,
  89. headers=headers, data=etree.tostring(req_env))
  90. playlist = xpath_element(resp_env, './/Playlist')
  91. if playlist is None:
  92. fault_code = xpath_text(resp_env, './/faultcode')
  93. fault_string = xpath_text(resp_env, './/faultstring')
  94. if fault_code == 'InvalidGeoRegion':
  95. self.raise_geo_restricted(
  96. msg=fault_string, countries=self._GEO_COUNTRIES)
  97. raise ExtractorError('%s said: %s' % (self.IE_NAME, fault_string))
  98. title = xpath_text(playlist, 'EpisodeTitle', fatal=True)
  99. video_element = xpath_element(playlist, 'VideoEntries/Video', fatal=True)
  100. media_files = xpath_element(video_element, 'MediaFiles', fatal=True)
  101. rtmp_url = media_files.attrib['base']
  102. formats = []
  103. for media_file in media_files.findall('MediaFile'):
  104. play_path = xpath_text(media_file, 'URL')
  105. if not play_path:
  106. continue
  107. tbr = int_or_none(media_file.get('bitrate'), 1000)
  108. f = {
  109. 'format_id': 'rtmp' + ('-%d' % tbr if tbr else ''),
  110. 'play_path': play_path,
  111. # Providing this swfVfy allows to avoid truncated downloads
  112. 'player_url': 'http://www.itv.com/mercury/Mercury_VideoPlayer.swf',
  113. 'page_url': url,
  114. 'tbr': tbr,
  115. 'ext': 'flv',
  116. }
  117. app = self._search_regex(
  118. 'rtmpe?://[^/]+/(.+)$', rtmp_url, 'app', default=None)
  119. if app:
  120. f.update({
  121. 'url': rtmp_url.split('?', 1)[0],
  122. 'app': app,
  123. })
  124. else:
  125. f['url'] = rtmp_url
  126. formats.append(f)
  127. ios_playlist_url = params.get('data-video-playlist')
  128. hmac = params.get('data-video-hmac')
  129. if ios_playlist_url and hmac:
  130. headers = self.geo_verification_headers()
  131. headers.update({
  132. 'Accept': 'application/vnd.itv.vod.playlist.v2+json',
  133. 'Content-Type': 'application/json',
  134. 'hmac': hmac.upper(),
  135. })
  136. ios_playlist = self._download_json(
  137. ios_playlist_url, video_id, data=json.dumps({
  138. 'user': {
  139. 'itvUserId': '',
  140. 'entitlements': [],
  141. 'token': ''
  142. },
  143. 'device': {
  144. 'manufacturer': 'Apple',
  145. 'model': 'iPad',
  146. 'os': {
  147. 'name': 'iPhone OS',
  148. 'version': '9.3',
  149. 'type': 'ios'
  150. }
  151. },
  152. 'client': {
  153. 'version': '4.1',
  154. 'id': 'browser'
  155. },
  156. 'variantAvailability': {
  157. 'featureset': {
  158. 'min': ['hls', 'aes'],
  159. 'max': ['hls', 'aes']
  160. },
  161. 'platformTag': 'mobile'
  162. }
  163. }).encode(), headers=headers, fatal=False)
  164. if ios_playlist:
  165. video_data = ios_playlist.get('Playlist', {}).get('Video', {})
  166. ios_base_url = video_data.get('Base')
  167. for media_file in video_data.get('MediaFiles', []):
  168. href = media_file.get('Href')
  169. if not href:
  170. continue
  171. if ios_base_url:
  172. href = ios_base_url + href
  173. ext = determine_ext(href)
  174. if ext == 'm3u8':
  175. formats.extend(self._extract_m3u8_formats(
  176. href, video_id, 'mp4', entry_protocol='m3u8_native',
  177. m3u8_id='hls', fatal=False))
  178. else:
  179. formats.append({
  180. 'url': href,
  181. })
  182. self._sort_formats(formats)
  183. subtitles = {}
  184. for caption_url in video_element.findall('ClosedCaptioningURIs/URL'):
  185. if not caption_url.text:
  186. continue
  187. ext = determine_ext(caption_url.text, 'ttml')
  188. subtitles.setdefault('en', []).append({
  189. 'url': caption_url.text,
  190. 'ext': 'ttml' if ext == 'xml' else ext,
  191. })
  192. info = self._search_json_ld(webpage, video_id, default={})
  193. info.update({
  194. 'id': video_id,
  195. 'title': title,
  196. 'formats': formats,
  197. 'subtitles': subtitles,
  198. 'episode_title': title,
  199. 'episode_number': int_or_none(xpath_text(playlist, 'EpisodeNumber')),
  200. 'series': xpath_text(playlist, 'ProgrammeTitle'),
  201. 'duartion': parse_duration(xpath_text(playlist, 'Duration')),
  202. })
  203. return info