dplay.py 14 KB

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