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.

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