linkedin.py 11 KB

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