svt.py 15 KB

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