logo

youtube-dl

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

ard.py (18910B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. from .common import InfoExtractor
  6. from .generic import GenericIE
  7. from ..utils import (
  8. determine_ext,
  9. ExtractorError,
  10. int_or_none,
  11. parse_duration,
  12. qualities,
  13. str_or_none,
  14. try_get,
  15. unified_strdate,
  16. unified_timestamp,
  17. update_url_query,
  18. url_or_none,
  19. xpath_text,
  20. )
  21. from ..compat import compat_etree_fromstring
  22. class ARDMediathekBaseIE(InfoExtractor):
  23. _GEO_COUNTRIES = ['DE']
  24. def _extract_media_info(self, media_info_url, webpage, video_id):
  25. media_info = self._download_json(
  26. media_info_url, video_id, 'Downloading media JSON')
  27. return self._parse_media_info(media_info, video_id, '"fsk"' in webpage)
  28. def _parse_media_info(self, media_info, video_id, fsk):
  29. formats = self._extract_formats(media_info, video_id)
  30. if not formats:
  31. if fsk:
  32. raise ExtractorError(
  33. 'This video is only available after 20:00', expected=True)
  34. elif media_info.get('_geoblocked'):
  35. self.raise_geo_restricted(
  36. 'This video is not available due to geoblocking',
  37. countries=self._GEO_COUNTRIES)
  38. self._sort_formats(formats)
  39. subtitles = {}
  40. subtitle_url = media_info.get('_subtitleUrl')
  41. if subtitle_url:
  42. subtitles['de'] = [{
  43. 'ext': 'ttml',
  44. 'url': subtitle_url,
  45. }]
  46. return {
  47. 'id': video_id,
  48. 'duration': int_or_none(media_info.get('_duration')),
  49. 'thumbnail': media_info.get('_previewImage'),
  50. 'is_live': media_info.get('_isLive') is True,
  51. 'formats': formats,
  52. 'subtitles': subtitles,
  53. }
  54. def _extract_formats(self, media_info, video_id):
  55. type_ = media_info.get('_type')
  56. media_array = media_info.get('_mediaArray', [])
  57. formats = []
  58. for num, media in enumerate(media_array):
  59. for stream in media.get('_mediaStreamArray', []):
  60. stream_urls = stream.get('_stream')
  61. if not stream_urls:
  62. continue
  63. if not isinstance(stream_urls, list):
  64. stream_urls = [stream_urls]
  65. quality = stream.get('_quality')
  66. server = stream.get('_server')
  67. for stream_url in stream_urls:
  68. if not url_or_none(stream_url):
  69. continue
  70. ext = determine_ext(stream_url)
  71. if quality != 'auto' and ext in ('f4m', 'm3u8'):
  72. continue
  73. if ext == 'f4m':
  74. formats.extend(self._extract_f4m_formats(
  75. update_url_query(stream_url, {
  76. 'hdcore': '3.1.1',
  77. 'plugin': 'aasp-3.1.1.69.124'
  78. }), video_id, f4m_id='hds', fatal=False))
  79. elif ext == 'm3u8':
  80. formats.extend(self._extract_m3u8_formats(
  81. stream_url, video_id, 'mp4', 'm3u8_native',
  82. m3u8_id='hls', fatal=False))
  83. else:
  84. if server and server.startswith('rtmp'):
  85. f = {
  86. 'url': server,
  87. 'play_path': stream_url,
  88. 'format_id': 'a%s-rtmp-%s' % (num, quality),
  89. }
  90. else:
  91. f = {
  92. 'url': stream_url,
  93. 'format_id': 'a%s-%s-%s' % (num, ext, quality)
  94. }
  95. m = re.search(
  96. r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$',
  97. stream_url)
  98. if m:
  99. f.update({
  100. 'width': int(m.group('width')),
  101. 'height': int(m.group('height')),
  102. })
  103. if type_ == 'audio':
  104. f['vcodec'] = 'none'
  105. formats.append(f)
  106. return formats
  107. class ARDMediathekIE(ARDMediathekBaseIE):
  108. IE_NAME = 'ARD:mediathek'
  109. _VALID_URL = r'^https?://(?:(?:(?:www|classic)\.)?ardmediathek\.de|mediathek\.(?:daserste|rbb-online)\.de|one\.ard\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?'
  110. _TESTS = [{
  111. # available till 26.07.2022
  112. 'url': 'http://www.ardmediathek.de/tv/S%C3%9CDLICHT/Was-ist-die-Kunst-der-Zukunft-liebe-Ann/BR-Fernsehen/Video?bcastId=34633636&documentId=44726822',
  113. 'info_dict': {
  114. 'id': '44726822',
  115. 'ext': 'mp4',
  116. 'title': 'Was ist die Kunst der Zukunft, liebe Anna McCarthy?',
  117. 'description': 'md5:4ada28b3e3b5df01647310e41f3a62f5',
  118. 'duration': 1740,
  119. },
  120. 'params': {
  121. # m3u8 download
  122. 'skip_download': True,
  123. }
  124. }, {
  125. 'url': 'https://one.ard.de/tv/Mord-mit-Aussicht/Mord-mit-Aussicht-6-39-T%C3%B6dliche-Nach/ONE/Video?bcastId=46384294&documentId=55586872',
  126. 'only_matching': True,
  127. }, {
  128. # audio
  129. 'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086',
  130. 'only_matching': True,
  131. }, {
  132. 'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht',
  133. 'only_matching': True,
  134. }, {
  135. # audio
  136. 'url': 'http://mediathek.rbb-online.de/radio/Hörspiel/Vor-dem-Fest/kulturradio/Audio?documentId=30796318&topRessort=radio&bcastId=9839158',
  137. 'only_matching': True,
  138. }, {
  139. 'url': 'https://classic.ardmediathek.de/tv/Panda-Gorilla-Co/Panda-Gorilla-Co-Folge-274/Das-Erste/Video?bcastId=16355486&documentId=58234698',
  140. 'only_matching': True,
  141. }]
  142. @classmethod
  143. def suitable(cls, url):
  144. return False if ARDBetaMediathekIE.suitable(url) else super(ARDMediathekIE, cls).suitable(url)
  145. def _real_extract(self, url):
  146. # determine video id from url
  147. m = re.match(self._VALID_URL, url)
  148. document_id = None
  149. numid = re.search(r'documentId=([0-9]+)', url)
  150. if numid:
  151. document_id = video_id = numid.group(1)
  152. else:
  153. video_id = m.group('video_id')
  154. webpage = self._download_webpage(url, video_id)
  155. ERRORS = (
  156. ('>Leider liegt eine Störung vor.', 'Video %s is unavailable'),
  157. ('>Der gewünschte Beitrag ist nicht mehr verfügbar.<',
  158. 'Video %s is no longer available'),
  159. )
  160. for pattern, message in ERRORS:
  161. if pattern in webpage:
  162. raise ExtractorError(message % video_id, expected=True)
  163. if re.search(r'[\?&]rss($|[=&])', url):
  164. doc = compat_etree_fromstring(webpage.encode('utf-8'))
  165. if doc.tag == 'rss':
  166. return GenericIE()._extract_rss(url, video_id, doc)
  167. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  168. [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>',
  169. r'<meta name="dcterms\.title" content="(.*?)"/>',
  170. r'<h4 class="headline">(.*?)</h4>',
  171. r'<title[^>]*>(.*?)</title>'],
  172. webpage, 'title')
  173. description = self._og_search_description(webpage, default=None) or self._html_search_meta(
  174. 'dcterms.abstract', webpage, 'description', default=None)
  175. if description is None:
  176. description = self._html_search_meta(
  177. 'description', webpage, 'meta description', default=None)
  178. if description is None:
  179. description = self._html_search_regex(
  180. r'<p\s+class="teasertext">(.+?)</p>',
  181. webpage, 'teaser text', default=None)
  182. # Thumbnail is sometimes not present.
  183. # It is in the mobile version, but that seems to use a different URL
  184. # structure altogether.
  185. thumbnail = self._og_search_thumbnail(webpage, default=None)
  186. media_streams = re.findall(r'''(?x)
  187. mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s*
  188. "([^"]+)"''', webpage)
  189. if media_streams:
  190. QUALITIES = qualities(['lo', 'hi', 'hq'])
  191. formats = []
  192. for furl in set(media_streams):
  193. if furl.endswith('.f4m'):
  194. fid = 'f4m'
  195. else:
  196. fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl)
  197. fid = fid_m.group(1) if fid_m else None
  198. formats.append({
  199. 'quality': QUALITIES(fid),
  200. 'format_id': fid,
  201. 'url': furl,
  202. })
  203. self._sort_formats(formats)
  204. info = {
  205. 'formats': formats,
  206. }
  207. else: # request JSON file
  208. if not document_id:
  209. video_id = self._search_regex(
  210. r'/play/(?:config|media)/(\d+)', webpage, 'media id')
  211. info = self._extract_media_info(
  212. 'http://www.ardmediathek.de/play/media/%s' % video_id,
  213. webpage, video_id)
  214. info.update({
  215. 'id': video_id,
  216. 'title': self._live_title(title) if info.get('is_live') else title,
  217. 'description': description,
  218. 'thumbnail': thumbnail,
  219. })
  220. return info
  221. class ARDIE(InfoExtractor):
  222. _VALID_URL = r'(?P<mainurl>https?://(?:www\.)?daserste\.de/(?:[^/?#&]+/)+(?P<id>[^/?#&]+))\.html'
  223. _TESTS = [{
  224. # available till 7.01.2022
  225. 'url': 'https://www.daserste.de/information/talk/maischberger/videos/maischberger-die-woche-video100.html',
  226. 'md5': '867d8aa39eeaf6d76407c5ad1bb0d4c1',
  227. 'info_dict': {
  228. 'id': 'maischberger-die-woche-video100',
  229. 'display_id': 'maischberger-die-woche-video100',
  230. 'ext': 'mp4',
  231. 'duration': 3687.0,
  232. 'title': 'maischberger. die woche vom 7. Januar 2021',
  233. 'upload_date': '20210107',
  234. 'thumbnail': r're:^https?://.*\.jpg$',
  235. },
  236. }, {
  237. 'url': 'https://www.daserste.de/information/politik-weltgeschehen/morgenmagazin/videosextern/dominik-kahun-aus-der-nhl-direkt-zur-weltmeisterschaft-100.html',
  238. 'only_matching': True,
  239. }, {
  240. 'url': 'https://www.daserste.de/information/nachrichten-wetter/tagesthemen/videosextern/tagesthemen-17736.html',
  241. 'only_matching': True,
  242. }, {
  243. 'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
  244. 'only_matching': True,
  245. }, {
  246. 'url': 'https://www.daserste.de/unterhaltung/serie/in-aller-freundschaft-die-jungen-aerzte/Drehpause-100.html',
  247. 'only_matching': True,
  248. }, {
  249. 'url': 'https://www.daserste.de/unterhaltung/film/filmmittwoch-im-ersten/videos/making-ofwendezeit-video-100.html',
  250. 'only_matching': True,
  251. }]
  252. def _real_extract(self, url):
  253. mobj = re.match(self._VALID_URL, url)
  254. display_id = mobj.group('id')
  255. player_url = mobj.group('mainurl') + '~playerXml.xml'
  256. doc = self._download_xml(player_url, display_id)
  257. video_node = doc.find('./video')
  258. upload_date = unified_strdate(xpath_text(
  259. video_node, './broadcastDate'))
  260. thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
  261. formats = []
  262. for a in video_node.findall('.//asset'):
  263. file_name = xpath_text(a, './fileName', default=None)
  264. if not file_name:
  265. continue
  266. format_type = a.attrib.get('type')
  267. format_url = url_or_none(file_name)
  268. if format_url:
  269. ext = determine_ext(file_name)
  270. if ext == 'm3u8':
  271. formats.extend(self._extract_m3u8_formats(
  272. format_url, display_id, 'mp4', entry_protocol='m3u8_native',
  273. m3u8_id=format_type or 'hls', fatal=False))
  274. continue
  275. elif ext == 'f4m':
  276. formats.extend(self._extract_f4m_formats(
  277. update_url_query(format_url, {'hdcore': '3.7.0'}),
  278. display_id, f4m_id=format_type or 'hds', fatal=False))
  279. continue
  280. f = {
  281. 'format_id': format_type,
  282. 'width': int_or_none(xpath_text(a, './frameWidth')),
  283. 'height': int_or_none(xpath_text(a, './frameHeight')),
  284. 'vbr': int_or_none(xpath_text(a, './bitrateVideo')),
  285. 'abr': int_or_none(xpath_text(a, './bitrateAudio')),
  286. 'vcodec': xpath_text(a, './codecVideo'),
  287. 'tbr': int_or_none(xpath_text(a, './totalBitrate')),
  288. }
  289. server_prefix = xpath_text(a, './serverPrefix', default=None)
  290. if server_prefix:
  291. f.update({
  292. 'url': server_prefix,
  293. 'playpath': file_name,
  294. })
  295. else:
  296. if not format_url:
  297. continue
  298. f['url'] = format_url
  299. formats.append(f)
  300. self._sort_formats(formats)
  301. _SUB_FORMATS = (
  302. ('./dataTimedText', 'ttml'),
  303. ('./dataTimedTextNoOffset', 'ttml'),
  304. ('./dataTimedTextVtt', 'vtt'),
  305. )
  306. subtitles = {}
  307. for subsel, subext in _SUB_FORMATS:
  308. for node in video_node.findall(subsel):
  309. subtitles.setdefault('de', []).append({
  310. 'url': node.attrib['url'],
  311. 'ext': subext,
  312. })
  313. return {
  314. 'id': xpath_text(video_node, './videoId', default=display_id),
  315. 'formats': formats,
  316. 'subtitles': subtitles,
  317. 'display_id': display_id,
  318. 'title': video_node.find('./title').text,
  319. 'duration': parse_duration(video_node.find('./duration').text),
  320. 'upload_date': upload_date,
  321. 'thumbnail': thumbnail,
  322. }
  323. class ARDBetaMediathekIE(ARDMediathekBaseIE):
  324. _VALID_URL = r'https://(?:(?:beta|www)\.)?ardmediathek\.de/(?:[^/]+/)?(?:player|live|video)/(?:[^/]+/)*(?P<id>Y3JpZDovL[a-zA-Z0-9]+)'
  325. _TESTS = [{
  326. 'url': 'https://www.ardmediathek.de/mdr/video/die-robuste-roswita/Y3JpZDovL21kci5kZS9iZWl0cmFnL2Ntcy84MWMxN2MzZC0wMjkxLTRmMzUtODk4ZS0wYzhlOWQxODE2NGI/',
  327. 'md5': 'a1dc75a39c61601b980648f7c9f9f71d',
  328. 'info_dict': {
  329. 'display_id': 'die-robuste-roswita',
  330. 'id': '78566716',
  331. 'title': 'Die robuste Roswita',
  332. 'description': r're:^Der Mord.*totgeglaubte Ehefrau Roswita',
  333. 'duration': 5316,
  334. 'thumbnail': 'https://img.ardmediathek.de/standard/00/78/56/67/84/575672121/16x9/960?mandant=ard',
  335. 'timestamp': 1596658200,
  336. 'upload_date': '20200805',
  337. 'ext': 'mp4',
  338. },
  339. }, {
  340. 'url': 'https://beta.ardmediathek.de/ard/video/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE',
  341. 'only_matching': True,
  342. }, {
  343. 'url': 'https://ardmediathek.de/ard/video/saartalk/saartalk-gesellschaftsgift-haltung-gegen-hass/sr-fernsehen/Y3JpZDovL3NyLW9ubGluZS5kZS9TVF84MTY4MA/',
  344. 'only_matching': True,
  345. }, {
  346. 'url': 'https://www.ardmediathek.de/ard/video/trailer/private-eyes-s01-e01/one/Y3JpZDovL3dkci5kZS9CZWl0cmFnLTE1MTgwYzczLWNiMTEtNGNkMS1iMjUyLTg5MGYzOWQxZmQ1YQ/',
  347. 'only_matching': True,
  348. }, {
  349. 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3N3ci5kZS9hZXgvbzEwNzE5MTU/',
  350. 'only_matching': True,
  351. }, {
  352. 'url': 'https://www.ardmediathek.de/swr/live/Y3JpZDovL3N3ci5kZS8xMzQ4MTA0Mg',
  353. 'only_matching': True,
  354. }, {
  355. 'url': 'https://www.ardmediathek.de/video/coronavirus-update-ndr-info/astrazeneca-kurz-lockdown-und-pims-syndrom-81/ndr/Y3JpZDovL25kci5kZS84NzE0M2FjNi0wMWEwLTQ5ODEtOTE5NS1mOGZhNzdhOTFmOTI/',
  356. 'only_matching': True,
  357. }, {
  358. 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3dkci5kZS9CZWl0cmFnLWQ2NDJjYWEzLTMwZWYtNGI4NS1iMTI2LTU1N2UxYTcxOGIzOQ/tatort-duo-koeln-leipzig-ihr-kinderlein-kommet',
  359. 'only_matching': True,
  360. }]
  361. def _real_extract(self, url):
  362. video_id = self._match_id(url)
  363. player_page = self._download_json(
  364. 'https://api.ardmediathek.de/public-gateway',
  365. video_id, data=json.dumps({
  366. 'query': '''{
  367. playerPage(client: "ard", clipId: "%s") {
  368. blockedByFsk
  369. broadcastedOn
  370. maturityContentRating
  371. mediaCollection {
  372. _duration
  373. _geoblocked
  374. _isLive
  375. _mediaArray {
  376. _mediaStreamArray {
  377. _quality
  378. _server
  379. _stream
  380. }
  381. }
  382. _previewImage
  383. _subtitleUrl
  384. _type
  385. }
  386. show {
  387. title
  388. }
  389. synopsis
  390. title
  391. tracking {
  392. atiCustomVars {
  393. contentId
  394. }
  395. }
  396. }
  397. }''' % video_id,
  398. }).encode(), headers={
  399. 'Content-Type': 'application/json'
  400. })['data']['playerPage']
  401. title = player_page['title']
  402. content_id = str_or_none(try_get(
  403. player_page, lambda x: x['tracking']['atiCustomVars']['contentId']))
  404. media_collection = player_page.get('mediaCollection') or {}
  405. if not media_collection and content_id:
  406. media_collection = self._download_json(
  407. 'https://www.ardmediathek.de/play/media/' + content_id,
  408. content_id, fatal=False) or {}
  409. info = self._parse_media_info(
  410. media_collection, content_id or video_id,
  411. player_page.get('blockedByFsk'))
  412. age_limit = None
  413. description = player_page.get('synopsis')
  414. maturity_content_rating = player_page.get('maturityContentRating')
  415. if maturity_content_rating:
  416. age_limit = int_or_none(maturity_content_rating.lstrip('FSK'))
  417. if not age_limit and description:
  418. age_limit = int_or_none(self._search_regex(
  419. r'\(FSK\s*(\d+)\)\s*$', description, 'age limit', default=None))
  420. info.update({
  421. 'age_limit': age_limit,
  422. 'title': title,
  423. 'description': description,
  424. 'timestamp': unified_timestamp(player_page.get('broadcastedOn')),
  425. 'series': try_get(player_page, lambda x: x['show']['title']),
  426. })
  427. return info