loom.py 18 KB

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