svt.py 9.6 KB

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