arte.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import re
  2. from .common import InfoExtractor
  3. from ..utils import (
  4. ExtractorError,
  5. GeoRestrictedError,
  6. int_or_none,
  7. parse_iso8601,
  8. parse_qs,
  9. strip_or_none,
  10. traverse_obj,
  11. url_or_none,
  12. )
  13. class ArteTVBaseIE(InfoExtractor):
  14. _ARTE_LANGUAGES = 'fr|de|en|es|it|pl'
  15. _API_BASE = 'https://api.arte.tv/api/player/v2'
  16. class ArteTVIE(ArteTVBaseIE):
  17. _VALID_URL = r'''(?x)
  18. (?:https?://
  19. (?:
  20. (?:www\.)?arte\.tv/(?P<lang>%(langs)s)/videos|
  21. api\.arte\.tv/api/player/v\d+/config/(?P<lang_2>%(langs)s)
  22. )
  23. |arte://program)
  24. /(?P<id>\d{6}-\d{3}-[AF]|LIVE)
  25. ''' % {'langs': ArteTVBaseIE._ARTE_LANGUAGES}
  26. _TESTS = [{
  27. 'url': 'https://www.arte.tv/en/videos/088501-000-A/mexico-stealing-petrol-to-survive/',
  28. 'only_matching': True,
  29. }, {
  30. 'url': 'https://www.arte.tv/pl/videos/100103-000-A/usa-dyskryminacja-na-porodowce/',
  31. 'info_dict': {
  32. 'id': '100103-000-A',
  33. 'title': 'USA: Dyskryminacja na porodówce',
  34. 'description': 'md5:242017b7cce59ffae340a54baefcafb1',
  35. 'alt_title': 'ARTE Reportage',
  36. 'upload_date': '20201103',
  37. 'duration': 554,
  38. 'thumbnail': r're:https://api-cdn\.arte\.tv/.+940x530',
  39. 'timestamp': 1604417980,
  40. 'ext': 'mp4',
  41. },
  42. 'params': {'skip_download': 'm3u8'}
  43. }, {
  44. 'note': 'No alt_title',
  45. 'url': 'https://www.arte.tv/fr/videos/110371-000-A/la-chaleur-supplice-des-arbres-de-rue/',
  46. 'info_dict': {
  47. 'id': '110371-000-A',
  48. 'ext': 'mp4',
  49. 'upload_date': '20220718',
  50. 'duration': 154,
  51. 'timestamp': 1658162460,
  52. 'description': 'md5:5890f36fe7dccfadb8b7c0891de54786',
  53. 'title': 'La chaleur, supplice des arbres de rue',
  54. 'thumbnail': 'https://api-cdn.arte.tv/img/v2/image/CPE2sQDtD8GLQgt8DuYHLf/940x530',
  55. },
  56. 'params': {'skip_download': 'm3u8'}
  57. }, {
  58. 'url': 'https://api.arte.tv/api/player/v2/config/de/100605-013-A',
  59. 'only_matching': True,
  60. }, {
  61. 'url': 'https://api.arte.tv/api/player/v2/config/de/LIVE',
  62. 'only_matching': True,
  63. }]
  64. _GEO_BYPASS = True
  65. _LANG_MAP = { # ISO639 -> French abbreviations
  66. 'fr': 'F',
  67. 'de': 'A',
  68. 'en': 'E[ANG]',
  69. 'es': 'E[ESP]',
  70. 'it': 'E[ITA]',
  71. 'pl': 'E[POL]',
  72. # XXX: probably means mixed; <https://www.arte.tv/en/videos/107710-029-A/dispatches-from-ukraine-local-journalists-report/>
  73. # uses this code for audio that happens to be in Ukrainian, but the manifest uses the ISO code 'mul' (mixed)
  74. 'mul': 'EU',
  75. }
  76. _VERSION_CODE_RE = re.compile(r'''(?x)
  77. V
  78. (?P<original_voice>O?)
  79. (?P<vlang>[FA]|E\[[A-Z]+\]|EU)?
  80. (?P<audio_desc>AUD|)
  81. (?:
  82. (?P<has_sub>-ST)
  83. (?P<sdh_sub>M?)
  84. (?P<sub_lang>[FA]|E\[[A-Z]+\]|EU)
  85. )?
  86. ''')
  87. # all obtained by exhaustive testing
  88. _COUNTRIES_MAP = {
  89. 'DE_FR': (
  90. 'BL', 'DE', 'FR', 'GF', 'GP', 'MF', 'MQ', 'NC',
  91. 'PF', 'PM', 'RE', 'WF', 'YT',
  92. ),
  93. # with both of the below 'BE' sometimes works, sometimes doesn't
  94. 'EUR_DE_FR': (
  95. 'AT', 'BL', 'CH', 'DE', 'FR', 'GF', 'GP', 'LI',
  96. 'MC', 'MF', 'MQ', 'NC', 'PF', 'PM', 'RE', 'WF',
  97. 'YT',
  98. ),
  99. 'SAT': (
  100. 'AD', 'AT', 'AX', 'BG', 'BL', 'CH', 'CY', 'CZ',
  101. 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GB', 'GF',
  102. 'GR', 'HR', 'HU', 'IE', 'IS', 'IT', 'KN', 'LI',
  103. 'LT', 'LU', 'LV', 'MC', 'MF', 'MQ', 'MT', 'NC',
  104. 'NL', 'NO', 'PF', 'PL', 'PM', 'PT', 'RE', 'RO',
  105. 'SE', 'SI', 'SK', 'SM', 'VA', 'WF', 'YT',
  106. ),
  107. }
  108. def _real_extract(self, url):
  109. mobj = self._match_valid_url(url)
  110. video_id = mobj.group('id')
  111. lang = mobj.group('lang') or mobj.group('lang_2')
  112. langauge_code = self._LANG_MAP.get(lang)
  113. config = self._download_json(f'{self._API_BASE}/config/{lang}/{video_id}', video_id)
  114. geoblocking = traverse_obj(config, ('data', 'attributes', 'restriction', 'geoblocking')) or {}
  115. if geoblocking.get('restrictedArea'):
  116. raise GeoRestrictedError(f'Video restricted to {geoblocking["code"]!r}',
  117. countries=self._COUNTRIES_MAP.get(geoblocking['code'], ('DE', 'FR')))
  118. if not traverse_obj(config, ('data', 'attributes', 'rights')):
  119. # Eg: https://www.arte.tv/de/videos/097407-215-A/28-minuten
  120. # Eg: https://www.arte.tv/es/videos/104351-002-A/serviteur-du-peuple-1-23
  121. raise ExtractorError(
  122. 'Video is not available in this language edition of Arte or broadcast rights expired', expected=True)
  123. formats, subtitles = [], {}
  124. secondary_formats = []
  125. for stream in config['data']['attributes']['streams']:
  126. # official player contains code like `e.get("versions")[0].eStat.ml5`
  127. stream_version = stream['versions'][0]
  128. stream_version_code = stream_version['eStat']['ml5']
  129. lang_pref = -1
  130. m = self._VERSION_CODE_RE.match(stream_version_code)
  131. if m:
  132. lang_pref = int(''.join('01'[x] for x in (
  133. m.group('vlang') == langauge_code, # we prefer voice in the requested language
  134. not m.group('audio_desc'), # and not the audio description version
  135. bool(m.group('original_voice')), # but if voice is not in the requested language, at least choose the original voice
  136. m.group('sub_lang') == langauge_code, # if subtitles are present, we prefer them in the requested language
  137. not m.group('has_sub'), # but we prefer no subtitles otherwise
  138. not m.group('sdh_sub'), # and we prefer not the hard-of-hearing subtitles if there are subtitles
  139. )))
  140. short_label = traverse_obj(stream_version, 'shortLabel', expected_type=str, default='?')
  141. if stream['protocol'].startswith('HLS'):
  142. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  143. stream['url'], video_id=video_id, ext='mp4', m3u8_id=stream_version_code, fatal=False)
  144. for fmt in fmts:
  145. fmt.update({
  146. 'format_note': f'{stream_version.get("label", "unknown")} [{short_label}]',
  147. 'language_preference': lang_pref,
  148. })
  149. if any(map(short_label.startswith, ('cc', 'OGsub'))):
  150. secondary_formats.extend(fmts)
  151. else:
  152. formats.extend(fmts)
  153. self._merge_subtitles(subs, target=subtitles)
  154. elif stream['protocol'] in ('HTTPS', 'RTMP'):
  155. formats.append({
  156. 'format_id': f'{stream["protocol"]}-{stream_version_code}',
  157. 'url': stream['url'],
  158. 'format_note': f'{stream_version.get("label", "unknown")} [{short_label}]',
  159. 'language_preference': lang_pref,
  160. # 'ext': 'mp4', # XXX: may or may not be necessary, at least for HTTPS
  161. })
  162. else:
  163. self.report_warning(f'Skipping stream with unknown protocol {stream["protocol"]}')
  164. # TODO: chapters from stream['segments']?
  165. # The JS also looks for chapters in config['data']['attributes']['chapters'],
  166. # but I am yet to find a video having those
  167. formats.extend(secondary_formats)
  168. self._remove_duplicate_formats(formats)
  169. metadata = config['data']['attributes']['metadata']
  170. return {
  171. 'id': metadata['providerId'],
  172. 'webpage_url': traverse_obj(metadata, ('link', 'url')),
  173. 'title': traverse_obj(metadata, 'subtitle', 'title'),
  174. 'alt_title': metadata.get('subtitle') and metadata.get('title'),
  175. 'description': metadata.get('description'),
  176. 'duration': traverse_obj(metadata, ('duration', 'seconds')),
  177. 'language': metadata.get('language'),
  178. 'timestamp': traverse_obj(config, ('data', 'attributes', 'rights', 'begin'), expected_type=parse_iso8601),
  179. 'is_live': config['data']['attributes'].get('live', False),
  180. 'formats': formats,
  181. 'subtitles': subtitles,
  182. 'thumbnails': [
  183. {'url': image['url'], 'id': image.get('caption')}
  184. for image in metadata.get('images') or [] if url_or_none(image.get('url'))
  185. ],
  186. }
  187. class ArteTVEmbedIE(InfoExtractor):
  188. _VALID_URL = r'https?://(?:www\.)?arte\.tv/player/v\d+/index\.php\?.*?\bjson_url=.+'
  189. _EMBED_REGEX = [r'<(?:iframe|script)[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?arte\.tv/player/v\d+/index\.php\?.*?\bjson_url=.+?)\1']
  190. _TESTS = [{
  191. 'url': 'https://www.arte.tv/player/v5/index.php?json_url=https%3A%2F%2Fapi.arte.tv%2Fapi%2Fplayer%2Fv2%2Fconfig%2Fde%2F100605-013-A&lang=de&autoplay=true&mute=0100605-013-A',
  192. 'info_dict': {
  193. 'id': '100605-013-A',
  194. 'ext': 'mp4',
  195. 'title': 'United we Stream November Lockdown Edition #13',
  196. 'description': 'md5:be40b667f45189632b78c1425c7c2ce1',
  197. 'upload_date': '20201116',
  198. },
  199. 'skip': 'No video available'
  200. }, {
  201. 'url': 'https://www.arte.tv/player/v3/index.php?json_url=https://api.arte.tv/api/player/v2/config/de/100605-013-A',
  202. 'only_matching': True,
  203. }]
  204. def _real_extract(self, url):
  205. qs = parse_qs(url)
  206. json_url = qs['json_url'][0]
  207. video_id = ArteTVIE._match_id(json_url)
  208. return self.url_result(
  209. json_url, ie=ArteTVIE.ie_key(), video_id=video_id)
  210. class ArteTVPlaylistIE(ArteTVBaseIE):
  211. _VALID_URL = r'https?://(?:www\.)?arte\.tv/(?P<lang>%s)/videos/(?P<id>RC-\d{6})' % ArteTVBaseIE._ARTE_LANGUAGES
  212. _TESTS = [{
  213. 'url': 'https://www.arte.tv/en/videos/RC-016954/earn-a-living/',
  214. 'only_matching': True,
  215. }, {
  216. 'url': 'https://www.arte.tv/pl/videos/RC-014123/arte-reportage/',
  217. 'playlist_mincount': 100,
  218. 'info_dict': {
  219. 'description': 'md5:84e7bf1feda248bc325ebfac818c476e',
  220. 'id': 'RC-014123',
  221. 'title': 'ARTE Reportage - najlepsze reportaże',
  222. },
  223. }]
  224. def _real_extract(self, url):
  225. lang, playlist_id = self._match_valid_url(url).group('lang', 'id')
  226. playlist = self._download_json(
  227. f'{self._API_BASE}/playlist/{lang}/{playlist_id}', playlist_id)['data']['attributes']
  228. entries = [{
  229. '_type': 'url_transparent',
  230. 'url': video['config']['url'],
  231. 'ie_key': ArteTVIE.ie_key(),
  232. 'id': video.get('providerId'),
  233. 'title': video.get('title'),
  234. 'alt_title': video.get('subtitle'),
  235. 'thumbnail': url_or_none(traverse_obj(video, ('mainImage', 'url'))),
  236. 'duration': int_or_none(traverse_obj(video, ('duration', 'seconds'))),
  237. } for video in traverse_obj(playlist, ('items', lambda _, v: v['config']['url']))]
  238. return self.playlist_result(entries, playlist_id,
  239. traverse_obj(playlist, ('metadata', 'title')),
  240. traverse_obj(playlist, ('metadata', 'description')))
  241. class ArteTVCategoryIE(ArteTVBaseIE):
  242. _VALID_URL = r'https?://(?:www\.)?arte\.tv/(?P<lang>%s)/videos/(?P<id>[\w-]+(?:/[\w-]+)*)/?\s*$' % ArteTVBaseIE._ARTE_LANGUAGES
  243. _TESTS = [{
  244. 'url': 'https://www.arte.tv/en/videos/politics-and-society/',
  245. 'info_dict': {
  246. 'id': 'politics-and-society',
  247. 'title': 'Politics and society',
  248. 'description': 'Investigative documentary series, geopolitical analysis, and international commentary',
  249. },
  250. 'playlist_mincount': 13,
  251. }]
  252. @classmethod
  253. def suitable(cls, url):
  254. return (
  255. not any(ie.suitable(url) for ie in (ArteTVIE, ArteTVPlaylistIE, ))
  256. and super().suitable(url))
  257. def _real_extract(self, url):
  258. lang, playlist_id = self._match_valid_url(url).groups()
  259. webpage = self._download_webpage(url, playlist_id)
  260. items = []
  261. for video in re.finditer(
  262. r'<a\b[^>]*?href\s*=\s*(?P<q>"|\'|\b)(?P<url>https?://www\.arte\.tv/%s/videos/[\w/-]+)(?P=q)' % lang,
  263. webpage):
  264. video = video.group('url')
  265. if video == url:
  266. continue
  267. if any(ie.suitable(video) for ie in (ArteTVIE, ArteTVPlaylistIE, )):
  268. items.append(video)
  269. title = strip_or_none(self._generic_title('', webpage, default='').rsplit('|', 1)[0]) or None
  270. return self.playlist_from_matches(items, playlist_id=playlist_id, playlist_title=title,
  271. description=self._og_search_description(webpage, default=None))