svt.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. str_or_none,
  11. strip_or_none,
  12. try_get,
  13. )
  14. class SVTBaseIE(InfoExtractor):
  15. _GEO_COUNTRIES = ['SE']
  16. def _extract_video(self, video_info, video_id):
  17. is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
  18. m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
  19. formats = []
  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. formats.extend(self._extract_m3u8_formats(
  26. vurl, video_id,
  27. ext='mp4', entry_protocol=m3u8_protocol,
  28. m3u8_id=player_type, fatal=False))
  29. elif ext == 'f4m':
  30. formats.extend(self._extract_f4m_formats(
  31. vurl + '?hdcore=3.3.0', video_id,
  32. f4m_id=player_type, fatal=False))
  33. elif ext == 'mpd':
  34. if player_type == 'dashhbbtv':
  35. formats.extend(self._extract_mpd_formats(
  36. vurl, video_id, mpd_id=player_type, fatal=False))
  37. else:
  38. formats.append({
  39. 'format_id': player_type,
  40. 'url': vurl,
  41. })
  42. if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
  43. self.raise_geo_restricted(
  44. 'This video is only available in Sweden',
  45. countries=self._GEO_COUNTRIES)
  46. self._sort_formats(formats)
  47. subtitles = {}
  48. subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
  49. if isinstance(subtitle_references, list):
  50. for sr in subtitle_references:
  51. subtitle_url = sr.get('url')
  52. subtitle_lang = sr.get('language', 'sv')
  53. if subtitle_url:
  54. if determine_ext(subtitle_url) == 'm3u8':
  55. # TODO(yan12125): handle WebVTT in m3u8 manifests
  56. continue
  57. subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
  58. title = video_info.get('title')
  59. series = video_info.get('programTitle')
  60. season_number = int_or_none(video_info.get('season'))
  61. episode = video_info.get('episodeTitle')
  62. episode_number = int_or_none(video_info.get('episodeNumber'))
  63. duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
  64. age_limit = None
  65. adult = dict_get(
  66. video_info, ('inappropriateForChildren', 'blockedForChildren'),
  67. skip_false_values=False)
  68. if adult is not None:
  69. age_limit = 18 if adult else 0
  70. return {
  71. 'id': video_id,
  72. 'title': title,
  73. 'formats': formats,
  74. 'subtitles': subtitles,
  75. 'duration': duration,
  76. 'age_limit': age_limit,
  77. 'series': series,
  78. 'season_number': season_number,
  79. 'episode': episode,
  80. 'episode_number': episode_number,
  81. 'is_live': is_live,
  82. }
  83. class SVTIE(SVTBaseIE):
  84. _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
  85. _TEST = {
  86. 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
  87. 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
  88. 'info_dict': {
  89. 'id': '2900353',
  90. 'ext': 'mp4',
  91. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  92. 'duration': 27,
  93. 'age_limit': 0,
  94. },
  95. }
  96. @staticmethod
  97. def _extract_url(webpage):
  98. mobj = re.search(
  99. r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
  100. if mobj:
  101. return mobj.group('url')
  102. def _real_extract(self, url):
  103. mobj = re.match(self._VALID_URL, url)
  104. widget_id = mobj.group('widget_id')
  105. article_id = mobj.group('id')
  106. info = self._download_json(
  107. 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
  108. article_id)
  109. info_dict = self._extract_video(info['video'], article_id)
  110. info_dict['title'] = info['context']['title']
  111. return info_dict
  112. class SVTPlayBaseIE(SVTBaseIE):
  113. _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
  114. class SVTPlayIE(SVTPlayBaseIE):
  115. IE_DESC = 'SVT Play and Öppet arkiv'
  116. _VALID_URL = r'''(?x)
  117. (?:
  118. svt:(?P<svt_id>[^/?#&]+)|
  119. https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
  120. )
  121. '''
  122. _TESTS = [{
  123. 'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
  124. 'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
  125. 'info_dict': {
  126. 'id': '5996901',
  127. 'ext': 'mp4',
  128. 'title': 'Flygplan till Haile Selassie',
  129. 'duration': 3527,
  130. 'thumbnail': r're:^https?://.*[\.-]jpg$',
  131. 'age_limit': 0,
  132. 'subtitles': {
  133. 'sv': [{
  134. 'ext': 'wsrt',
  135. }]
  136. },
  137. },
  138. }, {
  139. # geo restricted to Sweden
  140. 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
  141. 'only_matching': True,
  142. }, {
  143. 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
  144. 'only_matching': True,
  145. }, {
  146. 'url': 'https://www.svtplay.se/kanaler/svt1',
  147. 'only_matching': True,
  148. }, {
  149. 'url': 'svt:1376446-003A',
  150. 'only_matching': True,
  151. }, {
  152. 'url': 'svt:14278044',
  153. 'only_matching': True,
  154. }]
  155. def _adjust_title(self, info):
  156. if info['is_live']:
  157. info['title'] = self._live_title(info['title'])
  158. def _extract_by_video_id(self, video_id, webpage=None):
  159. data = self._download_json(
  160. 'https://api.svt.se/videoplayer-api/video/%s' % video_id,
  161. video_id, headers=self.geo_verification_headers())
  162. info_dict = self._extract_video(data, video_id)
  163. if not info_dict.get('title'):
  164. title = dict_get(info_dict, ('episode', 'series'))
  165. if not title and webpage:
  166. title = re.sub(
  167. r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
  168. if not title:
  169. title = video_id
  170. info_dict['title'] = title
  171. self._adjust_title(info_dict)
  172. return info_dict
  173. def _real_extract(self, url):
  174. mobj = re.match(self._VALID_URL, url)
  175. video_id, svt_id = mobj.group('id', 'svt_id')
  176. if svt_id:
  177. return self._extract_by_video_id(svt_id)
  178. webpage = self._download_webpage(url, video_id)
  179. data = self._parse_json(
  180. self._search_regex(
  181. self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
  182. group='json'),
  183. video_id, fatal=False)
  184. thumbnail = self._og_search_thumbnail(webpage)
  185. if data:
  186. video_info = try_get(
  187. data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
  188. dict)
  189. if video_info:
  190. info_dict = self._extract_video(video_info, video_id)
  191. info_dict.update({
  192. 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
  193. 'thumbnail': thumbnail,
  194. })
  195. self._adjust_title(info_dict)
  196. return info_dict
  197. svt_id = try_get(
  198. data, lambda x: x['statistics']['dataLake']['content']['id'],
  199. compat_str)
  200. if not svt_id:
  201. svt_id = self._search_regex(
  202. (r'<video[^>]+data-video-id=["\']([\da-zA-Z-]+)',
  203. r'"content"\s*:\s*{.*?"id"\s*:\s*"([\da-zA-Z-]+)"'),
  204. webpage, 'video id')
  205. return self._extract_by_video_id(svt_id, webpage)
  206. class SVTSeriesIE(SVTPlayBaseIE):
  207. _VALID_URL = r'https?://(?:www\.)?svtplay\.se/(?P<id>[^/?&#]+)(?:.+?\btab=(?P<season_slug>[^&#]+))?'
  208. _TESTS = [{
  209. 'url': 'https://www.svtplay.se/rederiet',
  210. 'info_dict': {
  211. 'id': '14445680',
  212. 'title': 'Rederiet',
  213. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  214. },
  215. 'playlist_mincount': 318,
  216. }, {
  217. 'url': 'https://www.svtplay.se/rederiet?tab=season-2-14445680',
  218. 'info_dict': {
  219. 'id': 'season-2-14445680',
  220. 'title': 'Rederiet - Säsong 2',
  221. 'description': 'md5:d9fdfff17f5d8f73468176ecd2836039',
  222. },
  223. 'playlist_mincount': 12,
  224. }]
  225. @classmethod
  226. def suitable(cls, url):
  227. return False if SVTIE.suitable(url) or SVTPlayIE.suitable(url) else super(SVTSeriesIE, cls).suitable(url)
  228. def _real_extract(self, url):
  229. series_slug, season_id = re.match(self._VALID_URL, url).groups()
  230. series = self._download_json(
  231. 'https://api.svt.se/contento/graphql', series_slug,
  232. 'Downloading series page', query={
  233. 'query': '''{
  234. listablesBySlug(slugs: ["%s"]) {
  235. associatedContent(include: [productionPeriod, season]) {
  236. items {
  237. item {
  238. ... on Episode {
  239. videoSvtId
  240. }
  241. }
  242. }
  243. id
  244. name
  245. }
  246. id
  247. longDescription
  248. name
  249. shortDescription
  250. }
  251. }''' % series_slug,
  252. })['data']['listablesBySlug'][0]
  253. season_name = None
  254. entries = []
  255. for season in series['associatedContent']:
  256. if not isinstance(season, dict):
  257. continue
  258. if season_id:
  259. if season.get('id') != season_id:
  260. continue
  261. season_name = season.get('name')
  262. items = season.get('items')
  263. if not isinstance(items, list):
  264. continue
  265. for item in items:
  266. video = item.get('item') or {}
  267. content_id = video.get('videoSvtId')
  268. if not content_id or not isinstance(content_id, compat_str):
  269. continue
  270. entries.append(self.url_result(
  271. 'svt:' + content_id, SVTPlayIE.ie_key(), content_id))
  272. title = series.get('name')
  273. season_name = season_name or season_id
  274. if title and season_name:
  275. title = '%s - %s' % (title, season_name)
  276. elif season_id:
  277. title = season_id
  278. return self.playlist_result(
  279. entries, season_id or series.get('id'), title,
  280. dict_get(series, ('longDescription', 'shortDescription')))
  281. class SVTPageIE(InfoExtractor):
  282. _VALID_URL = r'https?://(?:www\.)?svt\.se/(?P<path>(?:[^/]+/)*(?P<id>[^/?&#]+))'
  283. _TESTS = [{
  284. 'url': 'https://www.svt.se/sport/ishockey/bakom-masken-lehners-kamp-mot-mental-ohalsa',
  285. 'info_dict': {
  286. 'id': '25298267',
  287. 'title': 'Bakom masken – Lehners kamp mot mental ohälsa',
  288. },
  289. 'playlist_count': 4,
  290. }, {
  291. 'url': 'https://www.svt.se/nyheter/utrikes/svenska-andrea-ar-en-mil-fran-branderna-i-kalifornien',
  292. 'info_dict': {
  293. 'id': '24243746',
  294. 'title': 'Svenska Andrea redo att fly sitt hem i Kalifornien',
  295. },
  296. 'playlist_count': 2,
  297. }, {
  298. # only programTitle
  299. 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
  300. 'info_dict': {
  301. 'id': '8439V2K',
  302. 'ext': 'mp4',
  303. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  304. 'duration': 27,
  305. 'age_limit': 0,
  306. },
  307. }, {
  308. 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
  309. 'only_matching': True,
  310. }, {
  311. 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
  312. 'only_matching': True,
  313. }]
  314. @classmethod
  315. def suitable(cls, url):
  316. return False if SVTIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
  317. def _real_extract(self, url):
  318. path, display_id = re.match(self._VALID_URL, url).groups()
  319. article = self._download_json(
  320. 'https://api.svt.se/nss-api/page/' + path, display_id,
  321. query={'q': 'articles'})['articles']['content'][0]
  322. entries = []
  323. def _process_content(content):
  324. if content.get('_type') in ('VIDEOCLIP', 'VIDEOEPISODE'):
  325. video_id = compat_str(content['image']['svtId'])
  326. entries.append(self.url_result(
  327. 'svt:' + video_id, SVTPlayIE.ie_key(), video_id))
  328. for media in article.get('media', []):
  329. _process_content(media)
  330. for obj in article.get('structuredBody', []):
  331. _process_content(obj.get('content') or {})
  332. return self.playlist_result(
  333. entries, str_or_none(article.get('id')),
  334. strip_or_none(article.get('title')))