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.

294 lines
10 KiB

8 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_parse_qs,
  7. compat_urllib_parse_urlparse,
  8. )
  9. from ..utils import (
  10. determine_ext,
  11. dict_get,
  12. int_or_none,
  13. try_get,
  14. urljoin,
  15. compat_str,
  16. )
  17. class SVTBaseIE(InfoExtractor):
  18. _GEO_COUNTRIES = ['SE']
  19. def _extract_video(self, video_info, video_id):
  20. is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
  21. m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
  22. formats = []
  23. for vr in video_info['videoReferences']:
  24. player_type = vr.get('playerType') or vr.get('format')
  25. vurl = vr['url']
  26. ext = determine_ext(vurl)
  27. if ext == 'm3u8':
  28. formats.extend(self._extract_m3u8_formats(
  29. vurl, video_id,
  30. ext='mp4', entry_protocol=m3u8_protocol,
  31. m3u8_id=player_type, fatal=False))
  32. elif ext == 'f4m':
  33. formats.extend(self._extract_f4m_formats(
  34. vurl + '?hdcore=3.3.0', video_id,
  35. f4m_id=player_type, fatal=False))
  36. elif ext == 'mpd':
  37. if player_type == 'dashhbbtv':
  38. formats.extend(self._extract_mpd_formats(
  39. vurl, video_id, mpd_id=player_type, fatal=False))
  40. else:
  41. formats.append({
  42. 'format_id': player_type,
  43. 'url': vurl,
  44. })
  45. if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
  46. self.raise_geo_restricted(
  47. 'This video is only available in Sweden',
  48. countries=self._GEO_COUNTRIES)
  49. self._sort_formats(formats)
  50. subtitles = {}
  51. subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
  52. if isinstance(subtitle_references, list):
  53. for sr in subtitle_references:
  54. subtitle_url = sr.get('url')
  55. subtitle_lang = sr.get('language', 'sv')
  56. if subtitle_url:
  57. if determine_ext(subtitle_url) == 'm3u8':
  58. # TODO(yan12125): handle WebVTT in m3u8 manifests
  59. continue
  60. subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
  61. title = video_info.get('title')
  62. series = video_info.get('programTitle')
  63. season_number = int_or_none(video_info.get('season'))
  64. episode = video_info.get('episodeTitle')
  65. episode_number = int_or_none(video_info.get('episodeNumber'))
  66. duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
  67. age_limit = None
  68. adult = dict_get(
  69. video_info, ('inappropriateForChildren', 'blockedForChildren'),
  70. skip_false_values=False)
  71. if adult is not None:
  72. age_limit = 18 if adult else 0
  73. return {
  74. 'id': video_id,
  75. 'title': title,
  76. 'formats': formats,
  77. 'subtitles': subtitles,
  78. 'duration': duration,
  79. 'age_limit': age_limit,
  80. 'series': series,
  81. 'season_number': season_number,
  82. 'episode': episode,
  83. 'episode_number': episode_number,
  84. 'is_live': is_live,
  85. }
  86. class SVTIE(SVTBaseIE):
  87. _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
  88. _TEST = {
  89. 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
  90. 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
  91. 'info_dict': {
  92. 'id': '2900353',
  93. 'ext': 'mp4',
  94. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  95. 'duration': 27,
  96. 'age_limit': 0,
  97. },
  98. }
  99. @staticmethod
  100. def _extract_url(webpage):
  101. mobj = re.search(
  102. r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
  103. if mobj:
  104. return mobj.group('url')
  105. def _real_extract(self, url):
  106. mobj = re.match(self._VALID_URL, url)
  107. widget_id = mobj.group('widget_id')
  108. article_id = mobj.group('id')
  109. info = self._download_json(
  110. 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
  111. article_id)
  112. info_dict = self._extract_video(info['video'], article_id)
  113. info_dict['title'] = info['context']['title']
  114. return info_dict
  115. class SVTPlayBaseIE(SVTBaseIE):
  116. _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
  117. class SVTPlayIE(SVTPlayBaseIE):
  118. IE_DESC = 'SVT Play and Öppet arkiv'
  119. _VALID_URL = r'https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)'
  120. _TESTS = [{
  121. 'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
  122. 'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
  123. 'info_dict': {
  124. 'id': '5996901',
  125. 'ext': 'mp4',
  126. 'title': 'Flygplan till Haile Selassie',
  127. 'duration': 3527,
  128. 'thumbnail': r're:^https?://.*[\.-]jpg$',
  129. 'age_limit': 0,
  130. 'subtitles': {
  131. 'sv': [{
  132. 'ext': 'wsrt',
  133. }]
  134. },
  135. },
  136. }, {
  137. # geo restricted to Sweden
  138. 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
  139. 'only_matching': True,
  140. }, {
  141. 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
  142. 'only_matching': True,
  143. }, {
  144. 'url': 'https://www.svtplay.se/kanaler/svt1',
  145. 'only_matching': True,
  146. }]
  147. def _real_extract(self, url):
  148. video_id = self._match_id(url)
  149. webpage = self._download_webpage(url, video_id)
  150. data = self._parse_json(
  151. self._search_regex(
  152. self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
  153. group='json'),
  154. video_id, fatal=False)
  155. thumbnail = self._og_search_thumbnail(webpage)
  156. def adjust_title(info):
  157. if info['is_live']:
  158. info['title'] = self._live_title(info['title'])
  159. if data:
  160. video_info = try_get(
  161. data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
  162. dict)
  163. if video_info:
  164. info_dict = self._extract_video(video_info, video_id)
  165. info_dict.update({
  166. 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
  167. 'thumbnail': thumbnail,
  168. })
  169. adjust_title(info_dict)
  170. return info_dict
  171. video_id = self._search_regex(
  172. r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
  173. webpage, 'video id', default=None)
  174. if video_id:
  175. data = self._download_json(
  176. 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
  177. video_id, headers=self.geo_verification_headers())
  178. info_dict = self._extract_video(data, video_id)
  179. if not info_dict.get('title'):
  180. info_dict['title'] = re.sub(
  181. r'\s*\|\s*.+?$', '',
  182. info_dict.get('episode') or self._og_search_title(webpage))
  183. adjust_title(info_dict)
  184. return info_dict
  185. class SVTSeriesIE(SVTPlayBaseIE):
  186. _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)'
  187. _TESTS = [{
  188. 'url': 'https://www.svtplay.se/rederiet',
  189. 'info_dict': {
  190. 'id': 'rederiet',
  191. 'title': 'Rederiet',
  192. 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
  193. },
  194. 'playlist_mincount': 318,
  195. }, {
  196. 'url': 'https://www.svtplay.se/rederiet?tab=sasong2',
  197. 'info_dict': {
  198. 'id': 'rederiet-sasong2',
  199. 'title': 'Rederiet - Säsong 2',
  200. 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
  201. },
  202. 'playlist_count': 12,
  203. }]
  204. @classmethod
  205. def suitable(cls, url):
  206. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
  207. def _real_extract(self, url):
  208. series_id = self._match_id(url)
  209. qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  210. season_slug = qs.get('tab', [None])[0]
  211. if season_slug:
  212. series_id += '-%s' % season_slug
  213. webpage = self._download_webpage(
  214. url, series_id, 'Downloading series page')
  215. root = self._parse_json(
  216. self._search_regex(
  217. self._SVTPLAY_RE, webpage, 'content', group='json'),
  218. series_id)
  219. season_name = None
  220. entries = []
  221. for season in root['relatedVideoContent']['relatedVideosAccordion']:
  222. if not isinstance(season, dict):
  223. continue
  224. if season_slug:
  225. if season.get('slug') != season_slug:
  226. continue
  227. season_name = season.get('name')
  228. videos = season.get('videos')
  229. if not isinstance(videos, list):
  230. continue
  231. for video in videos:
  232. content_url = video.get('contentUrl')
  233. if not content_url or not isinstance(content_url, compat_str):
  234. continue
  235. entries.append(
  236. self.url_result(
  237. urljoin(url, content_url),
  238. ie=SVTPlayIE.ie_key(),
  239. video_title=video.get('title')
  240. ))
  241. metadata = root.get('metaData')
  242. if not isinstance(metadata, dict):
  243. metadata = {}
  244. title = metadata.get('title')
  245. season_name = season_name or season_slug
  246. if title and season_name:
  247. title = '%s - %s' % (title, season_name)
  248. elif season_slug:
  249. title = season_slug
  250. return self.playlist_result(
  251. entries, series_id, title, metadata.get('description'))