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