]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/linkedin.py
[ie/youtube] Suppress "Unavailable videos are hidden" warning (#10159)
[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,
add96eb9 62 'resolution': f'_{resolution}',
aa7e974a
RA
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 68 return self._download_json(
add96eb9 69 api_url, video_slug, f'Downloading{sub} JSON metadata', headers={
aa7e974a
RA
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):
add96eb9 81 return self._get_urn_id(video_data) or f'{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/.*$',
add96eb9 95 'like_count': int,
017adb28 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,
add96eb9 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
add96eb9 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')
8dc831f7
AG
166 return srt_data
167
aa7e974a 168 def _real_extract(self, url):
5ad28e7f 169 course_slug, video_slug = self._match_valid_url(url).groups()
aa7e974a 170
aa7e974a
RA
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({
add96eb9 180 'format_id': f'progressive-{height}p',
aa7e974a 181 'url': progressive_url,
8dc831f7 182 'ext': 'mp4',
aa7e974a
RA
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
8dc831f7
AG
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',
add96eb9 212 'data': self.json2srt(transcript_lines, duration),
8dc831f7 213 }]
aa7e974a
RA
214
215 return {
91effe22 216 'id': self._get_video_id(video_data, course_slug, video_slug),
aa7e974a
RA
217 'title': title,
218 'formats': formats,
219 'thumbnail': video_data.get('defaultThumbnail'),
220 'timestamp': float_or_none(video_data.get('publishedOn'), 1000),
8dc831f7
AG
221 'duration': duration,
222 'subtitles': subtitles,
9f14daf2 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
add96eb9 226 '_format_sort_fields': ('res', 'source_preference'),
aa7e974a
RA
227 }
228
229
230class 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):
add96eb9 245 return False if LinkedInLearningIE.suitable(url) else super().suitable(url)
aa7e974a
RA
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 = []
91effe22 252 for chapter_number, chapter in enumerate(course_data.get('chapters', []), 1):
aa7e974a 253 chapter_title = chapter.get('title')
91effe22 254 chapter_id = self._get_urn_id(chapter)
aa7e974a
RA
255 for video in chapter.get('videos', []):
256 video_slug = video.get('slug')
257 if not video_slug:
258 continue
259 entries.append({
b1447572 260 '_type': 'url_transparent',
91effe22 261 'id': self._get_video_id(video, course_slug, video_slug),
aa7e974a 262 'title': video.get('title'),
add96eb9 263 'url': f'https://www.linkedin.com/learning/{course_slug}/{video_slug}',
aa7e974a 264 'chapter': chapter_title,
91effe22
RA
265 'chapter_number': chapter_number,
266 'chapter_id': chapter_id,
aa7e974a
RA
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'))