[youtube] Add support for invidiou.sh (#20309)
[youtube-dl] / youtube_dl / extractor / linkedin.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     ExtractorError,
9     float_or_none,
10     int_or_none,
11     urlencode_postdata,
12 )
13
14
15 class LinkedInLearningBaseIE(InfoExtractor):
16     _NETRC_MACHINE = 'linkedin'
17
18     def _call_api(self, course_slug, fields, video_slug=None, resolution=None):
19         query = {
20             'courseSlug': course_slug,
21             'fields': fields,
22             'q': 'slugs',
23         }
24         sub = ''
25         if video_slug:
26             query.update({
27                 'videoSlug': video_slug,
28                 'resolution': '_%s' % resolution,
29             })
30             sub = ' %dp' % resolution
31         api_url = 'https://www.linkedin.com/learning-api/detailedCourses'
32         return self._download_json(
33             api_url, video_slug, 'Downloading%s JSON metadata' % sub, headers={
34                 'Csrf-Token': self._get_cookies(api_url)['JSESSIONID'].value,
35             }, query=query)['elements'][0]
36
37     def _get_urn_id(self, video_data):
38         urn = video_data.get('urn')
39         if urn:
40             mobj = re.search(r'urn:li:lyndaCourse:\d+,(\d+)', urn)
41             if mobj:
42                 return mobj.group(1)
43
44     def _get_video_id(self, video_data, course_slug, video_slug):
45         return self._get_urn_id(video_data) or '%s/%s' % (course_slug, video_slug)
46
47     def _real_initialize(self):
48         email, password = self._get_login_info()
49         if email is None:
50             return
51
52         login_page = self._download_webpage(
53             'https://www.linkedin.com/uas/login?trk=learning',
54             None, 'Downloading login page')
55         action_url = self._search_regex(
56             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page, 'post url',
57             default='https://www.linkedin.com/uas/login-submit', group='url')
58         data = self._hidden_inputs(login_page)
59         data.update({
60             'session_key': email,
61             'session_password': password,
62         })
63         login_submit_page = self._download_webpage(
64             action_url, None, 'Logging in',
65             data=urlencode_postdata(data))
66         error = self._search_regex(
67             r'<span[^>]+class="error"[^>]*>\s*(.+?)\s*</span>',
68             login_submit_page, 'error', default=None)
69         if error:
70             raise ExtractorError(error, expected=True)
71
72
73 class LinkedInLearningIE(LinkedInLearningBaseIE):
74     IE_NAME = 'linkedin:learning'
75     _VALID_URL = r'https?://(?:www\.)?linkedin\.com/learning/(?P<course_slug>[^/]+)/(?P<id>[^/?#]+)'
76     _TEST = {
77         'url': 'https://www.linkedin.com/learning/programming-foundations-fundamentals/welcome?autoplay=true',
78         'md5': 'a1d74422ff0d5e66a792deb996693167',
79         'info_dict': {
80             'id': '90426',
81             'ext': 'mp4',
82             'title': 'Welcome',
83             'timestamp': 1430396150.82,
84             'upload_date': '20150430',
85         },
86     }
87
88     def _real_extract(self, url):
89         course_slug, video_slug = re.match(self._VALID_URL, url).groups()
90
91         video_data = None
92         formats = []
93         for width, height in ((640, 360), (960, 540), (1280, 720)):
94             video_data = self._call_api(
95                 course_slug, 'selectedVideo', video_slug, height)['selectedVideo']
96
97             video_url_data = video_data.get('url') or {}
98             progressive_url = video_url_data.get('progressiveUrl')
99             if progressive_url:
100                 formats.append({
101                     'format_id': 'progressive-%dp' % height,
102                     'url': progressive_url,
103                     'height': height,
104                     'width': width,
105                     'source_preference': 1,
106                 })
107
108         title = video_data['title']
109
110         audio_url = video_data.get('audio', {}).get('progressiveUrl')
111         if audio_url:
112             formats.append({
113                 'abr': 64,
114                 'ext': 'm4a',
115                 'format_id': 'audio',
116                 'url': audio_url,
117                 'vcodec': 'none',
118             })
119
120         streaming_url = video_url_data.get('streamingUrl')
121         if streaming_url:
122             formats.extend(self._extract_m3u8_formats(
123                 streaming_url, video_slug, 'mp4',
124                 'm3u8_native', m3u8_id='hls', fatal=False))
125
126         self._sort_formats(formats, ('width', 'height', 'source_preference', 'tbr', 'abr'))
127
128         return {
129             'id': self._get_video_id(video_data, course_slug, video_slug),
130             'title': title,
131             'formats': formats,
132             'thumbnail': video_data.get('defaultThumbnail'),
133             'timestamp': float_or_none(video_data.get('publishedOn'), 1000),
134             'duration': int_or_none(video_data.get('durationInSeconds')),
135         }
136
137
138 class LinkedInLearningCourseIE(LinkedInLearningBaseIE):
139     IE_NAME = 'linkedin:learning:course'
140     _VALID_URL = r'https?://(?:www\.)?linkedin\.com/learning/(?P<id>[^/?#]+)'
141     _TEST = {
142         'url': 'https://www.linkedin.com/learning/programming-foundations-fundamentals',
143         'info_dict': {
144             'id': 'programming-foundations-fundamentals',
145             'title': 'Programming Foundations: Fundamentals',
146             'description': 'md5:76e580b017694eb89dc8e8923fff5c86',
147         },
148         'playlist_mincount': 61,
149     }
150
151     @classmethod
152     def suitable(cls, url):
153         return False if LinkedInLearningIE.suitable(url) else super(LinkedInLearningCourseIE, cls).suitable(url)
154
155     def _real_extract(self, url):
156         course_slug = self._match_id(url)
157         course_data = self._call_api(course_slug, 'chapters,description,title')
158
159         entries = []
160         for chapter_number, chapter in enumerate(course_data.get('chapters', []), 1):
161             chapter_title = chapter.get('title')
162             chapter_id = self._get_urn_id(chapter)
163             for video in chapter.get('videos', []):
164                 video_slug = video.get('slug')
165                 if not video_slug:
166                     continue
167                 entries.append({
168                     '_type': 'url_transparent',
169                     'id': self._get_video_id(video, course_slug, video_slug),
170                     'title': video.get('title'),
171                     'url': 'https://www.linkedin.com/learning/%s/%s' % (course_slug, video_slug),
172                     'chapter': chapter_title,
173                     'chapter_number': chapter_number,
174                     'chapter_id': chapter_id,
175                     'ie_key': LinkedInLearningIE.ie_key(),
176                 })
177
178         return self.playlist_result(
179             entries, course_slug,
180             course_data.get('title'),
181             course_data.get('description'))