logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

svt.py (15412B)


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