drtv.py 14 KB

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