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.

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