]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/linkedin.py
[misc] Add `hatch`, `ruff`, `pre-commit` and improve dev docs (#7409)
[yt-dlp.git] / yt_dlp / extractor / linkedin.py
CommitLineData
e3a3ed8a 1import itertools
aa7e974a
RA
2import re
3
4from .common import InfoExtractor
5from ..utils import (
6 ExtractorError,
017adb28 7 extract_attributes,
aa7e974a
RA
8 float_or_none,
9 int_or_none,
402cd603 10 mimetype2ext,
e897bd82 11 srt_subtitles_timecode,
017adb28 12 traverse_obj,
8dc831f7 13 try_get,
017adb28 14 url_or_none,
aa7e974a 15 urlencode_postdata,
c9120294 16 urljoin,
aa7e974a
RA
17)
18
19
402cd603 20class LinkedInBaseIE(InfoExtractor):
aa7e974a 21 _NETRC_MACHINE = 'linkedin'
da483200 22 _logged_in = False
aa7e974a 23
52efa4b3 24 def _perform_login(self, username, password):
402cd603 25 if self._logged_in:
26 return
402cd603 27
28 login_page = self._download_webpage(
29 self._LOGIN_URL, None, 'Downloading login page')
30 action_url = urljoin(self._LOGIN_URL, self._search_regex(
31 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page, 'post url',
32 default='https://www.linkedin.com/uas/login-submit', group='url'))
33 data = self._hidden_inputs(login_page)
34 data.update({
52efa4b3 35 'session_key': username,
402cd603 36 'session_password': password,
37 })
38 login_submit_page = self._download_webpage(
39 action_url, None, 'Logging in',
40 data=urlencode_postdata(data))
41 error = self._search_regex(
42 r'<span[^>]+class="error"[^>]*>\s*(.+?)\s*</span>',
43 login_submit_page, 'error', default=None)
44 if error:
45 raise ExtractorError(error, expected=True)
46 LinkedInBaseIE._logged_in = True
47
48
49class LinkedInLearningBaseIE(LinkedInBaseIE):
50 _LOGIN_URL = 'https://www.linkedin.com/uas/login?trk=learning'
51
aa7e974a
RA
52 def _call_api(self, course_slug, fields, video_slug=None, resolution=None):
53 query = {
54 'courseSlug': course_slug,
55 'fields': fields,
56 'q': 'slugs',
57 }
58 sub = ''
59 if video_slug:
60 query.update({
61 'videoSlug': video_slug,
62 'resolution': '_%s' % resolution,
63 })
64 sub = ' %dp' % resolution
65 api_url = 'https://www.linkedin.com/learning-api/detailedCourses'
da483200 66 if not self._get_cookies(api_url).get('JSESSIONID'):
67 self.raise_login_required()
aa7e974a
RA
68 return self._download_json(
69 api_url, video_slug, 'Downloading%s JSON metadata' % sub, headers={
70 'Csrf-Token': self._get_cookies(api_url)['JSESSIONID'].value,
71 }, query=query)['elements'][0]
72
91effe22
RA
73 def _get_urn_id(self, video_data):
74 urn = video_data.get('urn')
aa7e974a
RA
75 if urn:
76 mobj = re.search(r'urn:li:lyndaCourse:\d+,(\d+)', urn)
77 if mobj:
78 return mobj.group(1)
91effe22
RA
79
80 def _get_video_id(self, video_data, course_slug, video_slug):
81 return self._get_urn_id(video_data) or '%s/%s' % (course_slug, video_slug)
aa7e974a 82
aa7e974a 83
402cd603 84class LinkedInIE(LinkedInBaseIE):
017adb28 85 _VALID_URL = r'https?://(?:www\.)?linkedin\.com/posts/[^/?#]+-(?P<id>\d+)-\w{4}/?(?:[?#]|$)'
402cd603 86 _TESTS = [{
87 'url': 'https://www.linkedin.com/posts/mishalkhawaja_sendinblueviews-toronto-digitalmarketing-ugcPost-6850898786781339649-mM20',
88 'info_dict': {
89 'id': '6850898786781339649',
90 'ext': 'mp4',
017adb28 91 'title': 'Mishal K. on LinkedIn: #sendinblueviews #toronto #digitalmarketing #nowhiring #sendinblue…',
92 'description': 'md5:2998a31f6f479376dd62831f53a80f71',
93 'uploader': 'Mishal K.',
94 'thumbnail': 're:^https?://media.licdn.com/dms/image/.*$',
95 'like_count': int
96 },
97 }, {
98 'url': 'https://www.linkedin.com/posts/the-mathworks_2_what-is-mathworks-cloud-center-activity-7151241570371948544-4Gu7',
99 'info_dict': {
100 'id': '7151241570371948544',
101 'ext': 'mp4',
102 'title': 'MathWorks on LinkedIn: What Is MathWorks Cloud Center?',
103 'description': 'md5:95f9d4eeb6337882fb47eefe13d7a40c',
104 'uploader': 'MathWorks',
105 'thumbnail': 're:^https?://media.licdn.com/dms/image/.*$',
106 'like_count': int,
107 'subtitles': 'mincount:1'
402cd603 108 },
109 }]
110
111 def _real_extract(self, url):
112 video_id = self._match_id(url)
113 webpage = self._download_webpage(url, video_id)
114
017adb28 115 video_attrs = extract_attributes(self._search_regex(r'(<video[^>]+>)', webpage, 'video'))
116 sources = self._parse_json(video_attrs['data-sources'], video_id)
402cd603 117 formats = [{
118 'url': source['src'],
119 'ext': mimetype2ext(source.get('type')),
120 'tbr': float_or_none(source.get('data-bitrate'), scale=1000),
121 } for source in sources]
017adb28 122 subtitles = {'en': [{
123 'url': video_attrs['data-captions-url'],
124 'ext': 'vtt',
125 }]} if url_or_none(video_attrs.get('data-captions-url')) else {}
402cd603 126
402cd603 127 return {
128 'id': video_id,
129 'formats': formats,
017adb28 130 'title': self._og_search_title(webpage, default=None) or self._html_extract_title(webpage),
131 'like_count': int_or_none(self._search_regex(
132 r'\bdata-num-reactions="(\d+)"', webpage, 'reactions', default=None)),
133 'uploader': traverse_obj(
134 self._yield_json_ld(webpage, video_id),
135 (lambda _, v: v['@type'] == 'SocialMediaPosting', 'author', 'name', {str}), get_all=False),
402cd603 136 'thumbnail': self._og_search_thumbnail(webpage),
017adb28 137 'description': self._og_search_description(webpage, default=None),
138 'subtitles': subtitles,
402cd603 139 }
aa7e974a
RA
140
141
142class LinkedInLearningIE(LinkedInLearningBaseIE):
143 IE_NAME = 'linkedin:learning'
144 _VALID_URL = r'https?://(?:www\.)?linkedin\.com/learning/(?P<course_slug>[^/]+)/(?P<id>[^/?#]+)'
145 _TEST = {
146 'url': 'https://www.linkedin.com/learning/programming-foundations-fundamentals/welcome?autoplay=true',
147 'md5': 'a1d74422ff0d5e66a792deb996693167',
148 'info_dict': {
149 'id': '90426',
150 'ext': 'mp4',
151 'title': 'Welcome',
152 'timestamp': 1430396150.82,
153 'upload_date': '20150430',
154 },
155 }
156
8dc831f7
AG
157 def json2srt(self, transcript_lines, duration=None):
158 srt_data = ''
e3a3ed8a 159 for line, (line_dict, next_dict) in enumerate(itertools.zip_longest(transcript_lines, transcript_lines[1:])):
8dc831f7
AG
160 start_time, caption = line_dict['transcriptStartAt'] / 1000, line_dict['caption']
161 end_time = next_dict['transcriptStartAt'] / 1000 if next_dict else duration or start_time + 1
80c360d7
AG
162 srt_data += '%d\n%s --> %s\n%s\n\n' % (line + 1, srt_subtitles_timecode(start_time),
163 srt_subtitles_timecode(end_time),
164 caption)
8dc831f7
AG
165 return srt_data
166
aa7e974a 167 def _real_extract(self, url):
5ad28e7f 168 course_slug, video_slug = self._match_valid_url(url).groups()
aa7e974a 169
aa7e974a
RA
170 formats = []
171 for width, height in ((640, 360), (960, 540), (1280, 720)):
172 video_data = self._call_api(
173 course_slug, 'selectedVideo', video_slug, height)['selectedVideo']
174
175 video_url_data = video_data.get('url') or {}
176 progressive_url = video_url_data.get('progressiveUrl')
177 if progressive_url:
178 formats.append({
179 'format_id': 'progressive-%dp' % height,
180 'url': progressive_url,
8dc831f7 181 'ext': 'mp4',
aa7e974a
RA
182 'height': height,
183 'width': width,
184 'source_preference': 1,
185 })
186
187 title = video_data['title']
188
189 audio_url = video_data.get('audio', {}).get('progressiveUrl')
190 if audio_url:
191 formats.append({
192 'abr': 64,
193 'ext': 'm4a',
194 'format_id': 'audio',
195 'url': audio_url,
196 'vcodec': 'none',
197 })
198
199 streaming_url = video_url_data.get('streamingUrl')
200 if streaming_url:
201 formats.extend(self._extract_m3u8_formats(
202 streaming_url, video_slug, 'mp4',
203 'm3u8_native', m3u8_id='hls', fatal=False))
204
8dc831f7
AG
205 subtitles = {}
206 duration = int_or_none(video_data.get('durationInSeconds'))
207 transcript_lines = try_get(video_data, lambda x: x['transcript']['lines'], expected_type=list)
208 if transcript_lines:
209 subtitles['en'] = [{
210 'ext': 'srt',
211 'data': self.json2srt(transcript_lines, duration)
212 }]
aa7e974a
RA
213
214 return {
91effe22 215 'id': self._get_video_id(video_data, course_slug, video_slug),
aa7e974a
RA
216 'title': title,
217 'formats': formats,
218 'thumbnail': video_data.get('defaultThumbnail'),
219 'timestamp': float_or_none(video_data.get('publishedOn'), 1000),
8dc831f7
AG
220 'duration': duration,
221 'subtitles': subtitles,
9f14daf2 222 # It seems like this would be correctly handled by default
223 # However, unless someone can confirm this, the old
224 # behaviour is being kept as-is
225 '_format_sort_fields': ('res', 'source_preference')
aa7e974a
RA
226 }
227
228
229class LinkedInLearningCourseIE(LinkedInLearningBaseIE):
230 IE_NAME = 'linkedin:learning:course'
231 _VALID_URL = r'https?://(?:www\.)?linkedin\.com/learning/(?P<id>[^/?#]+)'
232 _TEST = {
233 'url': 'https://www.linkedin.com/learning/programming-foundations-fundamentals',
234 'info_dict': {
235 'id': 'programming-foundations-fundamentals',
236 'title': 'Programming Foundations: Fundamentals',
237 'description': 'md5:76e580b017694eb89dc8e8923fff5c86',
238 },
239 'playlist_mincount': 61,
240 }
241
242 @classmethod
243 def suitable(cls, url):
244 return False if LinkedInLearningIE.suitable(url) else super(LinkedInLearningCourseIE, cls).suitable(url)
245
246 def _real_extract(self, url):
247 course_slug = self._match_id(url)
248 course_data = self._call_api(course_slug, 'chapters,description,title')
249
250 entries = []
91effe22 251 for chapter_number, chapter in enumerate(course_data.get('chapters', []), 1):
aa7e974a 252 chapter_title = chapter.get('title')
91effe22 253 chapter_id = self._get_urn_id(chapter)
aa7e974a
RA
254 for video in chapter.get('videos', []):
255 video_slug = video.get('slug')
256 if not video_slug:
257 continue
258 entries.append({
b1447572 259 '_type': 'url_transparent',
91effe22 260 'id': self._get_video_id(video, course_slug, video_slug),
aa7e974a
RA
261 'title': video.get('title'),
262 'url': 'https://www.linkedin.com/learning/%s/%s' % (course_slug, video_slug),
263 'chapter': chapter_title,
91effe22
RA
264 'chapter_number': chapter_number,
265 'chapter_id': chapter_id,
aa7e974a
RA
266 'ie_key': LinkedInLearningIE.ie_key(),
267 })
268
269 return self.playlist_result(
270 entries, course_slug,
271 course_data.get('title'),
272 course_data.get('description'))