You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

371 lines
13 KiB

8 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_parse_qs,
  7. compat_urllib_parse_urlparse,
  8. )
  9. from ..utils import (
  10. determine_ext,
  11. dict_get,
  12. int_or_none,
  13. orderedSet,
  14. strip_or_none,
  15. try_get,
  16. urljoin,
  17. compat_str,
  18. )
  19. class SVTBaseIE(InfoExtractor):
  20. _GEO_COUNTRIES = ['SE']
  21. def _extract_video(self, video_info, video_id):
  22. is_live = dict_get(video_info, ('live', 'simulcast'), default=False)
  23. m3u8_protocol = 'm3u8' if is_live else 'm3u8_native'
  24. formats = []
  25. for vr in video_info['videoReferences']:
  26. player_type = vr.get('playerType') or vr.get('format')
  27. vurl = vr['url']
  28. ext = determine_ext(vurl)
  29. if ext == 'm3u8':
  30. formats.extend(self._extract_m3u8_formats(
  31. vurl, video_id,
  32. ext='mp4', entry_protocol=m3u8_protocol,
  33. m3u8_id=player_type, fatal=False))
  34. elif ext == 'f4m':
  35. formats.extend(self._extract_f4m_formats(
  36. vurl + '?hdcore=3.3.0', video_id,
  37. f4m_id=player_type, fatal=False))
  38. elif ext == 'mpd':
  39. if player_type == 'dashhbbtv':
  40. formats.extend(self._extract_mpd_formats(
  41. vurl, video_id, mpd_id=player_type, fatal=False))
  42. else:
  43. formats.append({
  44. 'format_id': player_type,
  45. 'url': vurl,
  46. })
  47. if not formats and video_info.get('rights', {}).get('geoBlockedSweden'):
  48. self.raise_geo_restricted(
  49. 'This video is only available in Sweden',
  50. countries=self._GEO_COUNTRIES)
  51. self._sort_formats(formats)
  52. subtitles = {}
  53. subtitle_references = dict_get(video_info, ('subtitles', 'subtitleReferences'))
  54. if isinstance(subtitle_references, list):
  55. for sr in subtitle_references:
  56. subtitle_url = sr.get('url')
  57. subtitle_lang = sr.get('language', 'sv')
  58. if subtitle_url:
  59. if determine_ext(subtitle_url) == 'm3u8':
  60. # TODO(yan12125): handle WebVTT in m3u8 manifests
  61. continue
  62. subtitles.setdefault(subtitle_lang, []).append({'url': subtitle_url})
  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. duration = int_or_none(dict_get(video_info, ('materialLength', 'contentDuration')))
  69. age_limit = None
  70. adult = dict_get(
  71. video_info, ('inappropriateForChildren', 'blockedForChildren'),
  72. skip_false_values=False)
  73. if adult is not None:
  74. age_limit = 18 if adult else 0
  75. return {
  76. 'id': video_id,
  77. 'title': title,
  78. 'formats': formats,
  79. 'subtitles': subtitles,
  80. 'duration': duration,
  81. 'age_limit': age_limit,
  82. 'series': series,
  83. 'season_number': season_number,
  84. 'episode': episode,
  85. 'episode_number': episode_number,
  86. 'is_live': is_live,
  87. }
  88. class SVTIE(SVTBaseIE):
  89. _VALID_URL = r'https?://(?:www\.)?svt\.se/wd\?(?:.*?&)?widgetId=(?P<widget_id>\d+)&.*?\barticleId=(?P<id>\d+)'
  90. _TEST = {
  91. 'url': 'http://www.svt.se/wd?widgetId=23991&sectionId=541&articleId=2900353&type=embed&contextSectionId=123&autostart=false',
  92. 'md5': '33e9a5d8f646523ce0868ecfb0eed77d',
  93. 'info_dict': {
  94. 'id': '2900353',
  95. 'ext': 'mp4',
  96. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  97. 'duration': 27,
  98. 'age_limit': 0,
  99. },
  100. }
  101. @staticmethod
  102. def _extract_url(webpage):
  103. mobj = re.search(
  104. r'(?:<iframe src|href)="(?P<url>%s[^"]*)"' % SVTIE._VALID_URL, webpage)
  105. if mobj:
  106. return mobj.group('url')
  107. def _real_extract(self, url):
  108. mobj = re.match(self._VALID_URL, url)
  109. widget_id = mobj.group('widget_id')
  110. article_id = mobj.group('id')
  111. info = self._download_json(
  112. 'http://www.svt.se/wd?widgetId=%s&articleId=%s&format=json&type=embed&output=json' % (widget_id, article_id),
  113. article_id)
  114. info_dict = self._extract_video(info['video'], article_id)
  115. info_dict['title'] = info['context']['title']
  116. return info_dict
  117. class SVTPlayBaseIE(SVTBaseIE):
  118. _SVTPLAY_RE = r'root\s*\[\s*(["\'])_*svtplay\1\s*\]\s*=\s*(?P<json>{.+?})\s*;\s*\n'
  119. class SVTPlayIE(SVTPlayBaseIE):
  120. IE_DESC = 'SVT Play and Öppet arkiv'
  121. _VALID_URL = r'''(?x)
  122. (?:
  123. svt:(?P<svt_id>[^/?#&]+)|
  124. https?://(?:www\.)?(?:svtplay|oppetarkiv)\.se/(?:video|klipp|kanaler)/(?P<id>[^/?#&]+)
  125. )
  126. '''
  127. _TESTS = [{
  128. 'url': 'http://www.svtplay.se/video/5996901/flygplan-till-haile-selassie/flygplan-till-haile-selassie-2',
  129. 'md5': '2b6704fe4a28801e1a098bbf3c5ac611',
  130. 'info_dict': {
  131. 'id': '5996901',
  132. 'ext': 'mp4',
  133. 'title': 'Flygplan till Haile Selassie',
  134. 'duration': 3527,
  135. 'thumbnail': r're:^https?://.*[\.-]jpg$',
  136. 'age_limit': 0,
  137. 'subtitles': {
  138. 'sv': [{
  139. 'ext': 'wsrt',
  140. }]
  141. },
  142. },
  143. }, {
  144. # geo restricted to Sweden
  145. 'url': 'http://www.oppetarkiv.se/video/5219710/trollflojten',
  146. 'only_matching': True,
  147. }, {
  148. 'url': 'http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg',
  149. 'only_matching': True,
  150. }, {
  151. 'url': 'https://www.svtplay.se/kanaler/svt1',
  152. 'only_matching': True,
  153. }, {
  154. 'url': 'svt:1376446-003A',
  155. 'only_matching': True,
  156. }, {
  157. 'url': 'svt:14278044',
  158. 'only_matching': True,
  159. }]
  160. def _adjust_title(self, info):
  161. if info['is_live']:
  162. info['title'] = self._live_title(info['title'])
  163. def _extract_by_video_id(self, video_id, webpage=None):
  164. data = self._download_json(
  165. 'https://api.svt.se/video/%s' % video_id,
  166. video_id, headers=self.geo_verification_headers())
  167. info_dict = self._extract_video(data, video_id)
  168. if not info_dict.get('title'):
  169. title = dict_get(info_dict, ('episode', 'series'))
  170. if not title and webpage:
  171. title = re.sub(
  172. r'\s*\|\s*.+?$', '', self._og_search_title(webpage))
  173. if not title:
  174. title = video_id
  175. info_dict['title'] = title
  176. self._adjust_title(info_dict)
  177. return info_dict
  178. def _real_extract(self, url):
  179. mobj = re.match(self._VALID_URL, url)
  180. video_id, svt_id = mobj.group('id', 'svt_id')
  181. if svt_id:
  182. return self._extract_by_video_id(svt_id)
  183. webpage = self._download_webpage(url, video_id)
  184. data = self._parse_json(
  185. self._search_regex(
  186. self._SVTPLAY_RE, webpage, 'embedded data', default='{}',
  187. group='json'),
  188. video_id, fatal=False)
  189. thumbnail = self._og_search_thumbnail(webpage)
  190. if data:
  191. video_info = try_get(
  192. data, lambda x: x['context']['dispatcher']['stores']['VideoTitlePageStore']['data']['video'],
  193. dict)
  194. if video_info:
  195. info_dict = self._extract_video(video_info, video_id)
  196. info_dict.update({
  197. 'title': data['context']['dispatcher']['stores']['MetaStore']['title'],
  198. 'thumbnail': thumbnail,
  199. })
  200. self._adjust_title(info_dict)
  201. return info_dict
  202. svt_id = self._search_regex(
  203. r'<video[^>]+data-video-id=["\']([\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>[^/?&#]+)'
  208. _TESTS = [{
  209. 'url': 'https://www.svtplay.se/rederiet',
  210. 'info_dict': {
  211. 'id': 'rederiet',
  212. 'title': 'Rederiet',
  213. 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
  214. },
  215. 'playlist_mincount': 318,
  216. }, {
  217. 'url': 'https://www.svtplay.se/rederiet?tab=sasong2',
  218. 'info_dict': {
  219. 'id': 'rederiet-sasong2',
  220. 'title': 'Rederiet - Säsong 2',
  221. 'description': 'md5:505d491a58f4fcf6eb418ecab947e69e',
  222. },
  223. 'playlist_count': 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_id = self._match_id(url)
  230. qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  231. season_slug = qs.get('tab', [None])[0]
  232. if season_slug:
  233. series_id += '-%s' % season_slug
  234. webpage = self._download_webpage(
  235. url, series_id, 'Downloading series page')
  236. root = self._parse_json(
  237. self._search_regex(
  238. self._SVTPLAY_RE, webpage, 'content', group='json'),
  239. series_id)
  240. season_name = None
  241. entries = []
  242. for season in root['relatedVideoContent']['relatedVideosAccordion']:
  243. if not isinstance(season, dict):
  244. continue
  245. if season_slug:
  246. if season.get('slug') != season_slug:
  247. continue
  248. season_name = season.get('name')
  249. videos = season.get('videos')
  250. if not isinstance(videos, list):
  251. continue
  252. for video in videos:
  253. content_url = video.get('contentUrl')
  254. if not content_url or not isinstance(content_url, compat_str):
  255. continue
  256. entries.append(
  257. self.url_result(
  258. urljoin(url, content_url),
  259. ie=SVTPlayIE.ie_key(),
  260. video_title=video.get('title')
  261. ))
  262. metadata = root.get('metaData')
  263. if not isinstance(metadata, dict):
  264. metadata = {}
  265. title = metadata.get('title')
  266. season_name = season_name or season_slug
  267. if title and season_name:
  268. title = '%s - %s' % (title, season_name)
  269. elif season_slug:
  270. title = season_slug
  271. return self.playlist_result(
  272. entries, series_id, title, metadata.get('description'))
  273. class SVTPageIE(InfoExtractor):
  274. _VALID_URL = r'https?://(?:www\.)?svt\.se/(?:[^/]+/)*(?P<id>[^/?&#]+)'
  275. _TESTS = [{
  276. 'url': 'https://www.svt.se/sport/oseedat/guide-sommartraningen-du-kan-gora-var-och-nar-du-vill',
  277. 'info_dict': {
  278. 'id': 'guide-sommartraningen-du-kan-gora-var-och-nar-du-vill',
  279. 'title': 'GUIDE: Sommarträning du kan göra var och när du vill',
  280. },
  281. 'playlist_count': 7,
  282. }, {
  283. 'url': 'https://www.svt.se/nyheter/inrikes/ebba-busch-thor-kd-har-delvis-ratt-om-no-go-zoner',
  284. 'info_dict': {
  285. 'id': 'ebba-busch-thor-kd-har-delvis-ratt-om-no-go-zoner',
  286. 'title': 'Ebba Busch Thor har bara delvis rätt om ”no-go-zoner”',
  287. },
  288. 'playlist_count': 1,
  289. }, {
  290. # only programTitle
  291. 'url': 'http://www.svt.se/sport/ishockey/jagr-tacklar-giroux-under-intervjun',
  292. 'info_dict': {
  293. 'id': '2900353',
  294. 'ext': 'mp4',
  295. 'title': 'Stjärnorna skojar till det - under SVT-intervjun',
  296. 'duration': 27,
  297. 'age_limit': 0,
  298. },
  299. }, {
  300. 'url': 'https://www.svt.se/nyheter/lokalt/vast/svt-testar-tar-nagon-upp-skrapet-1',
  301. 'only_matching': True,
  302. }, {
  303. 'url': 'https://www.svt.se/vader/manadskronikor/maj2018',
  304. 'only_matching': True,
  305. }]
  306. @classmethod
  307. def suitable(cls, url):
  308. return False if SVTIE.suitable(url) else super(SVTPageIE, cls).suitable(url)
  309. def _real_extract(self, url):
  310. playlist_id = self._match_id(url)
  311. webpage = self._download_webpage(url, playlist_id)
  312. entries = [
  313. self.url_result(
  314. 'svt:%s' % video_id, ie=SVTPlayIE.ie_key(), video_id=video_id)
  315. for video_id in orderedSet(re.findall(
  316. r'data-video-id=["\'](\d+)', webpage))]
  317. title = strip_or_none(self._og_search_title(webpage, default=None))
  318. return self.playlist_result(entries, playlist_id, title)