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.

352 lines
14 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import binascii
  4. import hashlib
  5. import re
  6. from .common import InfoExtractor
  7. from ..aes import aes_cbc_decrypt
  8. from ..compat import compat_urllib_parse_unquote
  9. from ..utils import (
  10. bytes_to_intlist,
  11. ExtractorError,
  12. int_or_none,
  13. intlist_to_bytes,
  14. float_or_none,
  15. mimetype2ext,
  16. str_or_none,
  17. try_get,
  18. unified_timestamp,
  19. update_url_query,
  20. url_or_none,
  21. )
  22. class DRTVIE(InfoExtractor):
  23. _VALID_URL = r'''(?x)
  24. https?://
  25. (?:
  26. (?:www\.)?dr\.dk/(?:tv/se|nyheder|radio(?:/ondemand)?)/(?:[^/]+/)*|
  27. (?:www\.)?(?:dr\.dk|dr-massive\.com)/drtv/(?:se|episode)/
  28. )
  29. (?P<id>[\da-z_-]+)
  30. '''
  31. _GEO_BYPASS = False
  32. _GEO_COUNTRIES = ['DK']
  33. IE_NAME = 'drtv'
  34. _TESTS = [{
  35. 'url': 'https://www.dr.dk/tv/se/boern/ultra/klassen-ultra/klassen-darlig-taber-10',
  36. 'md5': '25e659cccc9a2ed956110a299fdf5983',
  37. 'info_dict': {
  38. 'id': 'klassen-darlig-taber-10',
  39. 'ext': 'mp4',
  40. 'title': 'Klassen - Dårlig taber (10)',
  41. 'description': 'md5:815fe1b7fa656ed80580f31e8b3c79aa',
  42. 'timestamp': 1539085800,
  43. 'upload_date': '20181009',
  44. 'duration': 606.84,
  45. 'series': 'Klassen',
  46. 'season': 'Klassen I',
  47. 'season_number': 1,
  48. 'season_id': 'urn:dr:mu:bundle:57d7e8216187a4031cfd6f6b',
  49. 'episode': 'Episode 10',
  50. 'episode_number': 10,
  51. 'release_year': 2016,
  52. },
  53. 'expected_warnings': ['Unable to download f4m manifest'],
  54. }, {
  55. # embed
  56. 'url': 'https://www.dr.dk/nyheder/indland/live-christianias-rydning-af-pusher-street-er-i-gang',
  57. 'info_dict': {
  58. 'id': 'urn:dr:mu:programcard:57c926176187a50a9c6e83c6',
  59. 'ext': 'mp4',
  60. 'title': 'christiania pusher street ryddes drdkrjpo',
  61. 'description': 'md5:2a71898b15057e9b97334f61d04e6eb5',
  62. 'timestamp': 1472800279,
  63. 'upload_date': '20160902',
  64. 'duration': 131.4,
  65. },
  66. 'params': {
  67. 'skip_download': True,
  68. },
  69. 'expected_warnings': ['Unable to download f4m manifest'],
  70. }, {
  71. # with SignLanguage formats
  72. 'url': 'https://www.dr.dk/tv/se/historien-om-danmark/-/historien-om-danmark-stenalder',
  73. 'info_dict': {
  74. 'id': 'historien-om-danmark-stenalder',
  75. 'ext': 'mp4',
  76. 'title': 'Historien om Danmark: Stenalder',
  77. 'description': 'md5:8c66dcbc1669bbc6f873879880f37f2a',
  78. 'timestamp': 1546628400,
  79. 'upload_date': '20190104',
  80. 'duration': 3502.56,
  81. 'formats': 'mincount:20',
  82. },
  83. 'params': {
  84. 'skip_download': True,
  85. },
  86. }, {
  87. 'url': 'https://www.dr.dk/radio/p4kbh/regionale-nyheder-kh4/p4-nyheder-2019-06-26-17-30-9',
  88. 'only_matching': True,
  89. }, {
  90. 'url': 'https://www.dr.dk/drtv/se/bonderoeven_71769',
  91. 'info_dict': {
  92. 'id': '00951930010',
  93. 'ext': 'mp4',
  94. 'title': 'Bonderøven (1:8)',
  95. 'description': 'md5:3cf18fc0d3b205745d4505f896af8121',
  96. 'timestamp': 1546542000,
  97. 'upload_date': '20190103',
  98. 'duration': 2576.6,
  99. },
  100. 'params': {
  101. 'skip_download': True,
  102. },
  103. }, {
  104. 'url': 'https://www.dr.dk/drtv/episode/bonderoeven_71769',
  105. 'only_matching': True,
  106. }, {
  107. 'url': 'https://dr-massive.com/drtv/se/bonderoeven_71769',
  108. 'only_matching': True,
  109. }]
  110. def _real_extract(self, url):
  111. video_id = self._match_id(url)
  112. webpage = self._download_webpage(url, video_id)
  113. if '>Programmet er ikke længere tilgængeligt' in webpage:
  114. raise ExtractorError(
  115. 'Video %s is not available' % video_id, expected=True)
  116. video_id = self._search_regex(
  117. (r'data-(?:material-identifier|episode-slug)="([^"]+)"',
  118. r'data-resource="[^>"]+mu/programcard/expanded/([^"]+)"'),
  119. webpage, 'video id', default=None)
  120. if not video_id:
  121. video_id = self._search_regex(
  122. r'(urn(?:%3A|:)dr(?:%3A|:)mu(?:%3A|:)programcard(?:%3A|:)[\da-f]+)',
  123. webpage, 'urn', default=None)
  124. if video_id:
  125. video_id = compat_urllib_parse_unquote(video_id)
  126. _PROGRAMCARD_BASE = 'https://www.dr.dk/mu-online/api/1.4/programcard'
  127. query = {'expanded': 'true'}
  128. if video_id:
  129. programcard_url = '%s/%s' % (_PROGRAMCARD_BASE, video_id)
  130. else:
  131. programcard_url = _PROGRAMCARD_BASE
  132. page = self._parse_json(
  133. self._search_regex(
  134. r'data\s*=\s*({.+?})\s*(?:;|</script)', webpage,
  135. 'data'), '1')['cache']['page']
  136. page = page[list(page.keys())[0]]
  137. item = try_get(
  138. page, (lambda x: x['item'], lambda x: x['entries'][0]['item']),
  139. dict)
  140. video_id = item['customId'].split(':')[-1]
  141. query['productionnumber'] = video_id
  142. data = self._download_json(
  143. programcard_url, video_id, 'Downloading video JSON', query=query)
  144. title = str_or_none(data.get('Title')) or re.sub(
  145. r'\s*\|\s*(?:TV\s*\|\s*DR|DRTV)$', '',
  146. self._og_search_title(webpage))
  147. description = self._og_search_description(
  148. webpage, default=None) or data.get('Description')
  149. timestamp = unified_timestamp(
  150. data.get('PrimaryBroadcastStartTime') or data.get('SortDateTime'))
  151. thumbnail = None
  152. duration = None
  153. restricted_to_denmark = False
  154. formats = []
  155. subtitles = {}
  156. assets = []
  157. primary_asset = data.get('PrimaryAsset')
  158. if isinstance(primary_asset, dict):
  159. assets.append(primary_asset)
  160. secondary_assets = data.get('SecondaryAssets')
  161. if isinstance(secondary_assets, list):
  162. for secondary_asset in secondary_assets:
  163. if isinstance(secondary_asset, dict):
  164. assets.append(secondary_asset)
  165. def hex_to_bytes(hex):
  166. return binascii.a2b_hex(hex.encode('ascii'))
  167. def decrypt_uri(e):
  168. n = int(e[2:10], 16)
  169. a = e[10 + n:]
  170. data = bytes_to_intlist(hex_to_bytes(e[10:10 + n]))
  171. key = bytes_to_intlist(hashlib.sha256(
  172. ('%s:sRBzYNXBzkKgnjj8pGtkACch' % a).encode('utf-8')).digest())
  173. iv = bytes_to_intlist(hex_to_bytes(a))
  174. decrypted = aes_cbc_decrypt(data, key, iv)
  175. return intlist_to_bytes(
  176. decrypted[:-decrypted[-1]]).decode('utf-8').split('?')[0]
  177. for asset in assets:
  178. kind = asset.get('Kind')
  179. if kind == 'Image':
  180. thumbnail = url_or_none(asset.get('Uri'))
  181. elif kind in ('VideoResource', 'AudioResource'):
  182. duration = float_or_none(asset.get('DurationInMilliseconds'), 1000)
  183. restricted_to_denmark = asset.get('RestrictedToDenmark')
  184. asset_target = asset.get('Target')
  185. for link in asset.get('Links', []):
  186. uri = link.get('Uri')
  187. if not uri:
  188. encrypted_uri = link.get('EncryptedUri')
  189. if not encrypted_uri:
  190. continue
  191. try:
  192. uri = decrypt_uri(encrypted_uri)
  193. except Exception:
  194. self.report_warning(
  195. 'Unable to decrypt EncryptedUri', video_id)
  196. continue
  197. uri = url_or_none(uri)
  198. if not uri:
  199. continue
  200. target = link.get('Target')
  201. format_id = target or ''
  202. if asset_target in ('SpokenSubtitles', 'SignLanguage', 'VisuallyInterpreted'):
  203. preference = -1
  204. format_id += '-%s' % asset_target
  205. elif asset_target == 'Default':
  206. preference = 1
  207. else:
  208. preference = None
  209. if target == 'HDS':
  210. f4m_formats = self._extract_f4m_formats(
  211. uri + '?hdcore=3.3.0&plugin=aasp-3.3.0.99.43',
  212. video_id, preference, f4m_id=format_id, fatal=False)
  213. if kind == 'AudioResource':
  214. for f in f4m_formats:
  215. f['vcodec'] = 'none'
  216. formats.extend(f4m_formats)
  217. elif target == 'HLS':
  218. formats.extend(self._extract_m3u8_formats(
  219. uri, video_id, 'mp4', entry_protocol='m3u8_native',
  220. preference=preference, m3u8_id=format_id,
  221. fatal=False))
  222. else:
  223. bitrate = link.get('Bitrate')
  224. if bitrate:
  225. format_id += '-%s' % bitrate
  226. formats.append({
  227. 'url': uri,
  228. 'format_id': format_id,
  229. 'tbr': int_or_none(bitrate),
  230. 'ext': link.get('FileFormat'),
  231. 'vcodec': 'none' if kind == 'AudioResource' else None,
  232. 'preference': preference,
  233. })
  234. subtitles_list = asset.get('SubtitlesList') or asset.get('Subtitleslist')
  235. if isinstance(subtitles_list, list):
  236. LANGS = {
  237. 'Danish': 'da',
  238. }
  239. for subs in subtitles_list:
  240. if not isinstance(subs, dict):
  241. continue
  242. sub_uri = url_or_none(subs.get('Uri'))
  243. if not sub_uri:
  244. continue
  245. lang = subs.get('Language') or 'da'
  246. subtitles.setdefault(LANGS.get(lang, lang), []).append({
  247. 'url': sub_uri,
  248. 'ext': mimetype2ext(subs.get('MimeType')) or 'vtt'
  249. })
  250. if not formats and restricted_to_denmark:
  251. self.raise_geo_restricted(
  252. 'Unfortunately, DR is not allowed to show this program outside Denmark.',
  253. countries=self._GEO_COUNTRIES)
  254. self._sort_formats(formats)
  255. return {
  256. 'id': video_id,
  257. 'title': title,
  258. 'description': description,
  259. 'thumbnail': thumbnail,
  260. 'timestamp': timestamp,
  261. 'duration': duration,
  262. 'formats': formats,
  263. 'subtitles': subtitles,
  264. 'series': str_or_none(data.get('SeriesTitle')),
  265. 'season': str_or_none(data.get('SeasonTitle')),
  266. 'season_number': int_or_none(data.get('SeasonNumber')),
  267. 'season_id': str_or_none(data.get('SeasonUrn')),
  268. 'episode': str_or_none(data.get('EpisodeTitle')),
  269. 'episode_number': int_or_none(data.get('EpisodeNumber')),
  270. 'release_year': int_or_none(data.get('ProductionYear')),
  271. }
  272. class DRTVLiveIE(InfoExtractor):
  273. IE_NAME = 'drtv:live'
  274. _VALID_URL = r'https?://(?:www\.)?dr\.dk/(?:tv|TV)/live/(?P<id>[\da-z-]+)'
  275. _GEO_COUNTRIES = ['DK']
  276. _TEST = {
  277. 'url': 'https://www.dr.dk/tv/live/dr1',
  278. 'info_dict': {
  279. 'id': 'dr1',
  280. 'ext': 'mp4',
  281. 'title': 're:^DR1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  282. },
  283. 'params': {
  284. # m3u8 download
  285. 'skip_download': True,
  286. },
  287. }
  288. def _real_extract(self, url):
  289. channel_id = self._match_id(url)
  290. channel_data = self._download_json(
  291. 'https://www.dr.dk/mu-online/api/1.0/channel/' + channel_id,
  292. channel_id)
  293. title = self._live_title(channel_data['Title'])
  294. formats = []
  295. for streaming_server in channel_data.get('StreamingServers', []):
  296. server = streaming_server.get('Server')
  297. if not server:
  298. continue
  299. link_type = streaming_server.get('LinkType')
  300. for quality in streaming_server.get('Qualities', []):
  301. for stream in quality.get('Streams', []):
  302. stream_path = stream.get('Stream')
  303. if not stream_path:
  304. continue
  305. stream_url = update_url_query(
  306. '%s/%s' % (server, stream_path), {'b': ''})
  307. if link_type == 'HLS':
  308. formats.extend(self._extract_m3u8_formats(
  309. stream_url, channel_id, 'mp4',
  310. m3u8_id=link_type, fatal=False, live=True))
  311. elif link_type == 'HDS':
  312. formats.extend(self._extract_f4m_formats(update_url_query(
  313. '%s/%s' % (server, stream_path), {'hdcore': '3.7.0'}),
  314. channel_id, f4m_id=link_type, fatal=False))
  315. self._sort_formats(formats)
  316. return {
  317. 'id': channel_id,
  318. 'title': title,
  319. 'thumbnail': channel_data.get('PrimaryImageUri'),
  320. 'formats': formats,
  321. 'is_live': True,
  322. }