ard.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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/[^?#]+/videos(?:extern)?/(?P<display_id>[^/?#]+)-(?:video-?)?(?P<id>[0-9]+))\.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. 'display_id': 'maischberger-die-woche',
  229. 'id': '100',
  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/reportage-dokumentation/erlebnis-erde/videosextern/woelfe-und-herdenschutzhunde-ungleiche-brueder-102.html',
  238. 'only_matching': True,
  239. }, {
  240. 'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
  241. 'only_matching': True,
  242. }]
  243. def _real_extract(self, url):
  244. mobj = re.match(self._VALID_URL, url)
  245. display_id = mobj.group('display_id')
  246. player_url = mobj.group('mainurl') + '~playerXml.xml'
  247. doc = self._download_xml(player_url, display_id)
  248. video_node = doc.find('./video')
  249. upload_date = unified_strdate(xpath_text(
  250. video_node, './broadcastDate'))
  251. thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
  252. formats = []
  253. for a in video_node.findall('.//asset'):
  254. file_name = xpath_text(a, './fileName', default=None)
  255. if not file_name:
  256. continue
  257. format_type = a.attrib.get('type')
  258. format_url = url_or_none(file_name)
  259. if format_url:
  260. ext = determine_ext(file_name)
  261. if ext == 'm3u8':
  262. formats.extend(self._extract_m3u8_formats(
  263. format_url, display_id, 'mp4', entry_protocol='m3u8_native',
  264. m3u8_id=format_type or 'hls', fatal=False))
  265. continue
  266. elif ext == 'f4m':
  267. formats.extend(self._extract_f4m_formats(
  268. update_url_query(format_url, {'hdcore': '3.7.0'}),
  269. display_id, f4m_id=format_type or 'hds', fatal=False))
  270. continue
  271. f = {
  272. 'format_id': format_type,
  273. 'width': int_or_none(xpath_text(a, './frameWidth')),
  274. 'height': int_or_none(xpath_text(a, './frameHeight')),
  275. 'vbr': int_or_none(xpath_text(a, './bitrateVideo')),
  276. 'abr': int_or_none(xpath_text(a, './bitrateAudio')),
  277. 'vcodec': xpath_text(a, './codecVideo'),
  278. 'tbr': int_or_none(xpath_text(a, './totalBitrate')),
  279. }
  280. server_prefix = xpath_text(a, './serverPrefix', default=None)
  281. if server_prefix:
  282. f.update({
  283. 'url': server_prefix,
  284. 'playpath': file_name,
  285. })
  286. else:
  287. if not format_url:
  288. continue
  289. f['url'] = format_url
  290. formats.append(f)
  291. self._sort_formats(formats)
  292. return {
  293. 'id': mobj.group('id'),
  294. 'formats': formats,
  295. 'display_id': display_id,
  296. 'title': video_node.find('./title').text,
  297. 'duration': parse_duration(video_node.find('./duration').text),
  298. 'upload_date': upload_date,
  299. 'thumbnail': thumbnail,
  300. }
  301. class ARDBetaMediathekIE(ARDMediathekBaseIE):
  302. _VALID_URL = r'https://(?:(?:beta|www)\.)?ardmediathek\.de/(?:[^/]+/)?(?:player|live|video)/(?:[^/]+/)*(?P<id>Y3JpZDovL[a-zA-Z0-9]+)'
  303. _TESTS = [{
  304. 'url': 'https://www.ardmediathek.de/mdr/video/die-robuste-roswita/Y3JpZDovL21kci5kZS9iZWl0cmFnL2Ntcy84MWMxN2MzZC0wMjkxLTRmMzUtODk4ZS0wYzhlOWQxODE2NGI/',
  305. 'md5': 'a1dc75a39c61601b980648f7c9f9f71d',
  306. 'info_dict': {
  307. 'display_id': 'die-robuste-roswita',
  308. 'id': '78566716',
  309. 'title': 'Die robuste Roswita',
  310. 'description': r're:^Der Mord.*totgeglaubte Ehefrau Roswita',
  311. 'duration': 5316,
  312. 'thumbnail': 'https://img.ardmediathek.de/standard/00/78/56/67/84/575672121/16x9/960?mandant=ard',
  313. 'timestamp': 1596658200,
  314. 'upload_date': '20200805',
  315. 'ext': 'mp4',
  316. },
  317. }, {
  318. 'url': 'https://beta.ardmediathek.de/ard/video/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE',
  319. 'only_matching': True,
  320. }, {
  321. 'url': 'https://ardmediathek.de/ard/video/saartalk/saartalk-gesellschaftsgift-haltung-gegen-hass/sr-fernsehen/Y3JpZDovL3NyLW9ubGluZS5kZS9TVF84MTY4MA/',
  322. 'only_matching': True,
  323. }, {
  324. 'url': 'https://www.ardmediathek.de/ard/video/trailer/private-eyes-s01-e01/one/Y3JpZDovL3dkci5kZS9CZWl0cmFnLTE1MTgwYzczLWNiMTEtNGNkMS1iMjUyLTg5MGYzOWQxZmQ1YQ/',
  325. 'only_matching': True,
  326. }, {
  327. 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3N3ci5kZS9hZXgvbzEwNzE5MTU/',
  328. 'only_matching': True,
  329. }, {
  330. 'url': 'https://www.ardmediathek.de/swr/live/Y3JpZDovL3N3ci5kZS8xMzQ4MTA0Mg',
  331. 'only_matching': True,
  332. }, {
  333. 'url': 'https://www.ardmediathek.de/video/coronavirus-update-ndr-info/astrazeneca-kurz-lockdown-und-pims-syndrom-81/ndr/Y3JpZDovL25kci5kZS84NzE0M2FjNi0wMWEwLTQ5ODEtOTE5NS1mOGZhNzdhOTFmOTI/',
  334. 'only_matching': True,
  335. }, {
  336. 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3dkci5kZS9CZWl0cmFnLWQ2NDJjYWEzLTMwZWYtNGI4NS1iMTI2LTU1N2UxYTcxOGIzOQ/tatort-duo-koeln-leipzig-ihr-kinderlein-kommet',
  337. 'only_matching': True,
  338. }]
  339. def _real_extract(self, url):
  340. video_id = self._match_id(url)
  341. player_page = self._download_json(
  342. 'https://api.ardmediathek.de/public-gateway',
  343. video_id, data=json.dumps({
  344. 'query': '''{
  345. playerPage(client: "ard", clipId: "%s") {
  346. blockedByFsk
  347. broadcastedOn
  348. maturityContentRating
  349. mediaCollection {
  350. _duration
  351. _geoblocked
  352. _isLive
  353. _mediaArray {
  354. _mediaStreamArray {
  355. _quality
  356. _server
  357. _stream
  358. }
  359. }
  360. _previewImage
  361. _subtitleUrl
  362. _type
  363. }
  364. show {
  365. title
  366. }
  367. synopsis
  368. title
  369. tracking {
  370. atiCustomVars {
  371. contentId
  372. }
  373. }
  374. }
  375. }''' % video_id,
  376. }).encode(), headers={
  377. 'Content-Type': 'application/json'
  378. })['data']['playerPage']
  379. title = player_page['title']
  380. content_id = str_or_none(try_get(
  381. player_page, lambda x: x['tracking']['atiCustomVars']['contentId']))
  382. media_collection = player_page.get('mediaCollection') or {}
  383. if not media_collection and content_id:
  384. media_collection = self._download_json(
  385. 'https://www.ardmediathek.de/play/media/' + content_id,
  386. content_id, fatal=False) or {}
  387. info = self._parse_media_info(
  388. media_collection, content_id or video_id,
  389. player_page.get('blockedByFsk'))
  390. age_limit = None
  391. description = player_page.get('synopsis')
  392. maturity_content_rating = player_page.get('maturityContentRating')
  393. if maturity_content_rating:
  394. age_limit = int_or_none(maturity_content_rating.lstrip('FSK'))
  395. if not age_limit and description:
  396. age_limit = int_or_none(self._search_regex(
  397. r'\(FSK\s*(\d+)\)\s*$', description, 'age limit', default=None))
  398. info.update({
  399. 'age_limit': age_limit,
  400. 'title': title,
  401. 'description': description,
  402. 'timestamp': unified_timestamp(player_page.get('broadcastedOn')),
  403. 'series': try_get(player_page, lambda x: x['show']['title']),
  404. })
  405. return info