dplay.py 14 KB

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