svt.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_str
  6. from ..utils import (
  7. determine_ext,
  8. dict_get,
  9. int_or_none,
  10. unified_timestamp,
  11. str_or_none,
  12. strip_or_none,
  13. try_get,
  14. )
  15. class SVTBaseIE(InfoExtractor):
  16. _GEO_COUNTRIES = ['SE']
  17. def _extract_video(self, video_info, video_id):
  18. is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
  19. m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
  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_protocol,
  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. rights = try_get(video_info, lambda x: x['rights'], dict) or {}
  44. if not formats and rights.get('geoBlockedSweden'):
  45. self.raise_geo_restricted(
  46. 'This video is only available in Sweden',
  47. countries=self._GEO_COUNTRIES)
  48. self._sort_formats(formats)
  49. subtitles = {}
  50. subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
  51. if isinstance(subtitle_references, list):
  52. for sr in subtitle_references:
  53. subtitle_url = sr.get('url')
  54. subtitle_lang = sr.get('language', 'sv')
  55. if subtitle_url:
  56. if determine_ext(subtitle_url) == 'm3u8':
  57. # TODO(yan12125): handle WebVTT in m3u8 manifests
  58. continue
  59. subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
  60. title = video_info.get('title')
  61. series = video_info.get('programTitle')
  62. season_number = int_or_none(video_info.get('season'))
  63. episode = video_info.get('episodeTitle')
  64. episode_number = int_or_none(video_info.get('episodeNumber'))
  65. timestamp = unified_timestamp(rights.get('validFrom'))
  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. 'timestamp': timestamp,
  80. 'age_limit': age_limit,
  81. 'series': series,
  82. 'season_number': season_number,
  83. 'episode': episode,
  84. 'episode_number': episode_number,
  85. 'is_live': is_live,
  86. }
  87. class SVTIE(SVTBaseIE):
  88. _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
  89. _TEST = {
  90. 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
  91. 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
  92. 'info_dict': {
  93. 'id': '2900353',
  94. 'ext': 'mp4',
  95. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  96. 'duration': 27,
  97. 'age_limit': 0,
  98. },
  99. }
  100. @staticmethod
  101. def _extract_url(webpage):
  102. mobj = re.search(
  103. r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
  104. if mobj:
  105. return mobj.group('url')
  106. def _real_extract(self, url):
  107. mobj = re.match(self._VALID_URL, url)
  108. widget_id = mobj.group('widget_id')
  109. article_id = mobj.group('id')
  110. info = self._download_json(
  111. 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
  112. article_id)
  113. info_dict = self._extract_video(info['video'], article_id)
  114. info_dict['title'] = info['context']['title']
  115. return info_dict
  116. class SVTPlayBaseIE(SVTBaseIE):
  117. _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
  118. class SVTPlayIE(SVTPlayBaseIE):
  119. IE_DESC = 'SVT Play and Öppet arkiv'
  120. _VALID_URL = r'''(?x)
  121. (?:
  122. (?:
  123. svt:|
  124. https?://(?:www\.)?svt\.se/barnkanalen/barnplay/[^/]+/
  125. )
  126. (?P<svt_id>[^/?#&]+)|
  127. https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
  128. )
  129. '''
  130. _TESTS = [{
  131. 'url': 'https://www.svtplay.se/video/26194546/det-har-ar-himlen',
  132. 'md5': '2382036fd6f8c994856c323fe51c426e',
  133. 'info_dict': {
  134. 'id': 'jNwpV9P',
  135. 'ext': 'mp4',
  136. 'title': 'Det här är himlen',
  137. 'timestamp': 1586044800,
  138. 'upload_date': '20200405',
  139. 'duration': 3515,
  140. 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
  141. 'age_limit': 0,
  142. 'subtitles': {
  143. 'sv': [{
  144. 'ext': 'vtt',
  145. }]
  146. },
  147. },
  148. 'params': {
  149. 'format': 'bestvideo',
  150. # skip for now due to download test asserts that segment is > 10000 bytes and svt uses
  151. # init segments that are smaller
  152. # AssertionError: Expected test_SVTPlay_jNwpV9P.mp4 to be at least 9.77KiB, but it's only 864.00B
  153. 'skip_download': True,
  154. },
  155. }, {
  156. # geo restricted to Sweden
  157. 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
  158. 'only_matching': True,
  159. }, {
  160. 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
  161. 'only_matching': True,
  162. }, {
  163. 'url': 'https://www.svtplay.se/kanaler/svt1',
  164. 'only_matching': True,
  165. }, {
  166. 'url': 'svt:1376446-003A',
  167. 'only_matching': True,
  168. }, {
  169. 'url': 'svt:14278044',
  170. 'only_matching': True,
  171. }, {
  172. 'url': 'https://www.svt.se/barnkanalen/barnplay/kar/eWv5MLX/',
  173. 'only_matching': True,
  174. }, {
  175. 'url': 'svt:eWv5MLX',
  176. 'only_matching': True,
  177. }]
  178. def _adjust_title(self, info):
  179. if info['is_live']:
  180. info['title'] = self._live_title(info['title'])
  181. def _extract_by_video_id(self, video_id, webpage=None):
  182. data = self._download_json(
  183. 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
  184. video_id, headers=self.geo_verification_headers())
  185. info_dict = self._extract_video(data, video_id)
  186. if not info_dict.get('title'):
  187. title = dict_get(info_dict, ('episode', 'series'))
  188. if not title and webpage:
  189. title = re.sub(
  190. r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
  191. if not title:
  192. title = video_id
  193. info_dict['title'] = title
  194. self._adjust_title(info_dict)
  195. return info_dict
  196. def _real_extract(self, url):
  197. mobj = re.match(self._VALID_URL, url)
  198. video_id, svt_id = mobj.group('id', 'svt_id')
  199. if svt_id:
  200. return self._extract_by_video_id(svt_id)
  201. webpage = self._download_webpage(url, video_id)
  202. data = self._parse_json(
  203. self._search_regex(
  204. self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
  205. group='json'),
  206. video_id, fatal=False)
  207. thumbnail = self._og_search_thumbnail(webpage)
  208. if data:
  209. video_info = try_get(
  210. data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
  211. dict)
  212. if video_info:
  213. info_dict = self._extract_video(video_info, video_id)
  214. info_dict.update({
  215. 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
  216. 'thumbnail': thumbnail,
  217. })
  218. self._adjust_title(info_dict)
  219. return info_dict
  220. svt_id = try_get(
  221. data, lambda x: x['statistics']['dataLake']['content']['id'],
  222. compat_str)
  223. if not svt_id:
  224. svt_id = self._search_regex(
  225. (r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
  226. r'["\']videoSvtId["\']\s*:\s*["\']([\da-zA-Z-]+)',
  227. r'["\']videoSvtId\\?["\']\s*:\s*\\?["\']([\da-zA-Z-]+)',
  228. r'"content"\s*:\s*{.*?"id"\s*:\s*"([\da-zA-Z-]+)"',
  229. r'["\']svtId["\']\s*:\s*["\']([\da-zA-Z-]+)',
  230. r'["\']svtId\\?["\']\s*:\s*\\?["\']([\da-zA-Z-]+)'),
  231. webpage, 'video id')
  232. info_dict = self._extract_by_video_id(svt_id, webpage)
  233. info_dict['thumbnail'] = thumbnail
  234. return info_dict
  235. class SVTSeriesIE(SVTPlayBaseIE):
  236. _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
  237. _TESTS = [{
  238. 'url': 'https://www.svtplay.se/rederiet',
  239. 'info_dict': {
  240. 'id': '14445680',
  241. 'title': 'Rederiet',
  242. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  243. },
  244. 'playlist_mincount': 318,
  245. }, {
  246. 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
  247. 'info_dict': {
  248. 'id': 'season-2-14445680',
  249. 'title': 'Rederiet - Säsong 2',
  250. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  251. },
  252. 'playlist_mincount': 12,
  253. }]
  254. @classmethod
  255. def suitable(cls, url):
  256. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
  257. def _real_extract(self, url):
  258. series_slug, season_id = re.match(self._VALID_URL, url).groups()
  259. series = self._download_json(
  260. 'https://api.svt.se/contento/graphql', series_slug,
  261. 'Downloading series page', query={
  262. 'query': '''{
  263. listablesBySlug(slugs: ["%s"]) {
  264. associatedContent(include: [productionPeriod, season]) {
  265. items {
  266. item {
  267. ... on Episode {
  268. videoSvtId
  269. }
  270. }
  271. }
  272. id
  273. name
  274. }
  275. id
  276. longDescription
  277. name
  278. shortDescription
  279. }
  280. }''' % series_slug,
  281. })['data']['listablesBySlug'][0]
  282. season_name = None
  283. entries = []
  284. for season in series['associatedContent']:
  285. if not isinstance(season, dict):
  286. continue
  287. if season_id:
  288. if season.get('id') != season_id:
  289. continue
  290. season_name = season.get('name')
  291. items = season.get('items')
  292. if not isinstance(items, list):
  293. continue
  294. for item in items:
  295. video = item.get('item') or {}
  296. content_id = video.get('videoSvtId')
  297. if not content_id or not isinstance(content_id, compat_str):
  298. continue
  299. entries.append(self.url_result(
  300. 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
  301. title = series.get('name')
  302. season_name = season_name or season_id
  303. if title and season_name:
  304. title = '%s - %s' % (title, season_name)
  305. elif season_id:
  306. title = season_id
  307. return self.playlist_result(
  308. entries, season_id or series.get('id'), title,
  309. dict_get(series, ('longDescription', 'shortDescription')))
  310. class SVTPageIE(InfoExtractor):
  311. _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
  312. _TESTS = [{
  313. 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
  314. 'info_dict': {
  315. 'id': '25298267',
  316. 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
  317. },
  318. 'playlist_count': 4,
  319. }, {
  320. 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
  321. 'info_dict': {
  322. 'id': '24243746',
  323. 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
  324. },
  325. 'playlist_count': 2,
  326. }, {
  327. # only programTitle
  328. 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
  329. 'info_dict': {
  330. 'id': '8439V2K',
  331. 'ext': 'mp4',
  332. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  333. 'duration': 27,
  334. 'age_limit': 0,
  335. },
  336. }, {
  337. 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
  338. 'only_matching': True,
  339. }, {
  340. 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
  341. 'only_matching': True,
  342. }]
  343. @classmethod
  344. def suitable(cls, url):
  345. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
  346. def _real_extract(self, url):
  347. path, display_id = re.match(self._VALID_URL, url).groups()
  348. article = self._download_json(
  349. 'https://api.svt.se/nss-api/page/' + path, display_id,
  350. query={'q': 'articles'})['articles']['content'][0]
  351. entries = []
  352. def _process_content(content):
  353. if content.get('_type') in ('VIDEOCLIP', 'VIDEOEPISODE'):
  354. video_id = compat_str(content['image']['svtId'])
  355. entries.append(self.url_result(
  356. 'svt:' + video_id, SVTPlayIE.ie_key(), video_id))
  357. for media in article.get('media', []):
  358. _process_content(media)
  359. for obj in article.get('structuredBody', []):
  360. _process_content(obj.get('content') or {})
  361. return self.playlist_result(
  362. entries, str_or_none(article.get('id')),
  363. strip_or_none(article.get('title')))