svt.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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>\w+)'
  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. if data:
  157. video_info = try_get(
  158. data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
  159. dict)
  160. if video_info:
  161. info_dict = self._extract_video(video_info, video_id)
  162. info_dict.update({
  163. 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
  164. 'thumbnail': thumbnail,
  165. })
  166. if info_dict['is_live']:
  167. info_dict['title'] = self._live_title(info_dict['title'])
  168. return info_dict
  169. video_id = self._search_regex(
  170. r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
  171. webpage, 'video id', default=None)
  172. if video_id:
  173. data = self._download_json(
  174. 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
  175. video_id, headers=self.geo_verification_headers())
  176. info_dict = self._extract_video(data, video_id)
  177. if not info_dict.get('title'):
  178. info_dict['title'] = re.sub(
  179. r'\s*\|\s*.+?$', '',
  180. info_dict.get('episode') or self._og_search_title(webpage))
  181. if info_dict['is_live']:
  182. info_dict['title'] = self._live_title(info_dict['title'])
  183. return info_dict
  184. class SVTSeriesIE(SVTPlayBaseIE):
  185. _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)'
  186. _TESTS = [{
  187. 'url': 'https://www.svtplay.se/rederiet',
  188. 'info_dict': {
  189. 'id': 'rederiet',
  190. 'title': 'Rederiet',
  191. 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
  192. },
  193. 'playlist_mincount': 318,
  194. }, {
  195. 'url': 'https://www.svtplay.se/rederiet?tab=sasong2',
  196. 'info_dict': {
  197. 'id': 'rederiet-sasong2',
  198. 'title': 'Rederiet - Säsong 2',
  199. 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
  200. },
  201. 'playlist_count': 12,
  202. }]
  203. @classmethod
  204. def suitable(cls, url):
  205. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
  206. def _real_extract(self, url):
  207. series_id = self._match_id(url)
  208. qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  209. season_slug = qs.get('tab', [None])[0]
  210. if season_slug:
  211. series_id += '-%s' % season_slug
  212. webpage = self._download_webpage(
  213. url, series_id, 'Downloading series page')
  214. root = self._parse_json(
  215. self._search_regex(
  216. self._SVTPLAY_RE, webpage, 'content', group='json'),
  217. series_id)
  218. season_name = None
  219. entries = []
  220. for season in root['relatedVideoContent']['relatedVideosAccordion']:
  221. if not isinstance(season, dict):
  222. continue
  223. if season_slug:
  224. if season.get('slug') != season_slug:
  225. continue
  226. season_name = season.get('name')
  227. videos = season.get('videos')
  228. if not isinstance(videos, list):
  229. continue
  230. for video in videos:
  231. content_url = video.get('contentUrl')
  232. if not content_url or not isinstance(content_url, compat_str):
  233. continue
  234. entries.append(
  235. self.url_result(
  236. urljoin(url, content_url),
  237. ie=SVTPlayIE.ie_key(),
  238. video_title=video.get('title')
  239. ))
  240. metadata = root.get('metaData')
  241. if not isinstance(metadata, dict):
  242. metadata = {}
  243. title = metadata.get('title')
  244. season_name = season_name or season_slug
  245. if title and season_name:
  246. title = '%s - %s' % (title, season_name)
  247. elif season_slug:
  248. title = season_slug
  249. return self.playlist_result(
  250. entries, series_id, title, metadata.get('description'))