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.

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