svt.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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'"content"\s*:\s*{.*?"id"\s*:\s*"([\da-zA-Z-]+)"',
  228. r'["\']svtId["\']\s*:\s*["\']([\da-zA-Z-]+)'),
  229. webpage, 'video id')
  230. info_dict = self._extract_by_video_id(svt_id, webpage)
  231. info_dict['thumbnail'] = thumbnail
  232. return info_dict
  233. class SVTSeriesIE(SVTPlayBaseIE):
  234. _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
  235. _TESTS = [{
  236. 'url': 'https://www.svtplay.se/rederiet',
  237. 'info_dict': {
  238. 'id': '14445680',
  239. 'title': 'Rederiet',
  240. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  241. },
  242. 'playlist_mincount': 318,
  243. }, {
  244. 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
  245. 'info_dict': {
  246. 'id': 'season-2-14445680',
  247. 'title': 'Rederiet - Säsong 2',
  248. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  249. },
  250. 'playlist_mincount': 12,
  251. }]
  252. @classmethod
  253. def suitable(cls, url):
  254. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
  255. def _real_extract(self, url):
  256. series_slug, season_id = re.match(self._VALID_URL, url).groups()
  257. series = self._download_json(
  258. 'https://api.svt.se/contento/graphql', series_slug,
  259. 'Downloading series page', query={
  260. 'query': '''{
  261. listablesBySlug(slugs: ["%s"]) {
  262. associatedContent(include: [productionPeriod, season]) {
  263. items {
  264. item {
  265. ... on Episode {
  266. videoSvtId
  267. }
  268. }
  269. }
  270. id
  271. name
  272. }
  273. id
  274. longDescription
  275. name
  276. shortDescription
  277. }
  278. }''' % series_slug,
  279. })['data']['listablesBySlug'][0]
  280. season_name = None
  281. entries = []
  282. for season in series['associatedContent']:
  283. if not isinstance(season, dict):
  284. continue
  285. if season_id:
  286. if season.get('id') != season_id:
  287. continue
  288. season_name = season.get('name')
  289. items = season.get('items')
  290. if not isinstance(items, list):
  291. continue
  292. for item in items:
  293. video = item.get('item') or {}
  294. content_id = video.get('videoSvtId')
  295. if not content_id or not isinstance(content_id, compat_str):
  296. continue
  297. entries.append(self.url_result(
  298. 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
  299. title = series.get('name')
  300. season_name = season_name or season_id
  301. if title and season_name:
  302. title = '%s - %s' % (title, season_name)
  303. elif season_id:
  304. title = season_id
  305. return self.playlist_result(
  306. entries, season_id or series.get('id'), title,
  307. dict_get(series, ('longDescription', 'shortDescription')))
  308. class SVTPageIE(InfoExtractor):
  309. _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
  310. _TESTS = [{
  311. 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
  312. 'info_dict': {
  313. 'id': '25298267',
  314. 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
  315. },
  316. 'playlist_count': 4,
  317. }, {
  318. 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
  319. 'info_dict': {
  320. 'id': '24243746',
  321. 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
  322. },
  323. 'playlist_count': 2,
  324. }, {
  325. # only programTitle
  326. 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
  327. 'info_dict': {
  328. 'id': '8439V2K',
  329. 'ext': 'mp4',
  330. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  331. 'duration': 27,
  332. 'age_limit': 0,
  333. },
  334. }, {
  335. 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
  336. 'only_matching': True,
  337. }, {
  338. 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
  339. 'only_matching': True,
  340. }]
  341. @classmethod
  342. def suitable(cls, url):
  343. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
  344. def _real_extract(self, url):
  345. path, display_id = re.match(self._VALID_URL, url).groups()
  346. article = self._download_json(
  347. 'https://api.svt.se/nss-api/page/' + path, display_id,
  348. query={'q': 'articles'})['articles']['content'][0]
  349. entries = []
  350. def _process_content(content):
  351. if content.get('_type') in ('VIDEOCLIP', 'VIDEOEPISODE'):
  352. video_id = compat_str(content['image']['svtId'])
  353. entries.append(self.url_result(
  354. 'svt:' + video_id, SVTPlayIE.ie_key(), video_id))
  355. for media in article.get('media', []):
  356. _process_content(media)
  357. for obj in article.get('structuredBody', []):
  358. _process_content(obj.get('content') or {})
  359. return self.playlist_result(
  360. entries, str_or_none(article.get('id')),
  361. strip_or_none(article.get('title')))