]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/periscope.py
[extractors] Use new framework for existing embeds (#4307)
[yt-dlp.git] / yt_dlp / extractor / periscope.py
1 from .common import InfoExtractor
2 from ..utils import (
3 int_or_none,
4 parse_iso8601,
5 unescapeHTML,
6 )
7
8
9 class PeriscopeBaseIE(InfoExtractor):
10 _M3U8_HEADERS = {
11 'Referer': 'https://www.periscope.tv/'
12 }
13
14 def _call_api(self, method, query, item_id):
15 return self._download_json(
16 'https://api.periscope.tv/api/v2/%s' % method,
17 item_id, query=query)
18
19 def _parse_broadcast_data(self, broadcast, video_id):
20 title = broadcast.get('status') or 'Periscope Broadcast'
21 uploader = broadcast.get('user_display_name') or broadcast.get('username')
22 title = '%s - %s' % (uploader, title) if uploader else title
23 is_live = broadcast.get('state').lower() == 'running'
24
25 thumbnails = [{
26 'url': broadcast[image],
27 } for image in ('image_url', 'image_url_small') if broadcast.get(image)]
28
29 return {
30 'id': broadcast.get('id') or video_id,
31 'title': title,
32 'timestamp': parse_iso8601(broadcast.get('created_at')),
33 'uploader': uploader,
34 'uploader_id': broadcast.get('user_id') or broadcast.get('username'),
35 'thumbnails': thumbnails,
36 'view_count': int_or_none(broadcast.get('total_watched')),
37 'tags': broadcast.get('tags'),
38 'is_live': is_live,
39 }
40
41 @staticmethod
42 def _extract_common_format_info(broadcast):
43 return broadcast.get('state').lower(), int_or_none(broadcast.get('width')), int_or_none(broadcast.get('height'))
44
45 @staticmethod
46 def _add_width_and_height(f, width, height):
47 for key, val in (('width', width), ('height', height)):
48 if not f.get(key):
49 f[key] = val
50
51 def _extract_pscp_m3u8_formats(self, m3u8_url, video_id, format_id, state, width, height, fatal=True):
52 m3u8_formats = self._extract_m3u8_formats(
53 m3u8_url, video_id, 'mp4',
54 entry_protocol='m3u8_native'
55 if state in ('ended', 'timed_out') else 'm3u8',
56 m3u8_id=format_id, fatal=fatal, headers=self._M3U8_HEADERS)
57 if len(m3u8_formats) == 1:
58 self._add_width_and_height(m3u8_formats[0], width, height)
59 for f in m3u8_formats:
60 f.setdefault('http_headers', {}).update(self._M3U8_HEADERS)
61 return m3u8_formats
62
63
64 class PeriscopeIE(PeriscopeBaseIE):
65 IE_DESC = 'Periscope'
66 IE_NAME = 'periscope'
67 _VALID_URL = r'https?://(?:www\.)?(?:periscope|pscp)\.tv/[^/]+/(?P<id>[^/?#]+)'
68 _EMBED_REGEX = [r'<iframe[^>]+src=([\'"])(?P<url>(?:https?:)?//(?:www\.)?(?:periscope|pscp)\.tv/(?:(?!\1).)+)\1']
69 # Alive example URLs can be found here https://www.periscope.tv/
70 _TESTS = [{
71 'url': 'https://www.periscope.tv/w/aJUQnjY3MjA3ODF8NTYxMDIyMDl2zCg2pECBgwTqRpQuQD352EMPTKQjT4uqlM3cgWFA-g==',
72 'md5': '65b57957972e503fcbbaeed8f4fa04ca',
73 'info_dict': {
74 'id': '56102209',
75 'ext': 'mp4',
76 'title': 'Bec Boop - ๐Ÿš โœˆ๏ธ๐Ÿ‡ฌ๐Ÿ‡ง Fly above #London in Emirates Air Line cable car at night ๐Ÿ‡ฌ๐Ÿ‡งโœˆ๏ธ๐Ÿš  #BoopScope ๐ŸŽ€๐Ÿ’—',
77 'timestamp': 1438978559,
78 'upload_date': '20150807',
79 'uploader': 'Bec Boop',
80 'uploader_id': '1465763',
81 },
82 'skip': 'Expires in 24 hours',
83 }, {
84 'url': 'https://www.periscope.tv/w/1ZkKzPbMVggJv',
85 'only_matching': True,
86 }, {
87 'url': 'https://www.periscope.tv/bastaakanoggano/1OdKrlkZZjOJX',
88 'only_matching': True,
89 }, {
90 'url': 'https://www.periscope.tv/w/1ZkKzPbMVggJv',
91 'only_matching': True,
92 }]
93
94 def _real_extract(self, url):
95 token = self._match_id(url)
96
97 stream = self._call_api(
98 'accessVideoPublic', {'broadcast_id': token}, token)
99
100 broadcast = stream['broadcast']
101 info = self._parse_broadcast_data(broadcast, token)
102
103 state = broadcast.get('state').lower()
104 width = int_or_none(broadcast.get('width'))
105 height = int_or_none(broadcast.get('height'))
106
107 def add_width_and_height(f):
108 for key, val in (('width', width), ('height', height)):
109 if not f.get(key):
110 f[key] = val
111
112 video_urls = set()
113 formats = []
114 for format_id in ('replay', 'rtmp', 'hls', 'https_hls', 'lhls', 'lhlsweb'):
115 video_url = stream.get(format_id + '_url')
116 if not video_url or video_url in video_urls:
117 continue
118 video_urls.add(video_url)
119 if format_id != 'rtmp':
120 m3u8_formats = self._extract_pscp_m3u8_formats(
121 video_url, token, format_id, state, width, height, False)
122 formats.extend(m3u8_formats)
123 continue
124 rtmp_format = {
125 'url': video_url,
126 'ext': 'flv' if format_id == 'rtmp' else 'mp4',
127 }
128 self._add_width_and_height(rtmp_format)
129 formats.append(rtmp_format)
130 self._sort_formats(formats)
131
132 info['formats'] = formats
133 return info
134
135
136 class PeriscopeUserIE(PeriscopeBaseIE):
137 _VALID_URL = r'https?://(?:www\.)?(?:periscope|pscp)\.tv/(?P<id>[^/]+)/?$'
138 IE_DESC = 'Periscope user videos'
139 IE_NAME = 'periscope:user'
140
141 _TEST = {
142 'url': 'https://www.periscope.tv/LularoeHusbandMike/',
143 'info_dict': {
144 'id': 'LularoeHusbandMike',
145 'title': 'LULAROE HUSBAND MIKE',
146 'description': 'md5:6cf4ec8047768098da58e446e82c82f0',
147 },
148 # Periscope only shows videos in the last 24 hours, so it's possible to
149 # get 0 videos
150 'playlist_mincount': 0,
151 }
152
153 def _real_extract(self, url):
154 user_name = self._match_id(url)
155
156 webpage = self._download_webpage(url, user_name)
157
158 data_store = self._parse_json(
159 unescapeHTML(self._search_regex(
160 r'data-store=(["\'])(?P<data>.+?)\1',
161 webpage, 'data store', default='{}', group='data')),
162 user_name)
163
164 user = list(data_store['UserCache']['users'].values())[0]['user']
165 user_id = user['id']
166 session_id = data_store['SessionToken']['public']['broadcastHistory']['token']['session_id']
167
168 broadcasts = self._call_api(
169 'getUserBroadcastsPublic',
170 {'user_id': user_id, 'session_id': session_id},
171 user_name)['broadcasts']
172
173 broadcast_ids = [
174 broadcast['id'] for broadcast in broadcasts if broadcast.get('id')]
175
176 title = user.get('display_name') or user.get('username') or user_name
177 description = user.get('description')
178
179 entries = [
180 self.url_result(
181 'https://www.periscope.tv/%s/%s' % (user_name, broadcast_id))
182 for broadcast_id in broadcast_ids]
183
184 return self.playlist_result(entries, user_id, title, description)