]> jfr.im git - yt-dlp.git/blobdiff - yt_dlp/extractor/polskieradio.py
[ie/matchtv] Fix extractor (#10190)
[yt-dlp.git] / yt_dlp / extractor / polskieradio.py
index 68c4a2afd0bd5e6336a97cc17b7125ff439f8316..6fb21e156d571984a40d34757b45c38dd33d0e67 100644 (file)
@@ -2,26 +2,23 @@
 import json
 import math
 import re
+import urllib.parse
 
 from .common import InfoExtractor
-from ..compat import (
-    compat_str,
-    compat_urllib_parse_unquote,
-    compat_urlparse
-)
 from ..utils import (
-    determine_ext,
-    extract_attributes,
     ExtractorError,
     InAdvancePagedList,
+    determine_ext,
+    extract_attributes,
     int_or_none,
     js_to_json,
     parse_iso8601,
     strip_or_none,
     traverse_obj,
-    unified_timestamp,
     unescapeHTML,
+    unified_timestamp,
     url_or_none,
+    urljoin,
 )
 
 
@@ -39,12 +36,12 @@ def _extract_webpage_player_entries(self, webpage, playlist_id, base_data):
             media_urls.add(media_url)
             entry = base_data.copy()
             entry.update({
-                'id': compat_str(media['id']),
+                'id': str(media['id']),
                 'url': media_url,
                 'duration': int_or_none(media.get('length')),
                 'vcodec': 'none' if media.get('provider') == 'audio' else None,
             })
-            entry_title = compat_urllib_parse_unquote(media['desc'])
+            entry_title = urllib.parse.unquote(media['desc'])
             if entry_title:
                 entry['title'] = entry_title
             yield entry
@@ -70,7 +67,7 @@ class PolskieRadioLegacyIE(PolskieRadioBaseExtractor):
                 'timestamp': 1592654400,
                 'upload_date': '20200620',
                 'duration': 1430,
-                'thumbnail': r're:^https?://static\.prsa\.pl/images/.*\.jpg$'
+                'thumbnail': r're:^https?://static\.prsa\.pl/images/.*\.jpg$',
             },
         }],
     }, {
@@ -130,10 +127,11 @@ def _real_extract(self, url):
         return self.playlist_result(entries, playlist_id, title, description)
 
 
-class PolskieRadioIE(InfoExtractor):
-    # new next.js sites, excluding radiokierowcow.pl
-    _VALID_URL = r'https?://(?:[^/]+\.)?polskieradio(?:24)?\.pl/artykul/(?P<id>\d+)'
+class PolskieRadioIE(PolskieRadioBaseExtractor):
+    # new next.js sites
+    _VALID_URL = r'https?://(?:[^/]+\.)?(?:polskieradio(?:24)?|radiokierowcow)\.pl/artykul/(?P<id>\d+)'
     _TESTS = [{
+        # articleData, attachments
         'url': 'https://jedynka.polskieradio.pl/artykul/1587943',
         'info_dict': {
             'id': '1587943',
@@ -148,6 +146,31 @@ class PolskieRadioIE(InfoExtractor):
                 'title': 'md5:d4623290d4ac983bf924061c75c23a0d',
             },
         }],
+    }, {
+        # post, legacy html players
+        'url': 'https://trojka.polskieradio.pl/artykul/2589163,Czy-wciaz-otrzymujemy-zdjecia-z-sond-Voyager',
+        'info_dict': {
+            'id': '2589163',
+            'title': 'Czy wciąż otrzymujemy zdjęcia z sond Voyager?',
+            'description': 'md5:cf1a7f348d63a2db9c0d7a63d1669473',
+        },
+        'playlist': [{
+            'info_dict': {
+                'id': '2577880',
+                'ext': 'mp3',
+                'title': 'md5:a57d10a0c02abd34dd675cb33707ad5a',
+                'duration': 321,
+            },
+        }],
+    }, {
+        # data, legacy
+        'url': 'https://radiokierowcow.pl/artykul/2694529',
+        'info_dict': {
+            'id': '2694529',
+            'title': 'Zielona fala reliktem przeszłości?',
+            'description': 'md5:f20a9a7ed9cb58916c54add94eae3bc0',
+        },
+        'playlist_count': 3,
     }, {
         'url': 'https://trojka.polskieradio.pl/artykul/1632955',
         'only_matching': True,
@@ -166,7 +189,8 @@ def _real_extract(self, url):
         webpage = self._download_webpage(url, playlist_id)
 
         article_data = traverse_obj(
-            self._search_nextjs_data(webpage, playlist_id), ('props', 'pageProps', 'data', 'articleData'))
+            self._search_nextjs_data(webpage, playlist_id), (
+                'props', 'pageProps', (('data', 'articleData'), 'post', 'data')), get_all=False)
 
         title = strip_or_none(article_data['title'])
 
@@ -178,7 +202,13 @@ def _real_extract(self, url):
             'id': self._search_regex(
                 r'([a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12})', entry['file'], 'entry id'),
             'title': strip_or_none(entry.get('description')) or title,
-        } for entry in article_data.get('attachments') or () if entry['fileType'] in ('Audio', )]
+        } for entry in article_data.get('attachments') or () if entry.get('fileType') in ('Audio', )]
+
+        if not entries:
+            # some legacy articles have no json attachments, but players in body
+            entries = self._extract_webpage_player_entries(article_data['content'], playlist_id, {
+                'title': title,
+            })
 
         return self.playlist_result(entries, playlist_id, title, description)
 
@@ -214,6 +244,15 @@ class PolskieRadioAuditionIE(InfoExtractor):
             'thumbnail': r're:https://static\.prsa\.pl/images/.+',
         },
         'playlist_mincount': 722,
+    }, {
+        # some articles were "promoted to main page" and thus link to old frontend
+        'url': 'https://trojka.polskieradio.pl/audycja/305',
+        'info_dict': {
+            'id': '305',
+            'title': 'Co w mowie piszczy?',
+            'thumbnail': r're:https://static\.prsa\.pl/images/.+',
+        },
+        'playlist_count': 1523,
     }]
 
     def _call_lp3(self, path, query, video_id, note):
@@ -222,14 +261,14 @@ def _call_lp3(self, path, query, video_id, note):
             query=query, headers={'x-api-key': '9bf6c5a2-a7d0-4980-9ed7-a3f7291f2a81'})
 
     def _entries(self, playlist_id, has_episodes, has_articles):
-        for i in itertools.count(1) if has_episodes else []:
+        for i in itertools.count(0) if has_episodes else []:
             page = self._call_lp3(
                 'AudioArticle/GetListByCategoryId', {
                     'categoryId': playlist_id,
                     'PageSize': 10,
                     'skip': i,
                     'format': 400,
-                }, playlist_id, f'Downloading episode list page {i}')
+                }, playlist_id, f'Downloading episode list page {i + 1}')
             if not traverse_obj(page, 'data'):
                 break
             for episode in page['data']:
@@ -241,20 +280,19 @@ def _entries(self, playlist_id, has_episodes, has_articles):
                     'timestamp': parse_iso8601(episode.get('datePublic')),
                 }
 
-        for i in itertools.count(1) if has_articles else []:
+        for i in itertools.count(0) if has_articles else []:
             page = self._call_lp3(
                 'Article/GetListByCategoryId', {
                     'categoryId': playlist_id,
                     'PageSize': 9,
                     'skip': i,
                     'format': 400,
-                }, playlist_id, f'Downloading article list page {i}')
+                }, playlist_id, f'Downloading article list page {i + 1}')
             if not traverse_obj(page, 'data'):
                 break
             for article in page['data']:
                 yield {
                     '_type': 'url_transparent',
-                    'ie_key': PolskieRadioIE.ie_key(),
                     'id': str(article['id']),
                     'url': article['url'],
                     'title': article.get('shortTitle'),
@@ -282,24 +320,51 @@ def _real_extract(self, url):
 class PolskieRadioCategoryIE(InfoExtractor):
     # legacy sites
     IE_NAME = 'polskieradio:category'
-    _VALID_URL = r'https?://(?:www\.)?polskieradio\.pl/\d+(?:,[^/]+)?/(?P<id>\d+)'
+    _VALID_URL = r'https?://(?:www\.)?polskieradio\.pl/(?:\d+(?:,[^/]+)?/|[^/]+/Tag)(?P<id>\d+)'
     _TESTS = [{
-        'url': 'http://www.polskieradio.pl/7/129,Sygnaly-dnia?ref=source',
-        'only_matching': True
-    }, {
         'url': 'http://www.polskieradio.pl/37,RedakcjaKatolicka/4143,Kierunek-Krakow',
         'info_dict': {
             'id': '4143',
             'title': 'Kierunek Kraków',
         },
-        'playlist_mincount': 61
+        'playlist_mincount': 61,
     }, {
         'url': 'http://www.polskieradio.pl/10,czworka/214,muzyka',
         'info_dict': {
             'id': '214',
             'title': 'Muzyka',
         },
-        'playlist_mincount': 61
+        'playlist_mincount': 61,
+    }, {
+        # billennium tabs
+        'url': 'https://www.polskieradio.pl/8/2385',
+        'info_dict': {
+            'id': '2385',
+            'title': 'Droga przez mąkę',
+        },
+        'playlist_mincount': 111,
+    }, {
+        'url': 'https://www.polskieradio.pl/10/4930',
+        'info_dict': {
+            'id': '4930',
+            'title': 'Teraz K-pop!',
+        },
+        'playlist_mincount': 392,
+    }, {
+        # post back pages, audio content directly without articles
+        'url': 'https://www.polskieradio.pl/8,dwojka/7376,nowa-mowa',
+        'info_dict': {
+            'id': '7376',
+            'title': 'Nowa mowa',
+        },
+        'playlist_mincount': 244,
+    }, {
+        'url': 'https://www.polskieradio.pl/Krzysztof-Dziuba/Tag175458',
+        'info_dict': {
+            'id': '175458',
+            'title': 'Krzysztof Dziuba',
+        },
+        'playlist_mincount': 420,
     }, {
         'url': 'http://www.polskieradio.pl/8,Dwojka/196,Publicystyka',
         'only_matching': True,
@@ -311,25 +376,61 @@ def suitable(cls, url):
 
     def _entries(self, url, page, category_id):
         content = page
+        is_billennium_tabs = 'onclick="TB_LoadTab(' in page
+        is_post_back = 'onclick="__doPostBack(' in page
+        pagination = page if is_billennium_tabs else None
         for page_num in itertools.count(2):
             for a_entry, entry_id in re.findall(
-                    r'(?s)<article[^>]+>.*?(<a[^>]+href=["\']/\d+/\d+/Artykul/(\d+)[^>]+>).*?</article>',
+                    r'(?s)<article[^>]+>.*?(<a[^>]+href=["\'](?:(?:https?)?://[^/]+)?/\d+/\d+/Artykul/(\d+)[^>]+>).*?</article>',
                     content):
                 entry = extract_attributes(a_entry)
-                href = entry.get('href')
-                if not href:
-                    continue
-                yield self.url_result(
-                    compat_urlparse.urljoin(url, href), PolskieRadioLegacyIE,
-                    entry_id, entry.get('title'))
-            mobj = re.search(
-                r'<div[^>]+class=["\']next["\'][^>]*>\s*<a[^>]+href=(["\'])(?P<url>(?:(?!\1).)+)\1',
-                content)
-            if not mobj:
-                break
-            next_url = compat_urlparse.urljoin(url, mobj.group('url'))
-            content = self._download_webpage(
-                next_url, category_id, 'Downloading page %s' % page_num)
+                if entry.get('href'):
+                    yield self.url_result(
+                        urljoin(url, entry['href']), PolskieRadioLegacyIE, entry_id, entry.get('title'))
+            for a_entry in re.findall(r'<span data-media=({[^ ]+})', content):
+                yield traverse_obj(self._parse_json(a_entry, category_id), {
+                    'url': 'file',
+                    'id': 'uid',
+                    'duration': 'length',
+                    'title': ('title', {urllib.parse.unquote}),
+                    'description': ('desc', {urllib.parse.unquote}),
+                })
+            if is_billennium_tabs:
+                params = self._search_json(
+                    r'<div[^>]+class=["\']next["\'][^>]*>\s*<a[^>]+onclick=["\']TB_LoadTab\(',
+                    pagination, 'next page params', category_id, default=None, close_objects=1,
+                    contains_pattern='.+', transform_source=lambda x: f'[{js_to_json(unescapeHTML(x))}')
+                if not params:
+                    break
+                tab_content = self._download_json(
+                    'https://www.polskieradio.pl/CMS/TemplateBoxesManagement/TemplateBoxTabContent.aspx/GetTabContent',
+                    category_id, f'Downloading page {page_num}', headers={'content-type': 'application/json'},
+                    data=json.dumps(dict(zip((
+                        'boxInstanceId', 'tabId', 'categoryType', 'sectionId', 'categoryId', 'pagerMode',
+                        'subjectIds', 'tagIndexId', 'queryString', 'name', 'openArticlesInParentTemplate',
+                        'idSectionFromUrl', 'maxDocumentAge', 'showCategoryForArticle', 'pageNumber',
+                    ), params))).encode())['d']
+                content, pagination = tab_content['Content'], tab_content.get('PagerContent')
+            elif is_post_back:
+                target = self._search_regex(
+                    r'onclick=(?:["\'])__doPostBack\((?P<q1>["\'])(?P<target>[\w$]+)(?P=q1)\s*,\s*(?P<q2>["\'])Next(?P=q2)',
+                    content, 'pagination postback target', group='target', default=None)
+                if not target:
+                    break
+                content = self._download_webpage(
+                    url, category_id, f'Downloading page {page_num}',
+                    data=urllib.parse.urlencode({
+                        **self._hidden_inputs(content),
+                        '__EVENTTARGET': target,
+                        '__EVENTARGUMENT': 'Next',
+                    }).encode())
+            else:
+                next_url = urljoin(url, self._search_regex(
+                    r'<div[^>]+class=["\']next["\'][^>]*>\s*<a[^>]+href=(["\'])(?P<url>(?:(?!\1).)+)\1',
+                    content, 'next page url', group='url', default=None))
+                if not next_url:
+                    break
+                content = self._download_webpage(next_url, category_id, f'Downloading page {page_num}')
 
     def _real_extract(self, url):
         category_id = self._match_id(url)
@@ -337,7 +438,7 @@ def _real_extract(self, url):
         if PolskieRadioAuditionIE.suitable(urlh.url):
             return self.url_result(urlh.url, PolskieRadioAuditionIE, category_id)
         title = self._html_search_regex(
-            r'<title>([^<]+) - [^<]+ - [^<]+</title>',
+            r'<title>([^<]+)(?: - [^<]+ - [^<]+| w [Pp]olskie[Rr]adio\.pl\s*)</title>',
             webpage, 'title', fatal=False)
         return self.playlist_result(
             self._entries(url, webpage, category_id),
@@ -409,7 +510,7 @@ def _real_extract(self, url):
                 })
 
         return {
-            'id': compat_str(channel['id']),
+            'id': str(channel['id']),
             'formats': formats,
             'title': channel.get('name') or channel.get('streamName'),
             'display_id': channel_url,
@@ -501,44 +602,8 @@ def _real_extract(self, url):
             podcast_id, 'Downloading podcast metadata',
             data=json.dumps({
                 'guids': [podcast_id],
-            }).encode('utf-8'),
+            }).encode(),
             headers={
                 'Content-Type': 'application/json',
             })
         return self._parse_episode(data[0])
-
-
-class PolskieRadioRadioKierowcowIE(PolskieRadioBaseExtractor):
-    _VALID_URL = r'https?://(?:www\.)?radiokierowcow\.pl/artykul/(?P<id>[0-9]+)'
-    IE_NAME = 'polskieradio:kierowcow'
-
-    _TESTS = [{
-        'url': 'https://radiokierowcow.pl/artykul/2694529',
-        'info_dict': {
-            'id': '2694529',
-            'title': 'Zielona fala reliktem przeszłości?',
-            'description': 'md5:343950a8717c9818fdfd4bd2b8ca9ff2',
-        },
-        'playlist_count': 3,
-    }]
-
-    def _real_extract(self, url):
-        media_id = self._match_id(url)
-        webpage = self._download_webpage(url, media_id)
-        nextjs_build = self._search_nextjs_data(webpage, media_id)['buildId']
-        article = self._download_json(
-            f'https://radiokierowcow.pl/_next/data/{nextjs_build}/artykul/{media_id}.json?articleId={media_id}',
-            media_id)
-        data = article['pageProps']['data']
-        title = data['title']
-        entries = self._extract_webpage_player_entries(data['content'], media_id, {
-            'title': title,
-        })
-
-        return {
-            '_type': 'playlist',
-            'id': media_id,
-            'entries': entries,
-            'title': title,
-            'description': data.get('lead'),
-        }