svt.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. svt:(?P<svt_id>[^/?#&]+)|
  123. https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
  124. )
  125. '''
  126. _TESTS = [{
  127. 'url': 'https://www.svtplay.se/video/26194546/det-har-ar-himlen',
  128. 'md5': '2382036fd6f8c994856c323fe51c426e',
  129. 'info_dict': {
  130. 'id': 'jNwpV9P',
  131. 'ext': 'mp4',
  132. 'title': 'Det h\xe4r \xe4r himlen',
  133. 'timestamp': 1586044800,
  134. 'upload_date': '20200405',
  135. 'duration': 3515,
  136. 'thumbnail': r're:^https?://(?:.*[\.-]jpg|www.svtstatic.se/image/.*)$',
  137. 'age_limit': 0,
  138. 'subtitles': {
  139. 'sv': [{
  140. 'ext': 'vtt',
  141. }]
  142. },
  143. },
  144. 'params': {
  145. 'format': 'bestvideo',
  146. # skip for now due to download test asserts that segment is > 10000 bytes and svt uses
  147. # init segments that are smaller
  148. # AssertionError: Expected test_SVTPlay_jNwpV9P.mp4 to be at least 9.77KiB, but it's only 864.00B
  149. 'skip_download': True,
  150. },
  151. }, {
  152. # geo restricted to Sweden
  153. 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
  154. 'only_matching': True,
  155. }, {
  156. 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
  157. 'only_matching': True,
  158. }, {
  159. 'url': 'https://www.svtplay.se/kanaler/svt1',
  160. 'only_matching': True,
  161. }, {
  162. 'url': 'svt:1376446-003A',
  163. 'only_matching': True,
  164. }, {
  165. 'url': 'svt:14278044',
  166. 'only_matching': True,
  167. }]
  168. def _adjust_title(self, info):
  169. if info['is_live']:
  170. info['title'] = self._live_title(info['title'])
  171. def _extract_by_video_id(self, video_id, webpage=None):
  172. data = self._download_json(
  173. 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
  174. video_id, headers=self.geo_verification_headers())
  175. info_dict = self._extract_video(data, video_id)
  176. if not info_dict.get('title'):
  177. title = dict_get(info_dict, ('episode', 'series'))
  178. if not title and webpage:
  179. title = re.sub(
  180. r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
  181. if not title:
  182. title = video_id
  183. info_dict['title'] = title
  184. self._adjust_title(info_dict)
  185. return info_dict
  186. def _real_extract(self, url):
  187. mobj = re.match(self._VALID_URL, url)
  188. video_id, svt_id = mobj.group('id', 'svt_id')
  189. if svt_id:
  190. return self._extract_by_video_id(svt_id)
  191. webpage = self._download_webpage(url, video_id)
  192. data = self._parse_json(
  193. self._search_regex(
  194. self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
  195. group='json'),
  196. video_id, fatal=False)
  197. thumbnail = self._og_search_thumbnail(webpage)
  198. if data:
  199. video_info = try_get(
  200. data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
  201. dict)
  202. if video_info:
  203. info_dict = self._extract_video(video_info, video_id)
  204. info_dict.update({
  205. 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
  206. 'thumbnail': thumbnail,
  207. })
  208. self._adjust_title(info_dict)
  209. return info_dict
  210. svt_id = try_get(
  211. data, lambda x: x['statistics']['dataLake']['content']['id'],
  212. compat_str)
  213. if not svt_id:
  214. svt_id = self._search_regex(
  215. (r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
  216. r'["\']videoSvtId["\']\s*:\s*["\']([\da-zA-Z-]+)',
  217. r'"content"\s*:\s*{.*?"id"\s*:\s*"([\da-zA-Z-]+)"',
  218. r'["\']svtId["\']\s*:\s*["\']([\da-zA-Z-]+)'),
  219. webpage, 'video id')
  220. info_dict = self._extract_by_video_id(svt_id, webpage)
  221. info_dict['thumbnail'] = thumbnail
  222. return info_dict
  223. class SVTSeriesIE(SVTPlayBaseIE):
  224. _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
  225. _TESTS = [{
  226. 'url': 'https://www.svtplay.se/rederiet',
  227. 'info_dict': {
  228. 'id': '14445680',
  229. 'title': 'Rederiet',
  230. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  231. },
  232. 'playlist_mincount': 318,
  233. }, {
  234. 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
  235. 'info_dict': {
  236. 'id': 'season-2-14445680',
  237. 'title': 'Rederiet - Säsong 2',
  238. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  239. },
  240. 'playlist_mincount': 12,
  241. }]
  242. @classmethod
  243. def suitable(cls, url):
  244. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
  245. def _real_extract(self, url):
  246. series_slug, season_id = re.match(self._VALID_URL, url).groups()
  247. series = self._download_json(
  248. 'https://api.svt.se/contento/graphql', series_slug,
  249. 'Downloading series page', query={
  250. 'query': '''{
  251. listablesBySlug(slugs: ["%s"]) {
  252. associatedContent(include: [productionPeriod, season]) {
  253. items {
  254. item {
  255. ... on Episode {
  256. videoSvtId
  257. }
  258. }
  259. }
  260. id
  261. name
  262. }
  263. id
  264. longDescription
  265. name
  266. shortDescription
  267. }
  268. }''' % series_slug,
  269. })['data']['listablesBySlug'][0]
  270. season_name = None
  271. entries = []
  272. for season in series['associatedContent']:
  273. if not isinstance(season, dict):
  274. continue
  275. if season_id:
  276. if season.get('id') != season_id:
  277. continue
  278. season_name = season.get('name')
  279. items = season.get('items')
  280. if not isinstance(items, list):
  281. continue
  282. for item in items:
  283. video = item.get('item') or {}
  284. content_id = video.get('videoSvtId')
  285. if not content_id or not isinstance(content_id, compat_str):
  286. continue
  287. entries.append(self.url_result(
  288. 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
  289. title = series.get('name')
  290. season_name = season_name or season_id
  291. if title and season_name:
  292. title = '%s - %s' % (title, season_name)
  293. elif season_id:
  294. title = season_id
  295. return self.playlist_result(
  296. entries, season_id or series.get('id'), title,
  297. dict_get(series, ('longDescription', 'shortDescription')))
  298. class SVTPageIE(InfoExtractor):
  299. _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
  300. _TESTS = [{
  301. 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
  302. 'info_dict': {
  303. 'id': '25298267',
  304. 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
  305. },
  306. 'playlist_count': 4,
  307. }, {
  308. 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
  309. 'info_dict': {
  310. 'id': '24243746',
  311. 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
  312. },
  313. 'playlist_count': 2,
  314. }, {
  315. # only programTitle
  316. 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
  317. 'info_dict': {
  318. 'id': '8439V2K',
  319. 'ext': 'mp4',
  320. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  321. 'duration': 27,
  322. 'age_limit': 0,
  323. },
  324. }, {
  325. 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
  326. 'only_matching': True,
  327. }, {
  328. 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
  329. 'only_matching': True,
  330. }]
  331. @classmethod
  332. def suitable(cls, url):
  333. return False if SVTIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
  334. def _real_extract(self, url):
  335. path, display_id = re.match(self._VALID_URL, url).groups()
  336. article = self._download_json(
  337. 'https://api.svt.se/nss-api/page/' + path, display_id,
  338. query={'q': 'articles'})['articles']['content'][0]
  339. entries = []
  340. def _process_content(content):
  341. if content.get('_type') in ('VIDEOCLIP', 'VIDEOEPISODE'):
  342. video_id = compat_str(content['image']['svtId'])
  343. entries.append(self.url_result(
  344. 'svt:' + video_id, SVTPlayIE.ie_key(), video_id))
  345. for media in article.get('media', []):
  346. _process_content(media)
  347. for obj in article.get('structuredBody', []):
  348. _process_content(obj.get('content') or {})
  349. return self.playlist_result(
  350. entries, str_or_none(article.get('id')),
  351. strip_or_none(article.get('title')))