From 4b91f5d702ca592fe25ff7047b082320b76b1166 Mon Sep 17 00:00:00 2001 From: doe1080 <98906116+doe1080@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:10:16 +0900 Subject: [PATCH] [ie/twitter] Rework broadcast extraction (#18111) Authored by: doe1080 --- yt_dlp/extractor/_extractors.py | 5 +- yt_dlp/extractor/periscope.py | 181 --------------------- yt_dlp/extractor/twitter.py | 277 ++++++++++++++++++-------------- 3 files changed, 158 insertions(+), 305 deletions(-) delete mode 100644 yt_dlp/extractor/periscope.py diff --git a/yt_dlp/extractor/_extractors.py b/yt_dlp/extractor/_extractors.py index 8006734b28..b24a1be0ef 100644 --- a/yt_dlp/extractor/_extractors.py +++ b/yt_dlp/extractor/_extractors.py @@ -1396,10 +1396,6 @@ from .peloton import ( PelotonLiveIE, ) from .performgroup import PerformGroupIE -from .periscope import ( - PeriscopeIE, - PeriscopeUserIE, -) from .pgatour import PGATourIE from .philharmoniedeparis import PhilharmonieDeParisIE from .phoenix import PhoenixIE @@ -2096,6 +2092,7 @@ from .twitter import ( TwitterAmplifyIE, TwitterBroadcastIE, TwitterCardIE, + TwitterEventIE, TwitterIE, TwitterShortenerIE, TwitterSpacesIE, diff --git a/yt_dlp/extractor/periscope.py b/yt_dlp/extractor/periscope.py deleted file mode 100644 index 97ed7ad8dd..0000000000 --- a/yt_dlp/extractor/periscope.py +++ /dev/null @@ -1,181 +0,0 @@ -from .common import InfoExtractor -from ..utils import ( - clean_html, - int_or_none, - parse_iso8601, - str_or_none, - unescapeHTML, - url_or_none, -) -from ..utils.traversal import traverse_obj - - -class PeriscopeBaseIE(InfoExtractor): - _M3U8_HEADERS = { - 'Referer': 'https://www.periscope.tv/', - } - - def _call_api(self, method, query, item_id): - return self._download_json( - f'https://api.periscope.tv/api/v2/{method}', - item_id, query=query) - - def _parse_broadcast_data(self, broadcast, video_id): - return { - 'display_id': video_id, - 'live_status': { - 'running': 'is_live', - 'not_started': 'is_upcoming', - }.get(traverse_obj(broadcast, ('state', {str.lower}))) or 'was_live', - **traverse_obj(broadcast, { - 'id': ('id', {str_or_none}), - 'title': ('status', {clean_html}, filter), - 'concurrent_view_count': ('total_watching', {int_or_none}), - 'release_timestamp': (('scheduled_start_ms', 'start_ms'), {int_or_none(scale=1000)}, any), - 'tags': ('tags', ..., {clean_html}, filter, all, filter), - 'thumbnails': (('image_url_small', 'image_url_medium', 'image_url'), {'url': {url_or_none}}), - 'timestamp': ((('created_at', {parse_iso8601}), ('created_at_ms', {int_or_none(scale=1000)})), any), - 'uploader': ('user_display_name', {clean_html}, filter), - 'uploader_id': ('username', {clean_html}, filter), - 'view_count': ('total_watched', {int_or_none}), - }), - } - - @staticmethod - def _extract_common_format_info(broadcast): - return broadcast.get('state').lower(), int_or_none(broadcast.get('width')), int_or_none(broadcast.get('height')) - - @staticmethod - def _add_width_and_height(f, width, height): - for key, val in (('width', width), ('height', height)): - if not f.get(key): - f[key] = val - - def _extract_pscp_m3u8_formats(self, m3u8_url, video_id, format_id, state, width, height, fatal=True): - m3u8_formats = self._extract_m3u8_formats( - m3u8_url, video_id, 'mp4', - entry_protocol='m3u8_native' - if state in ('ended', 'timed_out') else 'm3u8', - m3u8_id=format_id, fatal=fatal, headers=self._M3U8_HEADERS) - if len(m3u8_formats) == 1: - self._add_width_and_height(m3u8_formats[0], width, height) - for f in m3u8_formats: - f.setdefault('http_headers', {}).update(self._M3U8_HEADERS) - return m3u8_formats - - -class PeriscopeIE(PeriscopeBaseIE): - IE_DESC = 'Periscope' - IE_NAME = 'periscope' - _VALID_URL = r'https?://(?:www\.)?(?:periscope|pscp)\.tv/[^/?#]+/(?P[^/?#]+)' - _EMBED_REGEX = [r']+src=([\'"])(?P(?:https?:)?//(?:www\.)?(?:periscope|pscp)\.tv/(?:(?!\1).)+)\1'] - _TESTS = [{ - 'url': 'https://www.periscope.tv/LularoeHusbandMike/1mrGmgaXAVqxy', - 'info_dict': { - 'id': '1mrGmgaXAVqxy', - 'ext': 'mp4', - 'title': 'πŸŽ‰πŸ‘πŸΌ BROWSE OUR ENTIRE 1,900 +PIECE INVENTORY! πŸ‘πŸΌπŸŽ‰ #lularoe', - 'live_status': 'was_live', - 'tags': 'count:1', - 'thumbnail': r're:https?://prod-fastly-us-east-1\.video\.pscp\.tv/.+', - 'timestamp': 1498621952, - 'upload_date': '20170628', - 'uploader': 'LuLaRoe Husband Mike', - 'uploader_id': 'LularoeHusbandMike', - }, - }, { - 'url': 'https://www.periscope.tv/w/1ZkKzPbMVggJv', - 'only_matching': True, - }, { - 'url': 'https://www.periscope.tv/bastaakanoggano/1OdKrlkZZjOJX', - 'only_matching': True, - }, { - 'url': 'https://www.periscope.tv/w/1ZkKzPbMVggJv', - 'only_matching': True, - }] - - def _real_extract(self, url): - token = self._match_id(url) - - stream = self._call_api( - 'accessVideoPublic', {'broadcast_id': token}, token) - - broadcast = stream['broadcast'] - info = self._parse_broadcast_data(broadcast, token) - - state = broadcast.get('state').lower() - width = int_or_none(broadcast.get('width')) - height = int_or_none(broadcast.get('height')) - - video_urls = set() - formats = [] - for format_id in ('replay', 'rtmp', 'hls', 'https_hls', 'lhls', 'lhlsweb'): - video_url = stream.get(format_id + '_url') - if not video_url or video_url in video_urls: - continue - video_urls.add(video_url) - if format_id != 'rtmp': - m3u8_formats = self._extract_pscp_m3u8_formats( - video_url, token, format_id, state, width, height, False) - formats.extend(m3u8_formats) - continue - rtmp_format = { - 'url': video_url, - 'ext': 'flv' if format_id == 'rtmp' else 'mp4', - } - self._add_width_and_height(rtmp_format, width, height) - formats.append(rtmp_format) - - info['formats'] = formats - return info - - -class PeriscopeUserIE(PeriscopeBaseIE): - _VALID_URL = r'https?://(?:www\.)?(?:periscope|pscp)\.tv/(?P[^/]+)/?$' - IE_DESC = 'Periscope user videos' - IE_NAME = 'periscope:user' - - _TEST = { - 'url': 'https://www.periscope.tv/LularoeHusbandMike/', - 'info_dict': { - 'id': 'LularoeHusbandMike', - 'title': 'LULAROE HUSBAND MIKE', - 'description': 'md5:6cf4ec8047768098da58e446e82c82f0', - }, - # Periscope only shows videos in the last 24 hours, so it's possible to - # get 0 videos - 'playlist_mincount': 0, - } - - def _real_extract(self, url): - user_name = self._match_id(url) - - webpage = self._download_webpage(url, user_name) - - data_store = self._parse_json( - unescapeHTML(self._search_regex( - r'data-store=(["\'])(?P.+?)\1', - webpage, 'data store', default='{}', group='data')), - user_name) - - user = next(iter(data_store['UserCache']['users'].values()))['user'] - user_id = user['id'] - session_id = data_store['SessionToken']['public']['broadcastHistory']['token']['session_id'] - - broadcasts = self._call_api( - 'getUserBroadcastsPublic', - {'user_id': user_id, 'session_id': session_id}, - user_name)['broadcasts'] - - broadcast_ids = [ - broadcast['id'] for broadcast in broadcasts if broadcast.get('id')] - - title = user.get('display_name') or user.get('username') or user_name - description = user.get('description') - - entries = [ - self.url_result( - f'https://www.periscope.tv/{user_name}/{broadcast_id}') - for broadcast_id in broadcast_ids] - - return self.playlist_result(entries, user_id, title, description) diff --git a/yt_dlp/extractor/twitter.py b/yt_dlp/extractor/twitter.py index 5478318450..2051db84bf 100644 --- a/yt_dlp/extractor/twitter.py +++ b/yt_dlp/extractor/twitter.py @@ -1,3 +1,4 @@ +import datetime as dt import functools import json import math @@ -5,7 +6,6 @@ import re import urllib.parse from .common import InfoExtractor -from .periscope import PeriscopeBaseIE, PeriscopeIE from ..jsinterp import js_number_to_string from ..networking.exceptions import HTTPError from ..utils import ( @@ -18,15 +18,19 @@ from ..utils import ( int_or_none, join_nonempty, make_archive_id, + parse_qs, remove_end, + smuggle_url, str_or_none, strip_or_none, truncate_string, try_call, try_get, unified_timestamp, + unsmuggle_url, update_url_query, url_or_none, + urljoin, xpath_text, ) from ..utils.traversal import require, traverse_obj @@ -400,20 +404,6 @@ class TwitterIE(TwitterBaseIE): 'age_limit': 0, '_old_archive_ids': ['twitter 719944021058060289'], }, - }, { - 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384', - 'info_dict': { - 'id': '1zqKVVlkqLaKB', - 'ext': 'mp4', - 'title': 'Sgt Kerry Schmidt - Ontario Provincial Police - Road rage, mischief, assault, rollover and fire in one occurrence', - 'upload_date': '20160923', - 'uploader_id': '1PmKqpJdOJQoY', - 'uploader': 'Sgt Kerry Schmidt - Ontario Provincial Police', - 'timestamp': 1474613214, - 'thumbnail': r're:^https?://.*\.jpg', - }, - 'add_ie': ['Periscope'], - 'skip': 'Broadcast not found', }, { # has mp4 formats via mobile API 'url': 'https://twitter.com/news_al3alm/status/852138619213144067', @@ -516,20 +506,24 @@ class TwitterIE(TwitterBaseIE): }, 'skip': 'This Tweet is unavailable', }, { - # not available in Periscope - 'url': 'https://twitter.com/ViviEducation/status/1136534865145286656', + 'url': 'https://x.com/SpaceX/status/2077785645645209727', 'info_dict': { - 'id': '1vOGwqejwoWxB', + 'id': '1MKgNNXAZdmxL', 'ext': 'mp4', - 'title': 'Vivi - Vivi founder @lior_rauchy announcing our new student feedback tool live at @EduTECH_AU #EduTECH2019', - 'uploader': 'Vivi', - 'uploader_id': '1eVjYOLGkGrQL', - 'thumbnail': r're:^https?://.*\.jpg', - 'tags': ['EduTECH2019'], + 'title': 'Starship\'s Thirteenth Flight Test', + 'concurrent_view_count': int, + 'live_status': 'was_live', + 'release_date': '20260716', + 'release_timestamp': 1784239800, + 'thumbnail': r're:https?://.+', + 'timestamp': 1784239795, + 'upload_date': '20260716', + 'uploader': 'SpaceX', + 'uploader_id': 'SpaceX', + 'uploader_url': 'https://x.com/SpaceX', 'view_count': int, }, 'add_ie': ['TwitterBroadcast'], - 'skip': 'Broadcast no longer exists', }, { # unified card 'url': 'https://twitter.com/BrooklynNets/status/1349794411333394432?s=20', @@ -1288,12 +1282,6 @@ class TwitterIE(TwitterBaseIE): '_type': 'url', 'url': get_binding_value('player_url'), } - elif card_name == 'periscope_broadcast': - yield { - '_type': 'url', - 'url': get_binding_value('url') or get_binding_value('player_url'), - 'ie_key': PeriscopeIE.ie_key(), - } elif card_name == 'broadcast': yield { '_type': 'url', @@ -1447,69 +1435,150 @@ class TwitterAmplifyIE(TwitterBaseIE): } -class TwitterBroadcastIE(TwitterBaseIE, PeriscopeBaseIE): +class TwitterBroadcastIE(TwitterBaseIE): IE_NAME = 'twitter:broadcast' - _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/(?Pbroadcasts|events)/(?P\w+)' + _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/broadcasts/(?P\w+)' _TESTS = [{ # Untitled broadcast - 'url': 'https://twitter.com/i/broadcasts/1yNGaQLWpejGj', + 'url': 'https://x.com/i/broadcasts/1yNGaQLWpejGj', 'info_dict': { 'id': '1yNGaQLWpejGj', 'ext': 'mp4', - 'title': 'Andrea May Sahouri - Twitter Broadcast', - 'display_id': '1yNGaQLWpejGj', - 'uploader': 'Andrea May Sahouri', - 'uploader_id': 'andreamsahouri', - 'uploader_url': 'https://twitter.com/andreamsahouri', - 'release_date': '20200601', - 'release_timestamp': 1590973647, - 'timestamp': 1590973638, - 'upload_date': '20200601', - 'thumbnail': r're:^https?://[^?#]+\.jpg\?token=', - 'view_count': int, + 'title': 'Andrea May Sahouri - X Broadcast', 'concurrent_view_count': int, 'live_status': 'was_live', + 'thumbnail': r're:https?://.+', + 'timestamp': 1590973647, + 'upload_date': '20200601', + 'uploader': 'Andrea May Sahouri', + 'uploader_id': 'andreamsahouri', + 'uploader_url': 'https://x.com/andreamsahouri', + 'view_count': int, }, }, { - 'url': 'https://twitter.com/i/broadcasts/1ZkKzeyrPbaxv', + 'url': 'https://x.com/i/broadcasts/1ZkKzeyrPbaxv', 'info_dict': { 'id': '1ZkKzeyrPbaxv', 'ext': 'mp4', 'title': 'Starship | SN10 | High-Altitude Flight Test', - 'display_id': '1ZkKzeyrPbaxv', - 'uploader': 'SpaceX', - 'uploader_id': 'SpaceX', - 'uploader_url': 'https://twitter.com/SpaceX', - 'release_date': '20210303', - 'release_timestamp': 1614812964, - 'timestamp': 1614812942, - 'upload_date': '20210303', - 'thumbnail': r're:^https?://[^?#]+\.jpg\?token=', - 'view_count': int, 'concurrent_view_count': int, 'live_status': 'was_live', + 'thumbnail': r're:https?://.+', + 'timestamp': 1614812964, + 'upload_date': '20210303', + 'uploader': 'SpaceX', + 'uploader_id': 'SpaceX', + 'uploader_url': 'https://x.com/SpaceX', + 'view_count': int, }, }, { - 'url': 'https://twitter.com/i/broadcasts/1OyKAVQrgzwGb', + 'url': 'https://x.com/i/broadcasts/1OyKAVQrgzwGb', 'info_dict': { 'id': '1OyKAVQrgzwGb', 'ext': 'mp4', 'title': 'Starship Flight Test', - 'display_id': '1OyKAVQrgzwGb', - 'uploader': 'SpaceX', - 'uploader_id': 'SpaceX', - 'uploader_url': 'https://twitter.com/SpaceX', - 'release_date': '20230420', - 'release_timestamp': 1681994486, - 'timestamp': 1681993964, - 'upload_date': '20230420', - 'thumbnail': r're:^https?://[^?#]+\.jpg\?token=', - 'view_count': int, 'concurrent_view_count': int, 'live_status': 'was_live', + 'thumbnail': r're:https?://.+', + 'timestamp': 1681994486, + 'upload_date': '20230420', + 'uploader': 'SpaceX', + 'uploader_id': 'SpaceX', + 'uploader_url': 'https://x.com/SpaceX', + 'view_count': int, }, - }, { + }] + + def _build_graphql_query(self, broadcast_id): + return {'variables': {'id': broadcast_id}} + + def _real_extract(self, url): + url, smuggled_data = unsmuggle_url(url, {}) + display_id = self._match_id(url) + graphql = self._call_graphql_api('0THBwNgta8LrS-cno61adw/BroadcastQuery', display_id) + broadcast = traverse_obj(graphql, ('broadcast', {dict})) + + broadcast_id = traverse_obj(broadcast, ('broadcast_id', {str})) + live_status = { + 'notstarted': 'is_upcoming', + 'prepublished': 'is_upcoming', + 'running': 'is_live', + 'canceled': 'was_live', + 'ended': 'was_live', + 'timedout': 'was_live', + }.get(traverse_obj(broadcast, ('state', {str.lower}))) + if not broadcast_id or ( + live_status == 'was_live' + and not traverse_obj(broadcast, ('available_for_replay', {bool})) + ): + raise ExtractorError('This broadcast is no longer available', expected=True) + + release_timestamp = traverse_obj(broadcast, ( + 'scheduled_start_time', {int_or_none(scale=1000)})) + + if live_status == 'is_upcoming': + if release_timestamp is not None: + start_time = dt.datetime.fromtimestamp( + release_timestamp, dt.UTC, + ).astimezone().strftime('%Y-%m-%d %H:%M:%S %Z') + msg = f'This broadcast is scheduled to start at {start_time}' + else: + msg = 'This broadcast has not yet started' + + self.raise_no_formats(msg, expected=True) + + return { + 'id': broadcast_id, + 'live_status': live_status, + 'release_timestamp': release_timestamp, + } + + media_key = traverse_obj(broadcast, ( + 'media_key', {str}, filter, any, {require('media key')})) + stream = self._call_api(f'live_video_stream/status/{media_key}', broadcast_id) + m3u8_url = traverse_obj(stream, ( + 'source', ('noRedirectPlaybackUrl', 'location'), {url_or_none}, any)) + if m3u8_url and '/live_video_stream/geoblocked/' in m3u8_url: + self.raise_geo_restricted() + + formats = self._extract_m3u8_formats( + m3u8_url, broadcast_id, 'mp4', + m3u8_id=traverse_obj(m3u8_url, ({parse_qs}, 'type', -1))) + if len(formats) == 1: + fmt = formats[0] + for key in ('height', 'width'): + if not fmt.get(key): + fmt[key] = traverse_obj(broadcast, (key, {int_or_none})) + + return { + 'id': broadcast_id, + 'display_id': smuggled_data.get('display_id', display_id), + 'formats': formats, + 'live_status': live_status, + 'release_timestamp': release_timestamp, + **traverse_obj(broadcast, ('user_results', 'result', 'core', { + 'title': ('name', {clean_html}, + {lambda name: join_nonempty(name, 'X Broadcast', delim=' - ')}), + 'uploader': ('name', {clean_html}, filter), + 'uploader_id': ('screen_name', {str}, filter), + 'uploader_url': ('screen_name', {urljoin('https://x.com/')}), + })), + **traverse_obj(broadcast, { + 'title': ('status', {clean_html}, filter), + 'concurrent_view_count': ('total_watching', {int_or_none}), + 'thumbnails': (('image_url_small', 'image_url_medium', 'image_url'), {'url': {url_or_none}}), + 'timestamp': ('start_time', {int_or_none(scale=1000)}), + 'view_count': ('total_watched', {int_or_none}), + }), + } + + +class TwitterEventIE(TwitterBaseIE): + IE_NAME = 'twitter:event' + + _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/events/(?P\d+)' + _TESTS = [{ 'url': 'https://x.com/i/events/1910629646300762112', 'info_dict': { 'id': '1LyxBWDRNqyKN', @@ -1520,13 +1589,12 @@ class TwitterBroadcastIE(TwitterBaseIE, PeriscopeBaseIE): 'live_status': 'was_live', 'release_date': '20250423', 'release_timestamp': 1745409000, - 'tags': ['ガンニバル'], - 'thumbnail': r're:https?://[^?#]+\.jpg\?token=', - 'timestamp': 1745403328, + 'thumbnail': r're:https?://.+', + 'timestamp': 1745408996, 'upload_date': '20250423', 'uploader': 'ディズニープラス公式', 'uploader_id': 'DisneyPlusJP', - 'uploader_url': 'https://twitter.com/DisneyPlusJP', + 'uploader_url': 'https://x.com/DisneyPlusJP', 'view_count': int, }, }, { @@ -1539,59 +1607,28 @@ class TwitterBroadcastIE(TwitterBaseIE, PeriscopeBaseIE): }] def _real_extract(self, url): - broadcast_type, display_id = self._match_valid_url(url).group('type', 'id') + event_id = self._match_id(url) + timeline = self._call_api( + f'live_event/1/{event_id}/timeline.json', event_id) + twitter_objects = traverse_obj(timeline, ('twitter_objects', {dict})) - if broadcast_type == 'events': - timeline = self._call_api( - f'live_event/1/{display_id}/timeline.json', display_id) - twitter_objects = traverse_obj(timeline, ('twitter_objects', {dict})) - if tweet_ids := traverse_obj(twitter_objects, ( - 'tweets', ..., 'id_str', {str}, - )): - event_title = traverse_obj(twitter_objects, ( - 'live_events', display_id, 'title', {clean_html}, filter)) + if tweet_ids := traverse_obj(twitter_objects, ( + 'tweets', ..., 'id_str', {str}, + )): + event_title = traverse_obj(twitter_objects, ( + 'live_events', event_id, 'title', {clean_html}, filter)) - return self.playlist_result([self.url_result( - f'https://twitter.com/i/web/status/{tweet_id}', TwitterIE, - ) for tweet_id in tweet_ids], display_id, event_title) + return self.playlist_result([self.url_result( + f'https://x.com/i/web/status/{tweet_id}', TwitterIE, + ) for tweet_id in tweet_ids], event_id, event_title) - broadcast_id = traverse_obj(twitter_objects, ( - 'broadcasts', ..., ('id', 'broadcast_id'), - {str}, any, {require('broadcast ID')})) - else: - broadcast_id = display_id + broadcast_id = traverse_obj(twitter_objects, ( + 'broadcasts', ..., ('id', 'broadcast_id'), {str}, any, {require('broadcast ID')})) - broadcast = self._call_api( - 'broadcasts/show.json', broadcast_id, - {'ids': broadcast_id})['broadcasts'][broadcast_id] - if not broadcast: - raise ExtractorError('Broadcast no longer exists', expected=True) - info = self._parse_broadcast_data(broadcast, broadcast_id) - info.update({ - 'display_id': display_id, - 'title': traverse_obj(broadcast, ( - 'status', {clean_html}, filter, - )) or join_nonempty(info.get('uploader'), 'Twitter Broadcast', delim=' - '), - 'uploader_id': broadcast.get('twitter_username') or info.get('uploader_id'), - 'uploader_url': format_field( - broadcast, 'twitter_username', 'https://twitter.com/%s', default=None), - }) - if info['live_status'] == 'is_upcoming': - self.raise_no_formats('This live broadcast has not yet started', expected=True) - return info - - media_key = broadcast['media_key'] - source = self._call_api( - f'live_video_stream/status/{media_key}', media_key)['source'] - m3u8_url = source.get('noRedirectPlaybackUrl') or source['location'] - if '/live_video_stream/geoblocked/' in m3u8_url: - self.raise_geo_restricted() - m3u8_id = urllib.parse.parse_qs(urllib.parse.urlparse( - m3u8_url).query).get('type', [None])[0] - state, width, height = self._extract_common_format_info(broadcast) - info['formats'] = self._extract_pscp_m3u8_formats( - m3u8_url, broadcast_id, m3u8_id, state, width, height) - return info + return self.url_result(smuggle_url( + f'https://x.com/i/broadcasts/{broadcast_id}', + {'display_id': event_id}, + ), TwitterBroadcastIE) class TwitterSpacesIE(TwitterBaseIE):