[ie/youtube:tab] Fix playlists tab extraction (#11615)
[yt-dlp3.git] / yt_dlp / extractor / loom.py
blobb0878c33e265bfd5b3effd9ed061290b995ac3aa
1 import json
2 import textwrap
3 import urllib.parse
4 import uuid
6 from .common import InfoExtractor
7 from ..utils import (
8 ExtractorError,
9 determine_ext,
10 filter_dict,
11 get_first,
12 int_or_none,
13 parse_iso8601,
14 update_url,
15 url_or_none,
16 variadic,
18 from ..utils.traversal import traverse_obj
21 class LoomIE(InfoExtractor):
22 IE_NAME = 'loom'
23 _VALID_URL = r'https?://(?:www\.)?loom\.com/(?:share|embed)/(?P<id>[\da-f]{32})'
24 _EMBED_REGEX = [rf'<iframe[^>]+\bsrc=["\'](?P<url>{_VALID_URL})']
25 _TESTS = [{
26 # m3u8 raw-url, mp4 transcoded-url, cdn url == raw-url, json subs only
27 'url': 'https://www.loom.com/share/43d05f362f734614a2e81b4694a3a523',
28 'md5': 'bfc2d7e9c2e0eb4813212230794b6f42',
29 'info_dict': {
30 'id': '43d05f362f734614a2e81b4694a3a523',
31 'ext': 'mp4',
32 'title': 'A Ruler for Windows - 28 March 2022',
33 'uploader': 'wILLIAM PIP',
34 'upload_date': '20220328',
35 'timestamp': 1648454238,
36 'duration': 27,
38 }, {
39 # webm raw-url, mp4 transcoded-url, cdn url == transcoded-url, no subs
40 'url': 'https://www.loom.com/share/c43a642f815f4378b6f80a889bb73d8d',
41 'md5': '70f529317be8cf880fcc2c649a531900',
42 'info_dict': {
43 'id': 'c43a642f815f4378b6f80a889bb73d8d',
44 'ext': 'webm',
45 'title': 'Lilah Nielsen Intro Video',
46 'uploader': 'Lilah Nielsen',
47 'upload_date': '20200826',
48 'timestamp': 1598480716,
49 'duration': 20,
51 }, {
52 # m3u8 raw-url, mp4 transcoded-url, cdn url == raw-url, vtt sub and json subs
53 'url': 'https://www.loom.com/share/9458bcbf79784162aa62ffb8dd66201b',
54 'md5': '51737ec002969dd28344db4d60b9cbbb',
55 'info_dict': {
56 'id': '9458bcbf79784162aa62ffb8dd66201b',
57 'ext': 'mp4',
58 'title': 'Sharing screen with gpt-4',
59 'description': 'Sharing screen with GPT 4 vision model and asking questions to guide through blender.',
60 'uploader': 'Suneel Matham',
61 'chapters': 'count:3',
62 'upload_date': '20231109',
63 'timestamp': 1699518978,
64 'duration': 93,
66 }, {
67 # mpd raw-url, mp4 transcoded-url, cdn url == raw-url, no subs
68 'url': 'https://www.loom.com/share/24351eb8b317420289b158e4b7e96ff2',
69 'info_dict': {
70 'id': '24351eb8b317420289b158e4b7e96ff2',
71 'ext': 'webm',
72 'title': 'OMFG clown',
73 'description': 'md5:285c5ee9d62aa087b7e3271b08796815',
74 'uploader': 'MrPumkin B',
75 'upload_date': '20210924',
76 'timestamp': 1632519618,
77 'duration': 210,
79 'params': {'skip_download': 'dash'},
80 }, {
81 # password-protected
82 'url': 'https://www.loom.com/share/50e26e8aeb7940189dff5630f95ce1f4',
83 'md5': '5cc7655e7d55d281d203f8ffd14771f7',
84 'info_dict': {
85 'id': '50e26e8aeb7940189dff5630f95ce1f4',
86 'ext': 'mp4',
87 'title': 'iOS Mobile Upload',
88 'uploader': 'Simon Curran',
89 'upload_date': '20200520',
90 'timestamp': 1590000123,
91 'duration': 35,
93 'params': {'videopassword': 'seniorinfants2'},
94 }, {
95 # embed, transcoded-url endpoint sends empty JSON response, split video and audio HLS formats
96 'url': 'https://www.loom.com/embed/ddcf1c1ad21f451ea7468b1e33917e4e',
97 'md5': 'b321d261656848c184a94e3b93eae28d',
98 'info_dict': {
99 'id': 'ddcf1c1ad21f451ea7468b1e33917e4e',
100 'ext': 'mp4',
101 'title': 'CF Reset User\'s Password',
102 'uploader': 'Aimee Heintz',
103 'upload_date': '20220707',
104 'timestamp': 1657216459,
105 'duration': 181,
107 'params': {'format': 'bestvideo'}, # Test video-only fixup
108 'expected_warnings': ['Failed to parse JSON'],
110 _WEBPAGE_TESTS = [{
111 'url': 'https://www.loom.com/community/e1229802a8694a09909e8ba0fbb6d073-pg',
112 'md5': 'ec838cd01b576cf0386f32e1ae424609',
113 'info_dict': {
114 'id': 'e1229802a8694a09909e8ba0fbb6d073',
115 'ext': 'mp4',
116 'title': 'Rexie Jane Cimafranca - Founder\'s Presentation',
117 'uploader': 'Rexie Cimafranca',
118 'upload_date': '20230213',
119 'duration': 247,
120 'timestamp': 1676274030,
124 _GRAPHQL_VARIABLES = {
125 'GetVideoSource': {
126 'acceptableMimes': ['DASH', 'M3U8', 'MP4'],
129 _GRAPHQL_QUERIES = {
130 'GetVideoSSR': textwrap.dedent('''\
131 query GetVideoSSR($videoId: ID!, $password: String) {
132 getVideo(id: $videoId, password: $password) {
133 __typename
134 ... on PrivateVideo {
136 status
137 message
138 __typename
140 ... on VideoPasswordMissingOrIncorrect {
142 message
143 __typename
145 ... on RegularUserVideo {
147 __typename
148 createdAt
149 description
150 download_enabled
151 folder_id
152 is_protected
153 needs_password
154 owner {
155 display_name
156 __typename
158 privacy
159 s3_id
160 name
161 video_properties {
162 avgBitRate
163 client
164 camera_enabled
165 client_version
166 duration
167 durationMs
168 format
169 height
170 microphone_enabled
172 os_version
173 recordingClient
174 recording_type
175 recording_version
176 screen_type
177 tab_audio
178 trim_duration
179 width
180 __typename
182 playable_duration
183 source_duration
184 visibility
187 }\n'''),
188 'GetVideoSource': textwrap.dedent('''\
189 query GetVideoSource($videoId: ID!, $password: String, $acceptableMimes: [CloudfrontVideoAcceptableMime]) {
190 getVideo(id: $videoId, password: $password) {
191 ... on RegularUserVideo {
193 nullableRawCdnUrl(acceptableMimes: $acceptableMimes, password: $password) {
195 __typename
197 __typename
199 __typename
201 }\n'''),
202 'FetchVideoTranscript': textwrap.dedent('''\
203 query FetchVideoTranscript($videoId: ID!, $password: String) {
204 fetchVideoTranscript(videoId: $videoId, password: $password) {
205 ... on VideoTranscriptDetails {
207 video_id
208 source_url
209 captions_source_url
210 __typename
212 ... on GenericError {
213 message
214 __typename
216 __typename
218 }\n'''),
219 'FetchChapters': textwrap.dedent('''\
220 query FetchChapters($videoId: ID!, $password: String) {
221 fetchVideoChapters(videoId: $videoId, password: $password) {
222 ... on VideoChapters {
223 video_id
224 content
225 __typename
227 ... on EmptyChaptersPayload {
228 content
229 __typename
231 ... on InvalidRequestWarning {
232 message
233 __typename
235 ... on Error {
236 message
237 __typename
239 __typename
241 }\n'''),
243 _APOLLO_GRAPHQL_VERSION = '0a1856c'
245 def _call_graphql_api(self, operations, video_id, note=None, errnote=None):
246 password = self.get_param('videopassword')
247 return self._download_json(
248 'https://www.loom.com/graphql', video_id, note or 'Downloading GraphQL JSON',
249 errnote or 'Failed to download GraphQL JSON', headers={
250 'Accept': 'application/json',
251 'Content-Type': 'application/json',
252 'x-loom-request-source': f'loom_web_{self._APOLLO_GRAPHQL_VERSION}',
253 'apollographql-client-name': 'web',
254 'apollographql-client-version': self._APOLLO_GRAPHQL_VERSION,
255 }, data=json.dumps([{
256 'operationName': operation_name,
257 'variables': {
258 'videoId': video_id,
259 'password': password,
260 **self._GRAPHQL_VARIABLES.get(operation_name, {}),
262 'query': self._GRAPHQL_QUERIES[operation_name],
263 } for operation_name in variadic(operations)], separators=(',', ':')).encode())
265 def _call_url_api(self, endpoint, video_id):
266 response = self._download_json(
267 f'https://www.loom.com/api/campaigns/sessions/{video_id}/{endpoint}', video_id,
268 f'Downloading {endpoint} JSON', f'Failed to download {endpoint} JSON', fatal=False,
269 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
270 data=json.dumps({
271 'anonID': str(uuid.uuid4()),
272 'deviceID': None,
273 'force_original': False, # HTTP error 401 if True
274 'password': self.get_param('videopassword'),
275 }, separators=(',', ':')).encode())
276 return traverse_obj(response, ('url', {url_or_none}))
278 def _extract_formats(self, video_id, metadata, gql_data):
279 formats = []
280 video_properties = traverse_obj(metadata, ('video_properties', {
281 'width': ('width', {int_or_none}),
282 'height': ('height', {int_or_none}),
283 'acodec': ('microphone_enabled', {lambda x: 'none' if x is False else None}),
286 def get_formats(format_url, format_id, quality):
287 if not format_url:
288 return
289 ext = determine_ext(format_url)
290 query = urllib.parse.urlparse(format_url).query
292 if ext == 'm3u8':
293 # Extract pre-merged HLS formats to avoid buggy parsing of metadata in split playlists
294 format_url = format_url.replace('-split.m3u8', '.m3u8')
295 m3u8_formats = self._extract_m3u8_formats(
296 format_url, video_id, 'mp4', m3u8_id=f'hls-{format_id}', fatal=False, quality=quality)
297 # Sometimes only split video/audio formats are available, need to fixup video-only formats
298 is_not_premerged = 'none' in traverse_obj(m3u8_formats, (..., 'vcodec'))
299 for fmt in m3u8_formats:
300 if is_not_premerged and fmt.get('vcodec') != 'none':
301 fmt['acodec'] = 'none'
302 yield {
303 **fmt,
304 'url': update_url(fmt['url'], query=query),
305 'extra_param_to_segment_url': query,
308 elif ext == 'mpd':
309 dash_formats = self._extract_mpd_formats(
310 format_url, video_id, mpd_id=f'dash-{format_id}', fatal=False)
311 for fmt in dash_formats:
312 yield {
313 **fmt,
314 'extra_param_to_segment_url': query,
315 'quality': quality,
318 else:
319 yield {
320 'url': format_url,
321 'ext': ext,
322 'format_id': f'http-{format_id}',
323 'quality': quality,
324 **video_properties,
327 raw_url = self._call_url_api('raw-url', video_id)
328 formats.extend(get_formats(raw_url, 'raw', quality=1)) # original quality
330 transcoded_url = self._call_url_api('transcoded-url', video_id)
331 formats.extend(get_formats(transcoded_url, 'transcoded', quality=-1)) # transcoded quality
333 cdn_url = get_first(gql_data, ('data', 'getVideo', 'nullableRawCdnUrl', 'url', {url_or_none}))
334 # cdn_url is usually a dupe, but the raw-url/transcoded-url endpoints could return errors
335 valid_urls = [update_url(url, query=None) for url in (raw_url, transcoded_url) if url]
336 if cdn_url and update_url(cdn_url, query=None) not in valid_urls:
337 formats.extend(get_formats(cdn_url, 'cdn', quality=0)) # could be original or transcoded
339 return formats
341 def _real_extract(self, url):
342 video_id = self._match_id(url)
343 metadata = get_first(
344 self._call_graphql_api('GetVideoSSR', video_id, 'Downloading GraphQL metadata JSON'),
345 ('data', 'getVideo', {dict})) or {}
347 if metadata.get('__typename') == 'VideoPasswordMissingOrIncorrect':
348 if not self.get_param('videopassword'):
349 raise ExtractorError(
350 'This video is password-protected, use the --video-password option', expected=True)
351 raise ExtractorError('Invalid video password', expected=True)
353 gql_data = self._call_graphql_api(['FetchChapters', 'FetchVideoTranscript', 'GetVideoSource'], video_id)
354 duration = traverse_obj(metadata, ('video_properties', 'duration', {int_or_none}))
356 return {
357 'id': video_id,
358 'duration': duration,
359 'chapters': self._extract_chapters_from_description(
360 get_first(gql_data, ('data', 'fetchVideoChapters', 'content', {str})), duration) or None,
361 'formats': self._extract_formats(video_id, metadata, gql_data),
362 'subtitles': filter_dict({
363 'en': traverse_obj(gql_data, (
364 ..., 'data', 'fetchVideoTranscript',
365 ('source_url', 'captions_source_url'), {
366 'url': {url_or_none},
367 })) or None,
369 **traverse_obj(metadata, {
370 'title': ('name', {str}),
371 'description': ('description', {str}),
372 'uploader': ('owner', 'display_name', {str}),
373 'timestamp': ('createdAt', {parse_iso8601}),
378 class LoomFolderIE(InfoExtractor):
379 IE_NAME = 'loom:folder'
380 _VALID_URL = r'https?://(?:www\.)?loom\.com/share/folder/(?P<id>[\da-f]{32})'
381 _TESTS = [{
382 # 2 subfolders, no videos in root
383 'url': 'https://www.loom.com/share/folder/997db4db046f43e5912f10dc5f817b5c',
384 'playlist_mincount': 16,
385 'info_dict': {
386 'id': '997db4db046f43e5912f10dc5f817b5c',
387 'title': 'Blending Lessons',
389 }, {
390 # only videos, no subfolders
391 'url': 'https://www.loom.com/share/folder/9a8a87f6b6f546d9a400c8e7575ff7f2',
392 'playlist_mincount': 12,
393 'info_dict': {
394 'id': '9a8a87f6b6f546d9a400c8e7575ff7f2',
395 'title': 'List A- a, i, o',
397 }, {
398 # videos in root and empty subfolder
399 'url': 'https://www.loom.com/share/folder/886e534218c24fd292e97e9563078cc4',
400 'playlist_mincount': 21,
401 'info_dict': {
402 'id': '886e534218c24fd292e97e9563078cc4',
403 'title': 'Medicare Agent Training videos',
405 }, {
406 # videos in root and videos in subfolders
407 'url': 'https://www.loom.com/share/folder/b72c4ecdf04745da9403926d80a40c38',
408 'playlist_mincount': 21,
409 'info_dict': {
410 'id': 'b72c4ecdf04745da9403926d80a40c38',
411 'title': 'Quick Altos Q & A Tutorials',
413 }, {
414 # recursive folder extraction
415 'url': 'https://www.loom.com/share/folder/8b458a94e0e4449b8df9ea7a68fafc4e',
416 'playlist_count': 23,
417 'info_dict': {
418 'id': '8b458a94e0e4449b8df9ea7a68fafc4e',
419 'title': 'Sezer Texting Guide',
421 }, {
422 # more than 50 videos in 1 folder
423 'url': 'https://www.loom.com/share/folder/e056a91d290d47ca9b00c9d1df56c463',
424 'playlist_mincount': 61,
425 'info_dict': {
426 'id': 'e056a91d290d47ca9b00c9d1df56c463',
427 'title': 'User Videos',
429 }, {
430 # many subfolders
431 'url': 'https://www.loom.com/share/folder/c2dde8cc67454f0e99031677279d8954',
432 'playlist_mincount': 75,
433 'info_dict': {
434 'id': 'c2dde8cc67454f0e99031677279d8954',
435 'title': 'Honors 1',
437 }, {
438 'url': 'https://www.loom.com/share/folder/bae17109a68146c7803454f2893c8cf8/Edpuzzle',
439 'only_matching': True,
442 def _extract_folder_data(self, folder_id):
443 return self._download_json(
444 f'https://www.loom.com/v1/folders/{folder_id}', folder_id,
445 'Downloading folder info JSON', query={'limit': '10000'})
447 def _extract_folder_entries(self, folder_id, initial_folder_data=None):
448 folder_data = initial_folder_data or self._extract_folder_data(folder_id)
450 for video in traverse_obj(folder_data, ('videos', lambda _, v: v['id'])):
451 video_id = video['id']
452 yield self.url_result(
453 f'https://www.loom.com/share/{video_id}', LoomIE, video_id, video.get('name'))
455 # Recurse into subfolders
456 for subfolder_id in traverse_obj(folder_data, (
457 'folders', lambda _, v: v['id'] != folder_id, 'id', {str})):
458 yield from self._extract_folder_entries(subfolder_id)
460 def _real_extract(self, url):
461 playlist_id = self._match_id(url)
462 playlist_data = self._extract_folder_data(playlist_id)
464 return self.playlist_result(
465 self._extract_folder_entries(playlist_id, playlist_data), playlist_id,
466 traverse_obj(playlist_data, ('folder', 'name', {str.strip})))