dplay.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 _get_disco_api_info(self, url, display_id, disco_host, realm):
  94. disco_base = 'https://' + disco_host
  95. token = self._download_json(
  96. '%s/token' % disco_base, display_id, 'Downloading token',
  97. query={
  98. 'realm': realm,
  99. })['data']['attributes']['token']
  100. headers = {
  101. 'Referer': url,
  102. 'Authorization': 'Bearer ' + token,
  103. }
  104. video = self._download_json(
  105. '%s/content/videos/%s' % (disco_base, display_id), display_id,
  106. headers=headers, query={
  107. 'include': 'show'
  108. })
  109. video_id = video['data']['id']
  110. info = video['data']['attributes']
  111. title = info['name']
  112. formats = []
  113. for format_id, format_dict in self._download_json(
  114. '%s/playback/videoPlaybackInfo/%s' % (disco_base, video_id),
  115. display_id, headers=headers)['data']['attributes']['streaming'].items():
  116. if not isinstance(format_dict, dict):
  117. continue
  118. format_url = format_dict.get('url')
  119. if not format_url:
  120. continue
  121. ext = determine_ext(format_url)
  122. if format_id == 'dash' or ext == 'mpd':
  123. formats.extend(self._extract_mpd_formats(
  124. format_url, display_id, mpd_id='dash', fatal=False))
  125. elif format_id == 'hls' or ext == 'm3u8':
  126. formats.extend(self._extract_m3u8_formats(
  127. format_url, display_id, 'mp4',
  128. entry_protocol='m3u8_native', m3u8_id='hls',
  129. fatal=False))
  130. else:
  131. formats.append({
  132. 'url': format_url,
  133. 'format_id': format_id,
  134. })
  135. self._sort_formats(formats)
  136. series = None
  137. try:
  138. included = video.get('included')
  139. if isinstance(included, list):
  140. show = next(e for e in included if e.get('type') == 'show')
  141. series = try_get(
  142. show, lambda x: x['attributes']['name'], compat_str)
  143. except StopIteration:
  144. pass
  145. return {
  146. 'id': video_id,
  147. 'display_id': display_id,
  148. 'title': title,
  149. 'description': info.get('description'),
  150. 'duration': float_or_none(
  151. info.get('videoDuration'), scale=1000),
  152. 'timestamp': unified_timestamp(info.get('publishStart')),
  153. 'series': series,
  154. 'season_number': int_or_none(info.get('seasonNumber')),
  155. 'episode_number': int_or_none(info.get('episodeNumber')),
  156. 'age_limit': int_or_none(info.get('minimum_age')),
  157. 'formats': formats,
  158. }
  159. def _real_extract(self, url):
  160. mobj = re.match(self._VALID_URL, url)
  161. display_id = mobj.group('id')
  162. domain = mobj.group('domain')
  163. self._initialize_geo_bypass({
  164. 'countries': [mobj.group('country').upper()],
  165. })
  166. webpage = self._download_webpage(url, display_id)
  167. video_id = self._search_regex(
  168. r'data-video-id=["\'](\d+)', webpage, 'video id', default=None)
  169. if not video_id:
  170. host = mobj.group('host')
  171. return self._get_disco_api_info(
  172. url, display_id, 'disco-api.' + host, host.replace('.', ''))
  173. info = self._download_json(
  174. 'http://%s/api/v2/ajax/videos?video_id=%s' % (domain, video_id),
  175. video_id)['data'][0]
  176. title = info['title']
  177. PROTOCOLS = ('hls', 'hds')
  178. formats = []
  179. def extract_formats(protocol, manifest_url):
  180. if protocol == 'hls':
  181. m3u8_formats = self._extract_m3u8_formats(
  182. manifest_url, video_id, ext='mp4',
  183. entry_protocol='m3u8_native', m3u8_id=protocol, fatal=False)
  184. # Sometimes final URLs inside m3u8 are unsigned, let's fix this
  185. # ourselves. Also fragments' URLs are only served signed for
  186. # Safari user agent.
  187. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(manifest_url).query)
  188. for m3u8_format in m3u8_formats:
  189. m3u8_format.update({
  190. 'url': update_url_query(m3u8_format['url'], query),
  191. 'http_headers': {
  192. 'User-Agent': USER_AGENTS['Safari'],
  193. },
  194. })
  195. formats.extend(m3u8_formats)
  196. elif protocol == 'hds':
  197. formats.extend(self._extract_f4m_formats(
  198. manifest_url + '&hdcore=3.8.0&plugin=flowplayer-3.8.0.0',
  199. video_id, f4m_id=protocol, fatal=False))
  200. domain_tld = domain.split('.')[-1]
  201. if domain_tld in ('se', 'dk', 'no'):
  202. for protocol in PROTOCOLS:
  203. # Providing dsc-geo allows to bypass geo restriction in some cases
  204. self._set_cookie(
  205. 'secure.dplay.%s' % domain_tld, 'dsc-geo',
  206. json.dumps({
  207. 'countryCode': domain_tld.upper(),
  208. 'expiry': (time.time() + 20 * 60) * 1000,
  209. }))
  210. stream = self._download_json(
  211. 'https://secure.dplay.%s/secure/api/v2/user/authorization/stream/%s?stream_type=%s'
  212. % (domain_tld, video_id, protocol), video_id,
  213. 'Downloading %s stream JSON' % protocol, fatal=False)
  214. if stream and stream.get(protocol):
  215. extract_formats(protocol, stream[protocol])
  216. # The last resort is to try direct unsigned hls/hds URLs from info dictionary.
  217. # Sometimes this does work even when secure API with dsc-geo has failed (e.g.
  218. # http://www.dplay.no/pga-tour/season-1-hoydepunkter-18-21-februar/).
  219. if not formats:
  220. for protocol in PROTOCOLS:
  221. if info.get(protocol):
  222. extract_formats(protocol, info[protocol])
  223. self._sort_formats(formats)
  224. subtitles = {}
  225. for lang in ('se', 'sv', 'da', 'nl', 'no'):
  226. for format_id in ('web_vtt', 'vtt', 'srt'):
  227. subtitle_url = info.get('subtitles_%s_%s' % (lang, format_id))
  228. if subtitle_url:
  229. subtitles.setdefault(lang, []).append({'url': subtitle_url})
  230. return {
  231. 'id': video_id,
  232. 'display_id': display_id,
  233. 'title': title,
  234. 'description': info.get('video_metadata_longDescription'),
  235. 'duration': int_or_none(info.get('video_metadata_length'), scale=1000),
  236. 'timestamp': int_or_none(info.get('video_publish_date')),
  237. 'creator': info.get('video_metadata_homeChannel'),
  238. 'series': info.get('video_metadata_show'),
  239. 'season_number': int_or_none(info.get('season')),
  240. 'episode_number': int_or_none(info.get('episode')),
  241. 'age_limit': int_or_none(info.get('minimum_age')),
  242. 'formats': formats,
  243. 'subtitles': subtitles,
  244. }
  245. class DPlayItIE(InfoExtractor):
  246. _VALID_URL = r'https?://it\.dplay\.com/[^/]+/[^/]+/(?P<id>[^/?#]+)'
  247. _GEO_COUNTRIES = ['IT']
  248. _TEST = {
  249. 'url': 'http://it.dplay.com/nove/biografie-imbarazzanti/luigi-di-maio-la-psicosi-di-stanislawskij/',
  250. 'md5': '2b808ffb00fc47b884a172ca5d13053c',
  251. 'info_dict': {
  252. 'id': '6918',
  253. 'display_id': 'luigi-di-maio-la-psicosi-di-stanislawskij',
  254. 'ext': 'mp4',
  255. 'title': 'Biografie imbarazzanti: Luigi Di Maio: la psicosi di Stanislawskij',
  256. 'description': 'md5:3c7a4303aef85868f867a26f5cc14813',
  257. 'thumbnail': r're:^https?://.*\.jpe?g',
  258. 'upload_date': '20160524',
  259. 'series': 'Biografie imbarazzanti',
  260. 'season_number': 1,
  261. 'episode': 'Luigi Di Maio: la psicosi di Stanislawskij',
  262. 'episode_number': 1,
  263. },
  264. }
  265. def _real_extract(self, url):
  266. display_id = self._match_id(url)
  267. webpage = self._download_webpage(url, display_id)
  268. title = remove_end(self._og_search_title(webpage), ' | Dplay')
  269. video_id = None
  270. info = self._search_regex(
  271. r'playback_json\s*:\s*JSON\.parse\s*\(\s*("(?:\\.|[^"\\])+?")',
  272. webpage, 'playback JSON', default=None)
  273. if info:
  274. for _ in range(2):
  275. info = self._parse_json(info, display_id, fatal=False)
  276. if not info:
  277. break
  278. else:
  279. video_id = try_get(info, lambda x: x['data']['id'])
  280. if not info:
  281. info_url = self._search_regex(
  282. r'url\s*[:=]\s*["\']((?:https?:)?//[^/]+/playback/videoPlaybackInfo/\d+)',
  283. webpage, 'info url')
  284. video_id = info_url.rpartition('/')[-1]
  285. try:
  286. info = self._download_json(
  287. info_url, display_id, headers={
  288. 'Authorization': 'Bearer %s' % self._get_cookies(url).get(
  289. 'dplayit_token').value,
  290. 'Referer': url,
  291. })
  292. except ExtractorError as e:
  293. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (400, 403):
  294. info = self._parse_json(e.cause.read().decode('utf-8'), display_id)
  295. error = info['errors'][0]
  296. if error.get('code') == 'access.denied.geoblocked':
  297. self.raise_geo_restricted(
  298. msg=error.get('detail'), countries=self._GEO_COUNTRIES)
  299. raise ExtractorError(info['errors'][0]['detail'], expected=True)
  300. raise
  301. hls_url = info['data']['attributes']['streaming']['hls']['url']
  302. formats = self._extract_m3u8_formats(
  303. hls_url, display_id, ext='mp4', entry_protocol='m3u8_native',
  304. m3u8_id='hls')
  305. series = self._html_search_regex(
  306. r'(?s)<h1[^>]+class=["\'].*?\bshow_title\b.*?["\'][^>]*>(.+?)</h1>',
  307. webpage, 'series', fatal=False)
  308. episode = self._search_regex(
  309. r'<p[^>]+class=["\'].*?\bdesc_ep\b.*?["\'][^>]*>\s*<br/>\s*<b>([^<]+)',
  310. webpage, 'episode', fatal=False)
  311. mobj = re.search(
  312. 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})',
  313. webpage)
  314. if mobj:
  315. season_number = int(mobj.group('season_number'))
  316. episode_number = int(mobj.group('episode_number'))
  317. upload_date = unified_strdate(mobj.group('upload_date'))
  318. else:
  319. season_number = episode_number = upload_date = None
  320. return {
  321. 'id': compat_str(video_id or display_id),
  322. 'display_id': display_id,
  323. 'title': title,
  324. 'description': self._og_search_description(webpage),
  325. 'thumbnail': self._og_search_thumbnail(webpage),
  326. 'series': series,
  327. 'season_number': season_number,
  328. 'episode': episode,
  329. 'episode_number': episode_number,
  330. 'upload_date': upload_date,
  331. 'formats': formats,
  332. }