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.

305 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. 'url': 'https://www.dr.dk/radio/p4kbh/regionale-nyheder-kh4/p4-nyheder-2019-06-26-17-30-9',
  80. 'only_matching': True,
  81. }]
  82. def _real_extract(self, url):
  83. video_id = self._match_id(url)
  84. webpage = self._download_webpage(url, video_id)
  85. if '>Programmet er ikke længere tilgængeligt' in webpage:
  86. raise ExtractorError(
  87. 'Video %s is not available' % video_id, expected=True)
  88. video_id = self._search_regex(
  89. (r'data-(?:material-identifier|episode-slug)="([^"]+)"',
  90. r'data-resource="[^>"]+mu/programcard/expanded/([^"]+)"'),
  91. webpage, 'video id', default=None)
  92. if not video_id:
  93. video_id = compat_urllib_parse_unquote(self._search_regex(
  94. r'(urn(?:%3A|:)dr(?:%3A|:)mu(?:%3A|:)programcard(?:%3A|:)[\da-f]+)',
  95. webpage, 'urn'))
  96. data = self._download_json(
  97. 'https://www.dr.dk/mu-online/api/1.4/programcard/%s' % video_id,
  98. video_id, 'Downloading video JSON', query={'expanded': 'true'})
  99. title = str_or_none(data.get('Title')) or re.sub(
  100. r'\s*\|\s*(?:TV\s*\|\s*DR|DRTV)$', '',
  101. self._og_search_title(webpage))
  102. description = self._og_search_description(
  103. webpage, default=None) or data.get('Description')
  104. timestamp = unified_timestamp(
  105. data.get('PrimaryBroadcastStartTime') or data.get('SortDateTime'))
  106. thumbnail = None
  107. duration = None
  108. restricted_to_denmark = False
  109. formats = []
  110. subtitles = {}
  111. assets = []
  112. primary_asset = data.get('PrimaryAsset')
  113. if isinstance(primary_asset, dict):
  114. assets.append(primary_asset)
  115. secondary_assets = data.get('SecondaryAssets')
  116. if isinstance(secondary_assets, list):
  117. for secondary_asset in secondary_assets:
  118. if isinstance(secondary_asset, dict):
  119. assets.append(secondary_asset)
  120. def hex_to_bytes(hex):
  121. return binascii.a2b_hex(hex.encode('ascii'))
  122. def decrypt_uri(e):
  123. n = int(e[2:10], 16)
  124. a = e[10 + n:]
  125. data = bytes_to_intlist(hex_to_bytes(e[10:10 + n]))
  126. key = bytes_to_intlist(hashlib.sha256(
  127. ('%s:sRBzYNXBzkKgnjj8pGtkACch' % a).encode('utf-8')).digest())
  128. iv = bytes_to_intlist(hex_to_bytes(a))
  129. decrypted = aes_cbc_decrypt(data, key, iv)
  130. return intlist_to_bytes(
  131. decrypted[:-decrypted[-1]]).decode('utf-8').split('?')[0]
  132. for asset in assets:
  133. kind = asset.get('Kind')
  134. if kind == 'Image':
  135. thumbnail = url_or_none(asset.get('Uri'))
  136. elif kind in ('VideoResource', 'AudioResource'):
  137. duration = float_or_none(asset.get('DurationInMilliseconds'), 1000)
  138. restricted_to_denmark = asset.get('RestrictedToDenmark')
  139. asset_target = asset.get('Target')
  140. for link in asset.get('Links', []):
  141. uri = link.get('Uri')
  142. if not uri:
  143. encrypted_uri = link.get('EncryptedUri')
  144. if not encrypted_uri:
  145. continue
  146. try:
  147. uri = decrypt_uri(encrypted_uri)
  148. except Exception:
  149. self.report_warning(
  150. 'Unable to decrypt EncryptedUri', video_id)
  151. continue
  152. uri = url_or_none(uri)
  153. if not uri:
  154. continue
  155. target = link.get('Target')
  156. format_id = target or ''
  157. if asset_target in ('SpokenSubtitles', 'SignLanguage', 'VisuallyInterpreted'):
  158. preference = -1
  159. format_id += '-%s' % asset_target
  160. elif asset_target == 'Default':
  161. preference = 1
  162. else:
  163. preference = None
  164. if target == 'HDS':
  165. f4m_formats = self._extract_f4m_formats(
  166. uri + '?hdcore=3.3.0&plugin=aasp-3.3.0.99.43',
  167. video_id, preference, f4m_id=format_id, fatal=False)
  168. if kind == 'AudioResource':
  169. for f in f4m_formats:
  170. f['vcodec'] = 'none'
  171. formats.extend(f4m_formats)
  172. elif target == 'HLS':
  173. formats.extend(self._extract_m3u8_formats(
  174. uri, video_id, 'mp4', entry_protocol='m3u8_native',
  175. preference=preference, m3u8_id=format_id,
  176. fatal=False))
  177. else:
  178. bitrate = link.get('Bitrate')
  179. if bitrate:
  180. format_id += '-%s' % bitrate
  181. formats.append({
  182. 'url': uri,
  183. 'format_id': format_id,
  184. 'tbr': int_or_none(bitrate),
  185. 'ext': link.get('FileFormat'),
  186. 'vcodec': 'none' if kind == 'AudioResource' else None,
  187. 'preference': preference,
  188. })
  189. subtitles_list = asset.get('SubtitlesList') or asset.get('Subtitleslist')
  190. if isinstance(subtitles_list, list):
  191. LANGS = {
  192. 'Danish': 'da',
  193. }
  194. for subs in subtitles_list:
  195. if not isinstance(subs, dict):
  196. continue
  197. sub_uri = url_or_none(subs.get('Uri'))
  198. if not sub_uri:
  199. continue
  200. lang = subs.get('Language') or 'da'
  201. subtitles.setdefault(LANGS.get(lang, lang), []).append({
  202. 'url': sub_uri,
  203. 'ext': mimetype2ext(subs.get('MimeType')) or 'vtt'
  204. })
  205. if not formats and restricted_to_denmark:
  206. self.raise_geo_restricted(
  207. 'Unfortunately, DR is not allowed to show this program outside Denmark.',
  208. countries=self._GEO_COUNTRIES)
  209. self._sort_formats(formats)
  210. return {
  211. 'id': video_id,
  212. 'title': title,
  213. 'description': description,
  214. 'thumbnail': thumbnail,
  215. 'timestamp': timestamp,
  216. 'duration': duration,
  217. 'formats': formats,
  218. 'subtitles': subtitles,
  219. 'series': str_or_none(data.get('SeriesTitle')),
  220. 'season': str_or_none(data.get('SeasonTitle')),
  221. 'season_number': int_or_none(data.get('SeasonNumber')),
  222. 'season_id': str_or_none(data.get('SeasonUrn')),
  223. 'episode': str_or_none(data.get('EpisodeTitle')),
  224. 'episode_number': int_or_none(data.get('EpisodeNumber')),
  225. 'release_year': int_or_none(data.get('ProductionYear')),
  226. }
  227. class DRTVLiveIE(InfoExtractor):
  228. IE_NAME = 'drtv:live'
  229. _VALID_URL = r'https?://(?:www\.)?dr\.dk/(?:tv|TV)/live/(?P<id>[\da-z-]+)'
  230. _GEO_COUNTRIES = ['DK']
  231. _TEST = {
  232. 'url': 'https://www.dr.dk/tv/live/dr1',
  233. 'info_dict': {
  234. 'id': 'dr1',
  235. 'ext': 'mp4',
  236. 'title': 're:^DR1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  237. },
  238. 'params': {
  239. # m3u8 download
  240. 'skip_download': True,
  241. },
  242. }
  243. def _real_extract(self, url):
  244. channel_id = self._match_id(url)
  245. channel_data = self._download_json(
  246. 'https://www.dr.dk/mu-online/api/1.0/channel/' + channel_id,
  247. channel_id)
  248. title = self._live_title(channel_data['Title'])
  249. formats = []
  250. for streaming_server in channel_data.get('StreamingServers', []):
  251. server = streaming_server.get('Server')
  252. if not server:
  253. continue
  254. link_type = streaming_server.get('LinkType')
  255. for quality in streaming_server.get('Qualities', []):
  256. for stream in quality.get('Streams', []):
  257. stream_path = stream.get('Stream')
  258. if not stream_path:
  259. continue
  260. stream_url = update_url_query(
  261. '%s/%s' % (server, stream_path), {'b': ''})
  262. if link_type == 'HLS':
  263. formats.extend(self._extract_m3u8_formats(
  264. stream_url, channel_id, 'mp4',
  265. m3u8_id=link_type, fatal=False, live=True))
  266. elif link_type == 'HDS':
  267. formats.extend(self._extract_f4m_formats(update_url_query(
  268. '%s/%s' % (server, stream_path), {'hdcore': '3.7.0'}),
  269. channel_id, f4m_id=link_type, fatal=False))
  270. self._sort_formats(formats)
  271. return {
  272. 'id': channel_id,
  273. 'title': title,
  274. 'thumbnail': channel_data.get('PrimaryImageUri'),
  275. 'formats': formats,
  276. 'is_live': True,
  277. }