svt.py 8.6 KB

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