svt.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. import json
  2. import re
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. determine_ext,
  6. dict_get,
  7. int_or_none,
  8. traverse_obj,
  9. try_get,
  10. unified_timestamp,
  11. )
  12. class SVTBaseIE(InfoExtractor):
  13. _GEO_COUNTRIES = ['SE']
  14. def _extract_video(self, video_info, video_id):
  15. is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
  16. m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
  17. formats = []
  18. subtitles = {}
  19. for vr in video_info['videoReferences']:
  20. player_type = vr.get('playerType') or vr.get('format')
  21. vurl = vr['url']
  22. ext = determine_ext(vurl)
  23. if ext == 'm3u8':
  24. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  25. vurl, video_id,
  26. ext='mp4', entry_protocol=m3u8_protocol,
  27. m3u8_id=player_type, fatal=False)
  28. formats.extend(fmts)
  29. self._merge_subtitles(subs, target=subtitles)
  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. fmts, subs = self._extract_mpd_formats_and_subtitles(
  36. vurl, video_id, mpd_id=player_type, fatal=False)
  37. formats.extend(fmts)
  38. self._merge_subtitles(subs, target=subtitles)
  39. else:
  40. formats.append({
  41. 'format_id': player_type,
  42. 'url': vurl,
  43. })
  44. rights = try_get(video_info, lambda x: x['rights'], dict) or {}
  45. if not formats and rights.get('geoBlockedSweden'):
  46. self.raise_geo_restricted(
  47. 'This video is only available in Sweden',
  48. countries=self._GEO_COUNTRIES, metadata_available=True)
  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. sub = {
  56. 'url': subtitle_url,
  57. }
  58. if determine_ext(subtitle_url) == 'm3u8':
  59. # XXX: no way of testing, is it ever hit?
  60. sub['ext'] = 'vtt'
  61. subtitles.setdefault(subtitle_lang, []).append(sub)
  62. title = video_info.get('title')
  63. series = video_info.get('programTitle')
  64. season_number = int_or_none(video_info.get('season'))
  65. episode = video_info.get('episodeTitle')
  66. episode_number = int_or_none(video_info.get('episodeNumber'))
  67. timestamp = unified_timestamp(rights.get('validFrom'))
  68. duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
  69. age_limit = None
  70. adult = dict_get(
  71. video_info, ('inappropriateForChildren', 'blockedForChildren'),
  72. skip_false_values=False)
  73. if adult is not None:
  74. age_limit = 18 if adult else 0
  75. return {
  76. 'id': video_id,
  77. 'title': title,
  78. 'formats': formats,
  79. 'subtitles': subtitles,
  80. 'duration': duration,
  81. 'timestamp': timestamp,
  82. 'age_limit': age_limit,
  83. 'series': series,
  84. 'season_number': season_number,
  85. 'episode': episode,
  86. 'episode_number': episode_number,
  87. 'is_live': is_live,
  88. }
  89. class SVTIE(SVTBaseIE):
  90. _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
  91. _EMBED_REGEX = [rf'(?:<iframe src|href)="(?P<url>{_VALID_URL}[^"]*)"']
  92. _TEST = {
  93. 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
  94. 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
  95. 'info_dict': {
  96. 'id': '2900353',
  97. 'ext': 'mp4',
  98. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  99. 'duration': 27,
  100. 'age_limit': 0,
  101. },
  102. }
  103. def _real_extract(self, url):
  104. mobj = self._match_valid_url(url)
  105. widget_id = mobj.group('widget_id')
  106. article_id = mobj.group('id')
  107. info = self._download_json(
  108. f'http://www.svt.se/wd?widgetId={widget_id}&articleId={article_id}&format=json&type=embed&output=json',
  109. article_id)
  110. info_dict = self._extract_video(info['video'], article_id)
  111. info_dict['title'] = info['context']['title']
  112. return info_dict
  113. class SVTPlayBaseIE(SVTBaseIE):
  114. _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
  115. class SVTPlayIE(SVTPlayBaseIE):
  116. IE_DESC = 'SVT Play and Öppet arkiv'
  117. _VALID_URL = r'''(?x)
  118. (?:
  119. (?:
  120. svt:|
  121. https?://(?:www\.)?svt\.se/barnkanalen/barnplay/[^/]+/
  122. )
  123. (?P<svt_id>[^/?#&]+)|
  124. https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
  125. (?:.*?(?:modalId|id)=(?P<modal_id>[\da-zA-Z-]+))?
  126. )
  127. '''
  128. _TESTS = [{
  129. 'url': 'https://www.svtplay.se/video/30479064',
  130. 'md5': '2382036fd6f8c994856c323fe51c426e',
  131. 'info_dict': {
  132. 'id': '8zVbDPA',
  133. 'ext': 'mp4',
  134. 'title': 'Designdrömmar i Stenungsund',
  135. 'timestamp': 1615770000,
  136. 'upload_date': '20210315',
  137. 'duration': 3519,
  138. 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
  139. 'age_limit': 0,
  140. 'subtitles': {
  141. 'sv': [{
  142. 'ext': 'vtt',
  143. }],
  144. },
  145. },
  146. 'params': {
  147. 'skip_download': 'm3u8',
  148. },
  149. 'skip': 'Episode is no longer available',
  150. }, {
  151. 'url': 'https://www.svtplay.se/video/emBxBQj',
  152. 'md5': '2382036fd6f8c994856c323fe51c426e',
  153. 'info_dict': {
  154. 'id': 'eyBd9aj',
  155. 'ext': 'mp4',
  156. 'title': '1. Farlig kryssning',
  157. 'timestamp': 1491019200,
  158. 'upload_date': '20170401',
  159. 'duration': 2566,
  160. 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
  161. 'age_limit': 0,
  162. 'episode': '1. Farlig kryssning',
  163. 'series': 'Rederiet',
  164. 'subtitles': {
  165. 'sv': 'count:3',
  166. },
  167. },
  168. 'params': {
  169. 'skip_download': 'm3u8',
  170. },
  171. }, {
  172. 'url': 'https://www.svtplay.se/video/jz2rYz7/anders-hansen-moter/james-fallon?info=visa',
  173. 'info_dict': {
  174. 'id': 'jvXAGVb',
  175. 'ext': 'mp4',
  176. 'title': 'James Fallon',
  177. 'timestamp': 1673917200,
  178. 'upload_date': '20230117',
  179. 'duration': 1081,
  180. 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
  181. 'age_limit': 0,
  182. 'episode': 'James Fallon',
  183. 'series': 'Anders Hansen möter...',
  184. },
  185. 'params': {
  186. 'skip_download': 'dash',
  187. },
  188. }, {
  189. 'url': 'https://www.svtplay.se/video/30479064/husdrommar/husdrommar-sasong-8-designdrommar-i-stenungsund?modalId=8zVbDPA',
  190. 'only_matching': True,
  191. }, {
  192. 'url': 'https://www.svtplay.se/video/30684086/rapport/rapport-24-apr-18-00-7?id=e72gVpa',
  193. 'only_matching': True,
  194. }, {
  195. # geo restricted to Sweden
  196. 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
  197. 'only_matching': True,
  198. }, {
  199. 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
  200. 'only_matching': True,
  201. }, {
  202. 'url': 'https://www.svtplay.se/kanaler/svt1',
  203. 'only_matching': True,
  204. }, {
  205. 'url': 'svt:1376446-003A',
  206. 'only_matching': True,
  207. }, {
  208. 'url': 'svt:14278044',
  209. 'only_matching': True,
  210. }, {
  211. 'url': 'https://www.svt.se/barnkanalen/barnplay/kar/eWv5MLX/',
  212. 'only_matching': True,
  213. }, {
  214. 'url': 'svt:eWv5MLX',
  215. 'only_matching': True,
  216. }]
  217. def _extract_by_video_id(self, video_id, webpage=None):
  218. data = self._download_json(
  219. f'https://api.svt.se/videoplayer-api/video/{video_id}',
  220. video_id, headers=self.geo_verification_headers())
  221. info_dict = self._extract_video(data, video_id)
  222. if not info_dict.get('title'):
  223. title = dict_get(info_dict, ('episode', 'series'))
  224. if not title and webpage:
  225. title = re.sub(
  226. r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
  227. if not title:
  228. title = video_id
  229. info_dict['title'] = title
  230. return info_dict
  231. def _real_extract(self, url):
  232. mobj = self._match_valid_url(url)
  233. video_id = mobj.group('id')
  234. svt_id = mobj.group('svt_id') or mobj.group('modal_id')
  235. if svt_id:
  236. return self._extract_by_video_id(svt_id)
  237. webpage = self._download_webpage(url, video_id)
  238. data = self._parse_json(
  239. self._search_regex(
  240. self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
  241. group='json'),
  242. video_id, fatal=False)
  243. thumbnail = self._og_search_thumbnail(webpage)
  244. if data:
  245. video_info = try_get(
  246. data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
  247. dict)
  248. if video_info:
  249. info_dict = self._extract_video(video_info, video_id)
  250. info_dict.update({
  251. 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
  252. 'thumbnail': thumbnail,
  253. })
  254. return info_dict
  255. svt_id = try_get(
  256. data, lambda x: x['statistics']['dataLake']['content']['id'],
  257. str)
  258. if not svt_id:
  259. nextjs_data = self._search_nextjs_data(webpage, video_id, fatal=False)
  260. svt_id = traverse_obj(nextjs_data, (
  261. 'props', 'urqlState', ..., 'data', {json.loads}, 'detailsPageByPath',
  262. 'video', 'svtId', {str}), get_all=False)
  263. if not svt_id:
  264. svt_id = self._search_regex(
  265. (r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
  266. r'<[^>]+\bdata-rt=["\']top-area-play-button["\'][^>]+\bhref=["\'][^"\']*video/[\w-]+/[^"\']*\b(?:modalId|id)=([\w-]+)'),
  267. webpage, 'video id')
  268. info_dict = self._extract_by_video_id(svt_id, webpage)
  269. info_dict['thumbnail'] = thumbnail
  270. return info_dict
  271. class SVTSeriesIE(SVTPlayBaseIE):
  272. _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
  273. _TESTS = [{
  274. 'url': 'https://www.svtplay.se/rederiet',
  275. 'info_dict': {
  276. 'id': '14445680',
  277. 'title': 'Rederiet',
  278. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  279. },
  280. 'playlist_mincount': 318,
  281. }, {
  282. 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
  283. 'info_dict': {
  284. 'id': 'season-2-14445680',
  285. 'title': 'Rederiet - Säsong 2',
  286. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  287. },
  288. 'playlist_mincount': 12,
  289. }]
  290. @classmethod
  291. def suitable(cls, url):
  292. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super().suitable(url)
  293. def _real_extract(self, url):
  294. series_slug, season_id = self._match_valid_url(url).groups()
  295. series = self._download_json(
  296. 'https://api.svt.se/contento/graphql', series_slug,
  297. 'Downloading series page', query={
  298. 'query': '''{
  299. listablesBySlug(slugs: ["%s"]) {
  300. associatedContent(include: [productionPeriod, season]) {
  301. items {
  302. item {
  303. ... on Episode {
  304. videoSvtId
  305. }
  306. }
  307. }
  308. id
  309. name
  310. }
  311. id
  312. longDescription
  313. name
  314. shortDescription
  315. }
  316. }''' % series_slug, # noqa: UP031
  317. })['data']['listablesBySlug'][0]
  318. season_name = None
  319. entries = []
  320. for season in series['associatedContent']:
  321. if not isinstance(season, dict):
  322. continue
  323. if season_id:
  324. if season.get('id') != season_id:
  325. continue
  326. season_name = season.get('name')
  327. items = season.get('items')
  328. if not isinstance(items, list):
  329. continue
  330. for item in items:
  331. video = item.get('item') or {}
  332. content_id = video.get('videoSvtId')
  333. if not content_id or not isinstance(content_id, str):
  334. continue
  335. entries.append(self.url_result(
  336. 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
  337. title = series.get('name')
  338. season_name = season_name or season_id
  339. if title and season_name:
  340. title = f'{title} - {season_name}'
  341. elif season_id:
  342. title = season_id
  343. return self.playlist_result(
  344. entries, season_id or series.get('id'), title,
  345. dict_get(series, ('longDescription', 'shortDescription')))
  346. class SVTPageIE(SVTBaseIE):
  347. _VALID_URL = r'https?://(?:www\.)?svt\.se/(?:[^/?#]+/)*(?P<id>[^/?&#]+)'
  348. _TESTS = [{
  349. 'url': 'https://www.svt.se/nyheter/lokalt/skane/viktor-18-forlorade-armar-och-ben-i-sepsis-vill-ateruppta-karaten-och-bli-svetsare',
  350. 'info_dict': {
  351. 'title': 'Viktor, 18, förlorade armar och ben i sepsis – vill återuppta karaten och bli svetsare',
  352. 'id': 'viktor-18-forlorade-armar-och-ben-i-sepsis-vill-ateruppta-karaten-och-bli-svetsare',
  353. },
  354. 'playlist_count': 2,
  355. }, {
  356. 'url': 'https://www.svt.se/nyheter/lokalt/skane/forsvarsmakten-om-trafikkaoset-pa-e22-kunde-inte-varit-dar-snabbare',
  357. 'info_dict': {
  358. 'id': 'jXvk42E',
  359. 'title': 'Försvarsmakten om trafikkaoset på E22: Kunde inte varit där snabbare',
  360. 'ext': 'mp4',
  361. 'duration': 80,
  362. 'age_limit': 0,
  363. 'timestamp': 1704370009,
  364. 'episode': 'Försvarsmakten om trafikkaoset på E22: Kunde inte varit där snabbare',
  365. 'series': 'Lokala Nyheter Skåne',
  366. 'upload_date': '20240104',
  367. },
  368. 'params': {
  369. 'skip_download': True,
  370. },
  371. }, {
  372. 'url': 'https://www.svt.se/nyheter/svtforum/2023-tungt-ar-for-svensk-media',
  373. 'info_dict': {
  374. 'title': '2023 tungt år för svensk media',
  375. 'id': 'ewqAZv4',
  376. 'ext': 'mp4',
  377. 'duration': 3074,
  378. 'age_limit': 0,
  379. 'series': '',
  380. 'timestamp': 1702980479,
  381. 'upload_date': '20231219',
  382. 'episode': 'Mediestudier',
  383. },
  384. 'params': {
  385. 'skip_download': True,
  386. },
  387. }, {
  388. 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
  389. 'info_dict': {
  390. 'id': '25298267',
  391. 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
  392. },
  393. 'playlist_count': 4,
  394. 'skip': 'Video is gone',
  395. }, {
  396. 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
  397. 'info_dict': {
  398. 'id': '24243746',
  399. 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
  400. },
  401. 'playlist_count': 2,
  402. 'skip': 'Video is gone',
  403. }, {
  404. # only programTitle
  405. 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
  406. 'info_dict': {
  407. 'id': '8439V2K',
  408. 'ext': 'mp4',
  409. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  410. 'duration': 27,
  411. 'age_limit': 0,
  412. },
  413. 'skip': 'Video is gone',
  414. }, {
  415. 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
  416. 'only_matching': True,
  417. }, {
  418. 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
  419. 'only_matching': True,
  420. }]
  421. @classmethod
  422. def suitable(cls, url):
  423. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super().suitable(url)
  424. def _real_extract(self, url):
  425. display_id = self._match_id(url)
  426. webpage = self._download_webpage(url, display_id)
  427. title = self._og_search_title(webpage)
  428. urql_state = self._search_json(
  429. r'window\.svt\.nyh\.urqlState\s*=', webpage, 'json data', display_id)
  430. data = traverse_obj(urql_state, (..., 'data', {str}, {json.loads}), get_all=False) or {}
  431. def entries():
  432. for video_id in set(traverse_obj(data, (
  433. 'page', (('topMedia', 'svtId'), ('body', ..., 'video', 'svtId')), {str},
  434. ))):
  435. info = self._extract_video(
  436. self._download_json(f'https://api.svt.se/video/{video_id}', video_id), video_id)
  437. info['title'] = title
  438. yield info
  439. return self.playlist_result(entries(), display_id, title)