ard.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. import json
  2. import re
  3. from .common import InfoExtractor
  4. from .generic import GenericIE
  5. from ..utils import (
  6. determine_ext,
  7. ExtractorError,
  8. int_or_none,
  9. parse_duration,
  10. qualities,
  11. str_or_none,
  12. try_get,
  13. unified_strdate,
  14. unified_timestamp,
  15. update_url_query,
  16. url_or_none,
  17. xpath_text,
  18. )
  19. from ..compat import compat_etree_fromstring
  20. class ARDMediathekBaseIE(InfoExtractor):
  21. _GEO_COUNTRIES = ['DE']
  22. def _extract_media_info(self, media_info_url, webpage, video_id):
  23. media_info = self._download_json(
  24. media_info_url, video_id, 'Downloading media JSON')
  25. return self._parse_media_info(media_info, video_id, '"fsk"' in webpage)
  26. def _parse_media_info(self, media_info, video_id, fsk):
  27. formats = self._extract_formats(media_info, video_id)
  28. if not formats:
  29. if fsk:
  30. self.raise_no_formats(
  31. 'This video is only available after 20:00', expected=True)
  32. elif media_info.get('_geoblocked'):
  33. self.raise_geo_restricted(
  34. 'This video is not available due to geoblocking',
  35. countries=self._GEO_COUNTRIES, metadata_available=True)
  36. subtitles = {}
  37. subtitle_url = media_info.get('_subtitleUrl')
  38. if subtitle_url:
  39. subtitles['de'] = [{
  40. 'ext': 'ttml',
  41. 'url': subtitle_url,
  42. }]
  43. return {
  44. 'id': video_id,
  45. 'duration': int_or_none(media_info.get('_duration')),
  46. 'thumbnail': media_info.get('_previewImage'),
  47. 'is_live': media_info.get('_isLive') is True,
  48. 'formats': formats,
  49. 'subtitles': subtitles,
  50. }
  51. def _ARD_extract_episode_info(self, title):
  52. """Try to extract season/episode data from the title."""
  53. res = {}
  54. if not title:
  55. return res
  56. for pattern in [
  57. # Pattern for title like "Homo sapiens (S06/E07) - Originalversion"
  58. # from: https://www.ardmediathek.de/one/sendung/doctor-who/Y3JpZDovL3dkci5kZS9vbmUvZG9jdG9yIHdobw
  59. r'.*(?P<ep_info> \(S(?P<season_number>\d+)/E(?P<episode_number>\d+)\)).*',
  60. # E.g.: title="Fritjof aus Norwegen (2) (AD)"
  61. # from: https://www.ardmediathek.de/ard/sammlung/der-krieg-und-ich/68cMkqJdllm639Skj4c7sS/
  62. r'.*(?P<ep_info> \((?:Folge |Teil )?(?P<episode_number>\d+)(?:/\d+)?\)).*',
  63. r'.*(?P<ep_info>Folge (?P<episode_number>\d+)(?:\:| -|) )\"(?P<episode>.+)\".*',
  64. # E.g.: title="Folge 25/42: Symmetrie"
  65. # from: https://www.ardmediathek.de/ard/video/grips-mathe/folge-25-42-symmetrie/ard-alpha/Y3JpZDovL2JyLmRlL3ZpZGVvLzMyYzI0ZjczLWQ1N2MtNDAxNC05ZmZhLTFjYzRkZDA5NDU5OQ/
  66. # E.g.: title="Folge 1063 - Vertrauen"
  67. # from: https://www.ardmediathek.de/ard/sendung/die-fallers/Y3JpZDovL3N3ci5kZS8yMzAyMDQ4/
  68. r'.*(?P<ep_info>Folge (?P<episode_number>\d+)(?:/\d+)?(?:\:| -|) ).*',
  69. ]:
  70. m = re.match(pattern, title)
  71. if m:
  72. groupdict = m.groupdict()
  73. res['season_number'] = int_or_none(groupdict.get('season_number'))
  74. res['episode_number'] = int_or_none(groupdict.get('episode_number'))
  75. res['episode'] = str_or_none(groupdict.get('episode'))
  76. # Build the episode title by removing numeric episode information:
  77. if groupdict.get('ep_info') and not res['episode']:
  78. res['episode'] = str_or_none(
  79. title.replace(groupdict.get('ep_info'), ''))
  80. if res['episode']:
  81. res['episode'] = res['episode'].strip()
  82. break
  83. # As a fallback use the whole title as the episode name:
  84. if not res.get('episode'):
  85. res['episode'] = title.strip()
  86. return res
  87. def _extract_formats(self, media_info, video_id):
  88. type_ = media_info.get('_type')
  89. media_array = media_info.get('_mediaArray', [])
  90. formats = []
  91. for num, media in enumerate(media_array):
  92. for stream in media.get('_mediaStreamArray', []):
  93. stream_urls = stream.get('_stream')
  94. if not stream_urls:
  95. continue
  96. if not isinstance(stream_urls, list):
  97. stream_urls = [stream_urls]
  98. quality = stream.get('_quality')
  99. server = stream.get('_server')
  100. for stream_url in stream_urls:
  101. if not url_or_none(stream_url):
  102. continue
  103. ext = determine_ext(stream_url)
  104. if quality != 'auto' and ext in ('f4m', 'm3u8'):
  105. continue
  106. if ext == 'f4m':
  107. formats.extend(self._extract_f4m_formats(
  108. update_url_query(stream_url, {
  109. 'hdcore': '3.1.1',
  110. 'plugin': 'aasp-3.1.1.69.124'
  111. }), video_id, f4m_id='hds', fatal=False))
  112. elif ext == 'm3u8':
  113. formats.extend(self._extract_m3u8_formats(
  114. stream_url, video_id, 'mp4', 'm3u8_native',
  115. m3u8_id='hls', fatal=False))
  116. else:
  117. if server and server.startswith('rtmp'):
  118. f = {
  119. 'url': server,
  120. 'play_path': stream_url,
  121. 'format_id': 'a%s-rtmp-%s' % (num, quality),
  122. }
  123. else:
  124. f = {
  125. 'url': stream_url,
  126. 'format_id': 'a%s-%s-%s' % (num, ext, quality)
  127. }
  128. m = re.search(
  129. r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$',
  130. stream_url)
  131. if m:
  132. f.update({
  133. 'width': int(m.group('width')),
  134. 'height': int(m.group('height')),
  135. })
  136. if type_ == 'audio':
  137. f['vcodec'] = 'none'
  138. formats.append(f)
  139. return formats
  140. class ARDMediathekIE(ARDMediathekBaseIE):
  141. IE_NAME = 'ARD:mediathek'
  142. _VALID_URL = r'^https?://(?:(?:(?:www|classic)\.)?ardmediathek\.de|mediathek\.(?:daserste|rbb-online)\.de|one\.ard\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?'
  143. _TESTS = [{
  144. # available till 26.07.2022
  145. 'url': 'http://www.ardmediathek.de/tv/S%C3%9CDLICHT/Was-ist-die-Kunst-der-Zukunft-liebe-Ann/BR-Fernsehen/Video?bcastId=34633636&documentId=44726822',
  146. 'info_dict': {
  147. 'id': '44726822',
  148. 'ext': 'mp4',
  149. 'title': 'Was ist die Kunst der Zukunft, liebe Anna McCarthy?',
  150. 'description': 'md5:4ada28b3e3b5df01647310e41f3a62f5',
  151. 'duration': 1740,
  152. },
  153. 'params': {
  154. # m3u8 download
  155. 'skip_download': True,
  156. }
  157. }, {
  158. 'url': 'https://one.ard.de/tv/Mord-mit-Aussicht/Mord-mit-Aussicht-6-39-T%C3%B6dliche-Nach/ONE/Video?bcastId=46384294&documentId=55586872',
  159. 'only_matching': True,
  160. }, {
  161. # audio
  162. 'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086',
  163. 'only_matching': True,
  164. }, {
  165. 'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht',
  166. 'only_matching': True,
  167. }, {
  168. # audio
  169. 'url': 'http://mediathek.rbb-online.de/radio/Hörspiel/Vor-dem-Fest/kulturradio/Audio?documentId=30796318&topRessort=radio&bcastId=9839158',
  170. 'only_matching': True,
  171. }, {
  172. 'url': 'https://classic.ardmediathek.de/tv/Panda-Gorilla-Co/Panda-Gorilla-Co-Folge-274/Das-Erste/Video?bcastId=16355486&documentId=58234698',
  173. 'only_matching': True,
  174. }]
  175. @classmethod
  176. def suitable(cls, url):
  177. return False if ARDBetaMediathekIE.suitable(url) else super(ARDMediathekIE, cls).suitable(url)
  178. def _real_extract(self, url):
  179. # determine video id from url
  180. m = self._match_valid_url(url)
  181. document_id = None
  182. numid = re.search(r'documentId=([0-9]+)', url)
  183. if numid:
  184. document_id = video_id = numid.group(1)
  185. else:
  186. video_id = m.group('video_id')
  187. webpage = self._download_webpage(url, video_id)
  188. ERRORS = (
  189. ('>Leider liegt eine Störung vor.', 'Video %s is unavailable'),
  190. ('>Der gewünschte Beitrag ist nicht mehr verfügbar.<',
  191. 'Video %s is no longer available'),
  192. )
  193. for pattern, message in ERRORS:
  194. if pattern in webpage:
  195. raise ExtractorError(message % video_id, expected=True)
  196. if re.search(r'[\?&]rss($|[=&])', url):
  197. doc = compat_etree_fromstring(webpage.encode('utf-8'))
  198. if doc.tag == 'rss':
  199. return GenericIE()._extract_rss(url, video_id, doc)
  200. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  201. [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>',
  202. r'<meta name="dcterms\.title" content="(.*?)"/>',
  203. r'<h4 class="headline">(.*?)</h4>',
  204. r'<title[^>]*>(.*?)</title>'],
  205. webpage, 'title')
  206. description = self._og_search_description(webpage, default=None) or self._html_search_meta(
  207. 'dcterms.abstract', webpage, 'description', default=None)
  208. if description is None:
  209. description = self._html_search_meta(
  210. 'description', webpage, 'meta description', default=None)
  211. if description is None:
  212. description = self._html_search_regex(
  213. r'<p\s+class="teasertext">(.+?)</p>',
  214. webpage, 'teaser text', default=None)
  215. # Thumbnail is sometimes not present.
  216. # It is in the mobile version, but that seems to use a different URL
  217. # structure altogether.
  218. thumbnail = self._og_search_thumbnail(webpage, default=None)
  219. media_streams = re.findall(r'''(?x)
  220. mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s*
  221. "([^"]+)"''', webpage)
  222. if media_streams:
  223. QUALITIES = qualities(['lo', 'hi', 'hq'])
  224. formats = []
  225. for furl in set(media_streams):
  226. if furl.endswith('.f4m'):
  227. fid = 'f4m'
  228. else:
  229. fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl)
  230. fid = fid_m.group(1) if fid_m else None
  231. formats.append({
  232. 'quality': QUALITIES(fid),
  233. 'format_id': fid,
  234. 'url': furl,
  235. })
  236. info = {
  237. 'formats': formats,
  238. }
  239. else: # request JSON file
  240. if not document_id:
  241. video_id = self._search_regex(
  242. (r'/play/(?:config|media|sola)/(\d+)', r'contentId["\']\s*:\s*(\d+)'),
  243. webpage, 'media id', default=None)
  244. info = self._extract_media_info(
  245. 'http://www.ardmediathek.de/play/media/%s' % video_id,
  246. webpage, video_id)
  247. info.update({
  248. 'id': video_id,
  249. 'title': title,
  250. 'description': description,
  251. 'thumbnail': thumbnail,
  252. })
  253. info.update(self._ARD_extract_episode_info(info['title']))
  254. return info
  255. class ARDIE(InfoExtractor):
  256. _VALID_URL = r'(?P<mainurl>https?://(?:www\.)?daserste\.de/(?:[^/?#&]+/)+(?P<id>[^/?#&]+))\.html'
  257. _TESTS = [{
  258. # available till 7.01.2022
  259. 'url': 'https://www.daserste.de/information/talk/maischberger/videos/maischberger-die-woche-video100.html',
  260. 'md5': '867d8aa39eeaf6d76407c5ad1bb0d4c1',
  261. 'info_dict': {
  262. 'id': 'maischberger-die-woche-video100',
  263. 'display_id': 'maischberger-die-woche-video100',
  264. 'ext': 'mp4',
  265. 'duration': 3687.0,
  266. 'title': 'maischberger. die woche vom 7. Januar 2021',
  267. 'upload_date': '20210107',
  268. 'thumbnail': r're:^https?://.*\.jpg$',
  269. },
  270. }, {
  271. 'url': 'https://www.daserste.de/information/politik-weltgeschehen/morgenmagazin/videosextern/dominik-kahun-aus-der-nhl-direkt-zur-weltmeisterschaft-100.html',
  272. 'only_matching': True,
  273. }, {
  274. 'url': 'https://www.daserste.de/information/nachrichten-wetter/tagesthemen/videosextern/tagesthemen-17736.html',
  275. 'only_matching': True,
  276. }, {
  277. 'url': 'https://www.daserste.de/unterhaltung/serie/in-aller-freundschaft-die-jungen-aerzte/videos/diversity-tag-sanam-afrashteh100.html',
  278. 'only_matching': True,
  279. }, {
  280. 'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
  281. 'only_matching': True,
  282. }, {
  283. 'url': 'https://www.daserste.de/unterhaltung/serie/in-aller-freundschaft-die-jungen-aerzte/Drehpause-100.html',
  284. 'only_matching': True,
  285. }, {
  286. 'url': 'https://www.daserste.de/unterhaltung/film/filmmittwoch-im-ersten/videos/making-ofwendezeit-video-100.html',
  287. 'only_matching': True,
  288. }]
  289. def _real_extract(self, url):
  290. mobj = self._match_valid_url(url)
  291. display_id = mobj.group('id')
  292. player_url = mobj.group('mainurl') + '~playerXml.xml'
  293. doc = self._download_xml(player_url, display_id)
  294. video_node = doc.find('./video')
  295. upload_date = unified_strdate(xpath_text(
  296. video_node, './broadcastDate'))
  297. thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
  298. formats = []
  299. for a in video_node.findall('.//asset'):
  300. file_name = xpath_text(a, './fileName', default=None)
  301. if not file_name:
  302. continue
  303. format_type = a.attrib.get('type')
  304. format_url = url_or_none(file_name)
  305. if format_url:
  306. ext = determine_ext(file_name)
  307. if ext == 'm3u8':
  308. formats.extend(self._extract_m3u8_formats(
  309. format_url, display_id, 'mp4', entry_protocol='m3u8_native',
  310. m3u8_id=format_type or 'hls', fatal=False))
  311. continue
  312. elif ext == 'f4m':
  313. formats.extend(self._extract_f4m_formats(
  314. update_url_query(format_url, {'hdcore': '3.7.0'}),
  315. display_id, f4m_id=format_type or 'hds', fatal=False))
  316. continue
  317. f = {
  318. 'format_id': format_type,
  319. 'width': int_or_none(xpath_text(a, './frameWidth')),
  320. 'height': int_or_none(xpath_text(a, './frameHeight')),
  321. 'vbr': int_or_none(xpath_text(a, './bitrateVideo')),
  322. 'abr': int_or_none(xpath_text(a, './bitrateAudio')),
  323. 'vcodec': xpath_text(a, './codecVideo'),
  324. 'tbr': int_or_none(xpath_text(a, './totalBitrate')),
  325. }
  326. server_prefix = xpath_text(a, './serverPrefix', default=None)
  327. if server_prefix:
  328. f.update({
  329. 'url': server_prefix,
  330. 'playpath': file_name,
  331. })
  332. else:
  333. if not format_url:
  334. continue
  335. f['url'] = format_url
  336. formats.append(f)
  337. _SUB_FORMATS = (
  338. ('./dataTimedText', 'ttml'),
  339. ('./dataTimedTextNoOffset', 'ttml'),
  340. ('./dataTimedTextVtt', 'vtt'),
  341. )
  342. subtitles = {}
  343. for subsel, subext in _SUB_FORMATS:
  344. for node in video_node.findall(subsel):
  345. subtitles.setdefault('de', []).append({
  346. 'url': node.attrib['url'],
  347. 'ext': subext,
  348. })
  349. return {
  350. 'id': xpath_text(video_node, './videoId', default=display_id),
  351. 'formats': formats,
  352. 'subtitles': subtitles,
  353. 'display_id': display_id,
  354. 'title': video_node.find('./title').text,
  355. 'duration': parse_duration(video_node.find('./duration').text),
  356. 'upload_date': upload_date,
  357. 'thumbnail': thumbnail,
  358. }
  359. class ARDBetaMediathekIE(ARDMediathekBaseIE):
  360. _VALID_URL = r'''(?x)https://
  361. (?:(?:beta|www)\.)?ardmediathek\.de/
  362. (?:(?P<client>[^/]+)/)?
  363. (?:player|live|video|(?P<playlist>sendung|sammlung))/
  364. (?:(?P<display_id>(?(playlist)[^?#]+?|[^?#]+))/)?
  365. (?P<id>(?(playlist)|Y3JpZDovL)[a-zA-Z0-9]+)
  366. (?(playlist)/(?P<season>\d+)?/?(?:[?#]|$))'''
  367. _TESTS = [{
  368. 'url': 'https://www.ardmediathek.de/mdr/video/die-robuste-roswita/Y3JpZDovL21kci5kZS9iZWl0cmFnL2Ntcy84MWMxN2MzZC0wMjkxLTRmMzUtODk4ZS0wYzhlOWQxODE2NGI/',
  369. 'md5': 'a1dc75a39c61601b980648f7c9f9f71d',
  370. 'info_dict': {
  371. 'display_id': 'die-robuste-roswita',
  372. 'id': '78566716',
  373. 'title': 'Die robuste Roswita',
  374. 'description': r're:^Der Mord.*totgeglaubte Ehefrau Roswita',
  375. 'duration': 5316,
  376. 'thumbnail': 'https://img.ardmediathek.de/standard/00/78/56/67/84/575672121/16x9/960?mandant=ard',
  377. 'timestamp': 1596658200,
  378. 'upload_date': '20200805',
  379. 'ext': 'mp4',
  380. },
  381. 'skip': 'Error',
  382. }, {
  383. 'url': 'https://www.ardmediathek.de/video/tagesschau-oder-tagesschau-20-00-uhr/das-erste/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhZ2Vzc2NoYXUvZmM4ZDUxMjgtOTE0ZC00Y2MzLTgzNzAtNDZkNGNiZWJkOTll',
  384. 'md5': 'f1837e563323b8a642a8ddeff0131f51',
  385. 'info_dict': {
  386. 'id': '10049223',
  387. 'ext': 'mp4',
  388. 'title': 'tagesschau, 20:00 Uhr',
  389. 'timestamp': 1636398000,
  390. 'description': 'md5:39578c7b96c9fe50afdf5674ad985e6b',
  391. 'upload_date': '20211108',
  392. },
  393. }, {
  394. 'url': 'https://www.ardmediathek.de/sendung/beforeigners/beforeigners/staffel-1/Y3JpZDovL2Rhc2Vyc3RlLmRlL2JlZm9yZWlnbmVycw/1',
  395. 'playlist_count': 6,
  396. 'info_dict': {
  397. 'id': 'Y3JpZDovL2Rhc2Vyc3RlLmRlL2JlZm9yZWlnbmVycw',
  398. 'title': 'beforeigners/beforeigners/staffel-1',
  399. },
  400. }, {
  401. 'url': 'https://beta.ardmediathek.de/ard/video/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE',
  402. 'only_matching': True,
  403. }, {
  404. 'url': 'https://ardmediathek.de/ard/video/saartalk/saartalk-gesellschaftsgift-haltung-gegen-hass/sr-fernsehen/Y3JpZDovL3NyLW9ubGluZS5kZS9TVF84MTY4MA/',
  405. 'only_matching': True,
  406. }, {
  407. 'url': 'https://www.ardmediathek.de/ard/video/trailer/private-eyes-s01-e01/one/Y3JpZDovL3dkci5kZS9CZWl0cmFnLTE1MTgwYzczLWNiMTEtNGNkMS1iMjUyLTg5MGYzOWQxZmQ1YQ/',
  408. 'only_matching': True,
  409. }, {
  410. 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3N3ci5kZS9hZXgvbzEwNzE5MTU/',
  411. 'only_matching': True,
  412. }, {
  413. 'url': 'https://www.ardmediathek.de/swr/live/Y3JpZDovL3N3ci5kZS8xMzQ4MTA0Mg',
  414. 'only_matching': True,
  415. }, {
  416. # playlist of type 'sendung'
  417. 'url': 'https://www.ardmediathek.de/ard/sendung/doctor-who/Y3JpZDovL3dkci5kZS9vbmUvZG9jdG9yIHdobw/',
  418. 'only_matching': True,
  419. }, {
  420. # playlist of type 'sammlung'
  421. 'url': 'https://www.ardmediathek.de/ard/sammlung/team-muenster/5JpTzLSbWUAK8184IOvEir/',
  422. 'only_matching': True,
  423. }, {
  424. 'url': 'https://www.ardmediathek.de/video/coronavirus-update-ndr-info/astrazeneca-kurz-lockdown-und-pims-syndrom-81/ndr/Y3JpZDovL25kci5kZS84NzE0M2FjNi0wMWEwLTQ5ODEtOTE5NS1mOGZhNzdhOTFmOTI/',
  425. 'only_matching': True,
  426. }, {
  427. 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3dkci5kZS9CZWl0cmFnLWQ2NDJjYWEzLTMwZWYtNGI4NS1iMTI2LTU1N2UxYTcxOGIzOQ/tatort-duo-koeln-leipzig-ihr-kinderlein-kommet',
  428. 'only_matching': True,
  429. }]
  430. def _ARD_load_playlist_snipped(self, playlist_id, display_id, client, mode, pageNumber):
  431. """ Query the ARD server for playlist information
  432. and returns the data in "raw" format """
  433. if mode == 'sendung':
  434. graphQL = json.dumps({
  435. 'query': '''{
  436. showPage(
  437. client: "%s"
  438. showId: "%s"
  439. pageNumber: %d
  440. ) {
  441. pagination {
  442. pageSize
  443. totalElements
  444. }
  445. teasers { # Array
  446. mediumTitle
  447. links { target { id href title } }
  448. type
  449. }
  450. }}''' % (client, playlist_id, pageNumber),
  451. }).encode()
  452. else: # mode == 'sammlung'
  453. graphQL = json.dumps({
  454. 'query': '''{
  455. morePage(
  456. client: "%s"
  457. compilationId: "%s"
  458. pageNumber: %d
  459. ) {
  460. widget {
  461. pagination {
  462. pageSize
  463. totalElements
  464. }
  465. teasers { # Array
  466. mediumTitle
  467. links { target { id href title } }
  468. type
  469. }
  470. }
  471. }}''' % (client, playlist_id, pageNumber),
  472. }).encode()
  473. # Ressources for ARD graphQL debugging:
  474. # https://api-test.ardmediathek.de/public-gateway
  475. show_page = self._download_json(
  476. 'https://api.ardmediathek.de/public-gateway',
  477. '[Playlist] %s' % display_id,
  478. data=graphQL,
  479. headers={'Content-Type': 'application/json'})['data']
  480. # align the structure of the returned data:
  481. if mode == 'sendung':
  482. show_page = show_page['showPage']
  483. else: # mode == 'sammlung'
  484. show_page = show_page['morePage']['widget']
  485. return show_page
  486. def _ARD_extract_playlist(self, url, playlist_id, display_id, client, mode):
  487. """ Collects all playlist entries and returns them as info dict.
  488. Supports playlists of mode 'sendung' and 'sammlung', and also nested
  489. playlists. """
  490. entries = []
  491. pageNumber = 0
  492. while True: # iterate by pageNumber
  493. show_page = self._ARD_load_playlist_snipped(
  494. playlist_id, display_id, client, mode, pageNumber)
  495. for teaser in show_page['teasers']: # process playlist items
  496. if '/compilation/' in teaser['links']['target']['href']:
  497. # alternativ cond.: teaser['type'] == "compilation"
  498. # => This is an nested compilation, e.g. like:
  499. # https://www.ardmediathek.de/ard/sammlung/die-kirche-bleibt-im-dorf/5eOHzt8XB2sqeFXbIoJlg2/
  500. link_mode = 'sammlung'
  501. else:
  502. link_mode = 'video'
  503. item_url = 'https://www.ardmediathek.de/%s/%s/%s/%s/%s' % (
  504. client, link_mode, display_id,
  505. # perform HTLM quoting of episode title similar to ARD:
  506. re.sub('^-|-$', '', # remove '-' from begin/end
  507. re.sub('[^a-zA-Z0-9]+', '-', # replace special chars by -
  508. teaser['links']['target']['title'].lower()
  509. .replace('ä', 'ae').replace('ö', 'oe')
  510. .replace('ü', 'ue').replace('ß', 'ss'))),
  511. teaser['links']['target']['id'])
  512. entries.append(self.url_result(
  513. item_url,
  514. ie=ARDBetaMediathekIE.ie_key()))
  515. if (show_page['pagination']['pageSize'] * (pageNumber + 1)
  516. >= show_page['pagination']['totalElements']):
  517. # we've processed enough pages to get all playlist entries
  518. break
  519. pageNumber = pageNumber + 1
  520. return self.playlist_result(entries, playlist_id, playlist_title=display_id)
  521. def _real_extract(self, url):
  522. video_id, display_id, playlist_type, client, season_number = self._match_valid_url(url).group(
  523. 'id', 'display_id', 'playlist', 'client', 'season')
  524. display_id, client = display_id or video_id, client or 'ard'
  525. if playlist_type:
  526. # TODO: Extract only specified season
  527. return self._ARD_extract_playlist(url, video_id, display_id, client, playlist_type)
  528. player_page = self._download_json(
  529. 'https://api.ardmediathek.de/public-gateway',
  530. display_id, data=json.dumps({
  531. 'query': '''{
  532. playerPage(client:"%s", clipId: "%s") {
  533. blockedByFsk
  534. broadcastedOn
  535. maturityContentRating
  536. mediaCollection {
  537. _duration
  538. _geoblocked
  539. _isLive
  540. _mediaArray {
  541. _mediaStreamArray {
  542. _quality
  543. _server
  544. _stream
  545. }
  546. }
  547. _previewImage
  548. _subtitleUrl
  549. _type
  550. }
  551. show {
  552. title
  553. }
  554. synopsis
  555. title
  556. tracking {
  557. atiCustomVars {
  558. contentId
  559. }
  560. }
  561. }
  562. }''' % (client, video_id),
  563. }).encode(), headers={
  564. 'Content-Type': 'application/json'
  565. })['data']['playerPage']
  566. title = player_page['title']
  567. content_id = str_or_none(try_get(
  568. player_page, lambda x: x['tracking']['atiCustomVars']['contentId']))
  569. media_collection = player_page.get('mediaCollection') or {}
  570. if not media_collection and content_id:
  571. media_collection = self._download_json(
  572. 'https://www.ardmediathek.de/play/media/' + content_id,
  573. content_id, fatal=False) or {}
  574. info = self._parse_media_info(
  575. media_collection, content_id or video_id,
  576. player_page.get('blockedByFsk'))
  577. age_limit = None
  578. description = player_page.get('synopsis')
  579. maturity_content_rating = player_page.get('maturityContentRating')
  580. if maturity_content_rating:
  581. age_limit = int_or_none(maturity_content_rating.lstrip('FSK'))
  582. if not age_limit and description:
  583. age_limit = int_or_none(self._search_regex(
  584. r'\(FSK\s*(\d+)\)\s*$', description, 'age limit', default=None))
  585. info.update({
  586. 'age_limit': age_limit,
  587. 'display_id': display_id,
  588. 'title': title,
  589. 'description': description,
  590. 'timestamp': unified_timestamp(player_page.get('broadcastedOn')),
  591. 'series': try_get(player_page, lambda x: x['show']['title']),
  592. })
  593. info.update(self._ARD_extract_episode_info(info['title']))
  594. return info