logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

drtv.py (13913B)


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