]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/linkedin.py
[ie/matchtv] Fix extractor (#10190)
[yt-dlp.git] / yt_dlp / extractor / linkedin.py
1 import itertools
2 import re
3
4 from .common import InfoExtractor
5 from ..utils import (
6 ExtractorError,
7 extract_attributes,
8 float_or_none,
9 int_or_none,
10 mimetype2ext,
11 srt_subtitles_timecode,
12 traverse_obj,
13 try_get,
14 url_or_none,
15 urlencode_postdata,
16 urljoin,
17 )
18
19
20 class LinkedInBaseIE(InfoExtractor):
21 _NETRC_MACHINE = 'linkedin'
22 _logged_in = False
23
24 def _perform_login(self, username, password):
25 if self._logged_in:
26 return
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({
35 'session_key': username,
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
49 class LinkedInLearningBaseIE(LinkedInBaseIE):
50 _LOGIN_URL = 'https://www.linkedin.com/uas/login?trk=learning'
51
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': f'_{resolution}',
63 })
64 sub = ' %dp' % resolution
65 api_url = 'https://www.linkedin.com/learning-api/detailedCourses'
66 if not self._get_cookies(api_url).get('JSESSIONID'):
67 self.raise_login_required()
68 return self._download_json(
69 api_url, video_slug, f'Downloading{sub} JSON metadata', headers={
70 'Csrf-Token': self._get_cookies(api_url)['JSESSIONID'].value,
71 }, query=query)['elements'][0]
72
73 def _get_urn_id(self, video_data):
74 urn = video_data.get('urn')
75 if urn:
76 mobj = re.search(r'urn:li:lyndaCourse:\d+,(\d+)', urn)
77 if mobj:
78 return mobj.group(1)
79
80 def _get_video_id(self, video_data, course_slug, video_slug):
81 return self._get_urn_id(video_data) or f'{course_slug}/{video_slug}'
82
83
84 class LinkedInIE(LinkedInBaseIE):
85 _VALID_URL = r'https?://(?:www\.)?linkedin\.com/posts/[^/?#]+-(?P<id>\d+)-\w{4}/?(?:[?#]|$)'
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',
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',
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
115 video_attrs = extract_attributes(self._search_regex(r'(<video[^>]+>)', webpage, 'video'))
116 sources = self._parse_json(video_attrs['data-sources'], video_id)
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]
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 {}
126
127 return {
128 'id': video_id,
129 'formats': formats,
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),
136 'thumbnail': self._og_search_thumbnail(webpage),
137 'description': self._og_search_description(webpage, default=None),
138 'subtitles': subtitles,
139 }
140
141
142 class 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
157 def json2srt(self, transcript_lines, duration=None):
158 srt_data = ''
159 for line, (line_dict, next_dict) in enumerate(itertools.zip_longest(transcript_lines, transcript_lines[1:])):
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
162 srt_data += (
163 f'{line + 1}\n'
164 f'{srt_subtitles_timecode(start_time)} --> {srt_subtitles_timecode(end_time)}\n'
165 f'{caption}\n\n')
166 return srt_data
167
168 def _real_extract(self, url):
169 course_slug, video_slug = self._match_valid_url(url).groups()
170
171 formats = []
172 for width, height in ((640, 360), (960, 540), (1280, 720)):
173 video_data = self._call_api(
174 course_slug, 'selectedVideo', video_slug, height)['selectedVideo']
175
176 video_url_data = video_data.get('url') or {}
177 progressive_url = video_url_data.get('progressiveUrl')
178 if progressive_url:
179 formats.append({
180 'format_id': f'progressive-{height}p',
181 'url': progressive_url,
182 'ext': 'mp4',
183 'height': height,
184 'width': width,
185 'source_preference': 1,
186 })
187
188 title = video_data['title']
189
190 audio_url = video_data.get('audio', {}).get('progressiveUrl')
191 if audio_url:
192 formats.append({
193 'abr': 64,
194 'ext': 'm4a',
195 'format_id': 'audio',
196 'url': audio_url,
197 'vcodec': 'none',
198 })
199
200 streaming_url = video_url_data.get('streamingUrl')
201 if streaming_url:
202 formats.extend(self._extract_m3u8_formats(
203 streaming_url, video_slug, 'mp4',
204 'm3u8_native', m3u8_id='hls', fatal=False))
205
206 subtitles = {}
207 duration = int_or_none(video_data.get('durationInSeconds'))
208 transcript_lines = try_get(video_data, lambda x: x['transcript']['lines'], expected_type=list)
209 if transcript_lines:
210 subtitles['en'] = [{
211 'ext': 'srt',
212 'data': self.json2srt(transcript_lines, duration),
213 }]
214
215 return {
216 'id': self._get_video_id(video_data, course_slug, video_slug),
217 'title': title,
218 'formats': formats,
219 'thumbnail': video_data.get('defaultThumbnail'),
220 'timestamp': float_or_none(video_data.get('publishedOn'), 1000),
221 'duration': duration,
222 'subtitles': subtitles,
223 # It seems like this would be correctly handled by default
224 # However, unless someone can confirm this, the old
225 # behaviour is being kept as-is
226 '_format_sort_fields': ('res', 'source_preference'),
227 }
228
229
230 class LinkedInLearningCourseIE(LinkedInLearningBaseIE):
231 IE_NAME = 'linkedin:learning:course'
232 _VALID_URL = r'https?://(?:www\.)?linkedin\.com/learning/(?P<id>[^/?#]+)'
233 _TEST = {
234 'url': 'https://www.linkedin.com/learning/programming-foundations-fundamentals',
235 'info_dict': {
236 'id': 'programming-foundations-fundamentals',
237 'title': 'Programming Foundations: Fundamentals',
238 'description': 'md5:76e580b017694eb89dc8e8923fff5c86',
239 },
240 'playlist_mincount': 61,
241 }
242
243 @classmethod
244 def suitable(cls, url):
245 return False if LinkedInLearningIE.suitable(url) else super().suitable(url)
246
247 def _real_extract(self, url):
248 course_slug = self._match_id(url)
249 course_data = self._call_api(course_slug, 'chapters,description,title')
250
251 entries = []
252 for chapter_number, chapter in enumerate(course_data.get('chapters', []), 1):
253 chapter_title = chapter.get('title')
254 chapter_id = self._get_urn_id(chapter)
255 for video in chapter.get('videos', []):
256 video_slug = video.get('slug')
257 if not video_slug:
258 continue
259 entries.append({
260 '_type': 'url_transparent',
261 'id': self._get_video_id(video, course_slug, video_slug),
262 'title': video.get('title'),
263 'url': f'https://www.linkedin.com/learning/{course_slug}/{video_slug}',
264 'chapter': chapter_title,
265 'chapter_number': chapter_number,
266 'chapter_id': chapter_id,
267 'ie_key': LinkedInLearningIE.ie_key(),
268 })
269
270 return self.playlist_result(
271 entries, course_slug,
272 course_data.get('title'),
273 course_data.get('description'))