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.

376 lines
15 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. import time
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_HTTPError,
  9. compat_str,
  10. compat_urlparse,
  11. )
  12. from ..utils import (
  13. determine_ext,
  14. ExtractorError,
  15. float_or_none,
  16. int_or_none,
  17. remove_end,
  18. try_get,
  19. unified_strdate,
  20. unified_timestamp,
  21. update_url_query,
  22. urljoin,
  23. USER_AGENTS,
  24. )
  25. class DPlayIE(InfoExtractor):
  26. _VALID_URL = r'https?://(?P<domain>www\.(?P<host>dplay\.(?P<country>dk|se|no)))/(?:video(?:er|s)/)?(?P<id>[^/]+/[^/?#]+)'
  27. _TESTS = [{
  28. # non geo restricted, via secure api, unsigned download hls URL
  29. 'url': 'http://www.dplay.se/nugammalt-77-handelser-som-format-sverige/season-1-svensken-lar-sig-njuta-av-livet/',
  30. 'info_dict': {
  31. 'id': '3172',
  32. 'display_id': 'nugammalt-77-handelser-som-format-sverige/season-1-svensken-lar-sig-njuta-av-livet',
  33. 'ext': 'mp4',
  34. 'title': 'Svensken lär sig njuta av livet',
  35. 'description': 'md5:d3819c9bccffd0fe458ca42451dd50d8',
  36. 'duration': 2650,
  37. 'timestamp': 1365454320,
  38. 'upload_date': '20130408',
  39. 'creator': 'Kanal 5 (Home)',
  40. 'series': 'Nugammalt - 77 händelser som format Sverige',
  41. 'season_number': 1,
  42. 'episode_number': 1,
  43. 'age_limit': 0,
  44. },
  45. }, {
  46. # geo restricted, via secure api, unsigned download hls URL
  47. 'url': 'http://www.dplay.dk/mig-og-min-mor/season-6-episode-12/',
  48. 'info_dict': {
  49. 'id': '70816',
  50. 'display_id': 'mig-og-min-mor/season-6-episode-12',
  51. 'ext': 'mp4',
  52. 'title': 'Episode 12',
  53. 'description': 'md5:9c86e51a93f8a4401fc9641ef9894c90',
  54. 'duration': 2563,
  55. 'timestamp': 1429696800,
  56. 'upload_date': '20150422',
  57. 'creator': 'Kanal 4 (Home)',
  58. 'series': 'Mig og min mor',
  59. 'season_number': 6,
  60. 'episode_number': 12,
  61. 'age_limit': 0,
  62. },
  63. }, {
  64. # geo restricted, via direct unsigned hls URL
  65. 'url': 'http://www.dplay.no/pga-tour/season-1-hoydepunkter-18-21-februar/',
  66. 'only_matching': True,
  67. }, {
  68. # disco-api
  69. 'url': 'https://www.dplay.no/videoer/i-kongens-klr/sesong-1-episode-7',
  70. 'info_dict': {
  71. 'id': '40206',
  72. 'display_id': 'i-kongens-klr/sesong-1-episode-7',
  73. 'ext': 'mp4',
  74. 'title': 'Episode 7',
  75. 'description': 'md5:e3e1411b2b9aebeea36a6ec5d50c60cf',
  76. 'duration': 2611.16,
  77. 'timestamp': 1516726800,
  78. 'upload_date': '20180123',
  79. 'series': 'I kongens klær',
  80. 'season_number': 1,
  81. 'episode_number': 7,
  82. },
  83. 'params': {
  84. 'format': 'bestvideo',
  85. 'skip_download': True,
  86. },
  87. }, {
  88. 'url': 'https://www.dplay.dk/videoer/singleliv/season-5-episode-3',
  89. 'only_matching': True,
  90. }, {
  91. 'url': 'https://www.dplay.se/videos/sofias-anglar/sofias-anglar-1001',
  92. 'only_matching': True,
  93. }]
  94. def _get_disco_api_info(self, url, display_id, disco_host, realm):
  95. disco_base = 'https://' + disco_host
  96. token = self._download_json(
  97. '%s/token' % disco_base, display_id, 'Downloading token',
  98. query={
  99. 'realm': realm,
  100. })['data']['attributes']['token']
  101. headers = {
  102. 'Referer': url,
  103. 'Authorization': 'Bearer ' + token,
  104. }
  105. video = self._download_json(
  106. '%s/content/videos/%s' % (disco_base, display_id), display_id,
  107. headers=headers, query={
  108. 'include': 'show'
  109. })
  110. video_id = video['data']['id']
  111. info = video['data']['attributes']
  112. title = info['name']
  113. formats = []
  114. for format_id, format_dict in self._download_json(
  115. '%s/playback/videoPlaybackInfo/%s' % (disco_base, video_id),
  116. display_id, headers=headers)['data']['attributes']['streaming'].items():
  117. if not isinstance(format_dict, dict):
  118. continue
  119. format_url = format_dict.get('url')
  120. if not format_url:
  121. continue
  122. ext = determine_ext(format_url)
  123. if format_id == 'dash' or ext == 'mpd':
  124. formats.extend(self._extract_mpd_formats(
  125. format_url, display_id, mpd_id='dash', fatal=False))
  126. elif format_id == 'hls' or ext == 'm3u8':
  127. formats.extend(self._extract_m3u8_formats(
  128. format_url, display_id, 'mp4',
  129. entry_protocol='m3u8_native', m3u8_id='hls',
  130. fatal=False))
  131. else:
  132. formats.append({
  133. 'url': format_url,
  134. 'format_id': format_id,
  135. })
  136. self._sort_formats(formats)
  137. series = None
  138. try:
  139. included = video.get('included')
  140. if isinstance(included, list):
  141. show = next(e for e in included if e.get('type') == 'show')
  142. series = try_get(
  143. show, lambda x: x['attributes']['name'], compat_str)
  144. except StopIteration:
  145. pass
  146. return {
  147. 'id': video_id,
  148. 'display_id': display_id,
  149. 'title': title,
  150. 'description': info.get('description'),
  151. 'duration': float_or_none(
  152. info.get('videoDuration'), scale=1000),
  153. 'timestamp': unified_timestamp(info.get('publishStart')),
  154. 'series': series,
  155. 'season_number': int_or_none(info.get('seasonNumber')),
  156. 'episode_number': int_or_none(info.get('episodeNumber')),
  157. 'age_limit': int_or_none(info.get('minimum_age')),
  158. 'formats': formats,
  159. }
  160. def _real_extract(self, url):
  161. mobj = re.match(self._VALID_URL, url)
  162. display_id = mobj.group('id')
  163. domain = mobj.group('domain')
  164. self._initialize_geo_bypass({
  165. 'countries': [mobj.group('country').upper()],
  166. })
  167. webpage = self._download_webpage(url, display_id)
  168. video_id = self._search_regex(
  169. r'data-video-id=["\'](\d+)', webpage, 'video id', default=None)
  170. if not video_id:
  171. host = mobj.group('host')
  172. return self._get_disco_api_info(
  173. url, display_id, 'disco-api.' + host, host.replace('.', ''))
  174. info = self._download_json(
  175. 'http://%s/api/v2/ajax/videos?video_id=%s' % (domain, video_id),
  176. video_id)['data'][0]
  177. title = info['title']
  178. PROTOCOLS = ('hls', 'hds')
  179. formats = []
  180. def extract_formats(protocol, manifest_url):
  181. if protocol == 'hls':
  182. m3u8_formats = self._extract_m3u8_formats(
  183. manifest_url, video_id, ext='mp4',
  184. entry_protocol='m3u8_native', m3u8_id=protocol, fatal=False)
  185. # Sometimes final URLs inside m3u8 are unsigned, let's fix this
  186. # ourselves. Also fragments' URLs are only served signed for
  187. # Safari user agent.
  188. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(manifest_url).query)
  189. for m3u8_format in m3u8_formats:
  190. m3u8_format.update({
  191. 'url': update_url_query(m3u8_format['url'], query),
  192. 'http_headers': {
  193. 'User-Agent': USER_AGENTS['Safari'],
  194. },
  195. })
  196. formats.extend(m3u8_formats)
  197. elif protocol == 'hds':
  198. formats.extend(self._extract_f4m_formats(
  199. manifest_url + '&hdcore=3.8.0&plugin=flowplayer-3.8.0.0',
  200. video_id, f4m_id=protocol, fatal=False))
  201. domain_tld = domain.split('.')[-1]
  202. if domain_tld in ('se', 'dk', 'no'):
  203. for protocol in PROTOCOLS:
  204. # Providing dsc-geo allows to bypass geo restriction in some cases
  205. self._set_cookie(
  206. 'secure.dplay.%s' % domain_tld, 'dsc-geo',
  207. json.dumps({
  208. 'countryCode': domain_tld.upper(),
  209. 'expiry': (time.time() + 20 * 60) * 1000,
  210. }))
  211. stream = self._download_json(
  212. 'https://secure.dplay.%s/secure/api/v2/user/authorization/stream/%s?stream_type=%s'
  213. % (domain_tld, video_id, protocol), video_id,
  214. 'Downloading %s stream JSON' % protocol, fatal=False)
  215. if stream and stream.get(protocol):
  216. extract_formats(protocol, stream[protocol])
  217. # The last resort is to try direct unsigned hls/hds URLs from info dictionary.
  218. # Sometimes this does work even when secure API with dsc-geo has failed (e.g.
  219. # http://www.dplay.no/pga-tour/season-1-hoydepunkter-18-21-februar/).
  220. if not formats:
  221. for protocol in PROTOCOLS:
  222. if info.get(protocol):
  223. extract_formats(protocol, info[protocol])
  224. self._sort_formats(formats)
  225. subtitles = {}
  226. for lang in ('se', 'sv', 'da', 'nl', 'no'):
  227. for format_id in ('web_vtt', 'vtt', 'srt'):
  228. subtitle_url = info.get('subtitles_%s_%s' % (lang, format_id))
  229. if subtitle_url:
  230. subtitles.setdefault(lang, []).append({'url': subtitle_url})
  231. return {
  232. 'id': video_id,
  233. 'display_id': display_id,
  234. 'title': title,
  235. 'description': info.get('video_metadata_longDescription'),
  236. 'duration': int_or_none(info.get('video_metadata_length'), scale=1000),
  237. 'timestamp': int_or_none(info.get('video_publish_date')),
  238. 'creator': info.get('video_metadata_homeChannel'),
  239. 'series': info.get('video_metadata_show'),
  240. 'season_number': int_or_none(info.get('season')),
  241. 'episode_number': int_or_none(info.get('episode')),
  242. 'age_limit': int_or_none(info.get('minimum_age')),
  243. 'formats': formats,
  244. 'subtitles': subtitles,
  245. }
  246. class DPlayItIE(InfoExtractor):
  247. _VALID_URL = r'https?://it\.dplay\.com/[^/]+/[^/]+/(?P<id>[^/?#]+)'
  248. _GEO_COUNTRIES = ['IT']
  249. _TEST = {
  250. 'url': 'http://it.dplay.com/nove/biografie-imbarazzanti/luigi-di-maio-la-psicosi-di-stanislawskij/',
  251. 'md5': '2b808ffb00fc47b884a172ca5d13053c',
  252. 'info_dict': {
  253. 'id': '6918',
  254. 'display_id': 'luigi-di-maio-la-psicosi-di-stanislawskij',
  255. 'ext': 'mp4',
  256. 'title': 'Biografie imbarazzanti: Luigi Di Maio: la psicosi di Stanislawskij',
  257. 'description': 'md5:3c7a4303aef85868f867a26f5cc14813',
  258. 'thumbnail': r're:^https?://.*\.jpe?g',
  259. 'upload_date': '20160524',
  260. 'series': 'Biografie imbarazzanti',
  261. 'season_number': 1,
  262. 'episode': 'Luigi Di Maio: la psicosi di Stanislawskij',
  263. 'episode_number': 1,
  264. },
  265. }
  266. def _real_extract(self, url):
  267. display_id = self._match_id(url)
  268. webpage = self._download_webpage(url, display_id)
  269. title = remove_end(self._og_search_title(webpage), ' | Dplay')
  270. video_id = None
  271. info = self._search_regex(
  272. r'playback_json\s*:\s*JSON\.parse\s*\(\s*("(?:\\.|[^"\\])+?")',
  273. webpage, 'playback JSON', default=None)
  274. if info:
  275. for _ in range(2):
  276. info = self._parse_json(info, display_id, fatal=False)
  277. if not info:
  278. break
  279. else:
  280. video_id = try_get(info, lambda x: x['data']['id'])
  281. if not info:
  282. info_url = self._search_regex(
  283. (r'playback_json_url\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1',
  284. r'url\s*[:=]\s*["\'](?P<url>(?:https?:)?//[^/]+/playback/videoPlaybackInfo/\d+)'),
  285. webpage, 'info url', group='url')
  286. info_url = urljoin(url, info_url)
  287. video_id = info_url.rpartition('/')[-1]
  288. try:
  289. info = self._download_json(
  290. info_url, display_id, headers={
  291. 'Authorization': 'Bearer %s' % self._get_cookies(url).get(
  292. 'dplayit_token').value,
  293. 'Referer': url,
  294. })
  295. if isinstance(info, compat_str):
  296. info = self._parse_json(info, display_id)
  297. except ExtractorError as e:
  298. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (400, 403):
  299. info = self._parse_json(e.cause.read().decode('utf-8'), display_id)
  300. error = info['errors'][0]
  301. if error.get('code') == 'access.denied.geoblocked':
  302. self.raise_geo_restricted(
  303. msg=error.get('detail'), countries=self._GEO_COUNTRIES)
  304. raise ExtractorError(info['errors'][0]['detail'], expected=True)
  305. raise
  306. hls_url = info['data']['attributes']['streaming']['hls']['url']
  307. formats = self._extract_m3u8_formats(
  308. hls_url, display_id, ext='mp4', entry_protocol='m3u8_native',
  309. m3u8_id='hls')
  310. self._sort_formats(formats)
  311. series = self._html_search_regex(
  312. r'(?s)<h1[^>]+class=["\'].*?\bshow_title\b.*?["\'][^>]*>(.+?)</h1>',
  313. webpage, 'series', fatal=False)
  314. episode = self._search_regex(
  315. r'<p[^>]+class=["\'].*?\bdesc_ep\b.*?["\'][^>]*>\s*<br/>\s*<b>([^<]+)',
  316. webpage, 'episode', fatal=False)
  317. mobj = re.search(
  318. r'(?s)<span[^>]+class=["\']dates["\'][^>]*>.+?\bS\.(?P<season_number>\d+)\s+E\.(?P<episode_number>\d+)\s*-\s*(?P<upload_date>\d{2}/\d{2}/\d{4})',
  319. webpage)
  320. if mobj:
  321. season_number = int(mobj.group('season_number'))
  322. episode_number = int(mobj.group('episode_number'))
  323. upload_date = unified_strdate(mobj.group('upload_date'))
  324. else:
  325. season_number = episode_number = upload_date = None
  326. return {
  327. 'id': compat_str(video_id or display_id),
  328. 'display_id': display_id,
  329. 'title': title,
  330. 'description': self._og_search_description(webpage),
  331. 'thumbnail': self._og_search_thumbnail(webpage),
  332. 'series': series,
  333. 'season_number': season_number,
  334. 'episode': episode,
  335. 'episode_number': episode_number,
  336. 'upload_date': upload_date,
  337. 'formats': formats,
  338. }