[lecturio] Add extractor (closes #18405)
[youtube-dl] / youtube_dl / extractor / lecturio.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import compat_str
8 from ..utils import (
9     determine_ext,
10     extract_attributes,
11     ExtractorError,
12     float_or_none,
13     int_or_none,
14     str_or_none,
15     url_or_none,
16     urlencode_postdata,
17     urljoin,
18 )
19
20
21 class LecturioBaseIE(InfoExtractor):
22     _LOGIN_URL = 'https://app.lecturio.com/en/login'
23     _NETRC_MACHINE = 'lecturio'
24
25     def _real_initialize(self):
26         self._login()
27
28     def _login(self):
29         username, password = self._get_login_info()
30         if username is None:
31             return
32
33         # Sets some cookies
34         _, urlh = self._download_webpage_handle(
35             self._LOGIN_URL, None, 'Downloading login popup')
36
37         def is_logged(url_handle):
38             return self._LOGIN_URL not in compat_str(url_handle.geturl())
39
40         # Already logged in
41         if is_logged(urlh):
42             return
43
44         login_form = {
45             'signin[email]': username,
46             'signin[password]': password,
47             'signin[remember]': 'on',
48         }
49
50         response, urlh = self._download_webpage_handle(
51             self._LOGIN_URL, None, 'Logging in',
52             data=urlencode_postdata(login_form))
53
54         # Logged in successfully
55         if is_logged(urlh):
56             return
57
58         errors = self._html_search_regex(
59             r'(?s)<ul[^>]+class=["\']error_list[^>]+>(.+?)</ul>', response,
60             'errors', default=None)
61         if errors:
62             raise ExtractorError('Unable to login: %s' % errors, expected=True)
63         raise ExtractorError('Unable to log in')
64
65
66 class LecturioIE(LecturioBaseIE):
67     _VALID_URL = r'https://app\.lecturio\.com/[^/]+/(?P<id>[^/?#&]+)\.lecture'
68     _TEST = {
69         'url': 'https://app.lecturio.com/medical-courses/important-concepts-and-terms-introduction-to-microbiology.lecture#tab/videos',
70         'md5': 'f576a797a5b7a5e4e4bbdfc25a6a6870',
71         'info_dict': {
72             'id': '39634',
73             'ext': 'mp4',
74             'title': 'Important Concepts and Terms – Introduction to Microbiology',
75         },
76         'skip': 'Requires lecturio account credentials',
77     }
78
79     _CC_LANGS = {
80         'German': 'de',
81         'English': 'en',
82         'Spanish': 'es',
83         'French': 'fr',
84         'Polish': 'pl',
85         'Russian': 'ru',
86     }
87
88     def _real_extract(self, url):
89         display_id = self._match_id(url)
90
91         webpage = self._download_webpage(
92             'https://app.lecturio.com/en/lecture/%s/player.html' % display_id,
93             display_id)
94
95         lecture_id = self._search_regex(
96             r'lecture_id\s*=\s*(?:L_)?(\d+)', webpage, 'lecture id')
97
98         api_url = self._search_regex(
99             r'lectureDataLink\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
100             'api url', group='url')
101
102         video = self._download_json(api_url, display_id)
103
104         title = video['title'].strip()
105
106         formats = []
107         for format_ in video['content']['media']:
108             if not isinstance(format_, dict):
109                 continue
110             file_ = format_.get('file')
111             if not file_:
112                 continue
113             ext = determine_ext(file_)
114             if ext == 'smil':
115                 # smil contains only broken RTMP formats anyway
116                 continue
117             file_url = url_or_none(file_)
118             if not file_url:
119                 continue
120             label = str_or_none(format_.get('label'))
121             filesize = int_or_none(format_.get('fileSize'))
122             formats.append({
123                 'url': file_url,
124                 'format_id': label,
125                 'filesize': float_or_none(filesize, invscale=1000)
126             })
127         self._sort_formats(formats)
128
129         subtitles = {}
130         automatic_captions = {}
131         cc = self._parse_json(
132             self._search_regex(
133                 r'subtitleUrls\s*:\s*({.+?})\s*,', webpage, 'subtitles',
134                 default='{}'), display_id, fatal=False)
135         for cc_label, cc_url in cc.items():
136             cc_url = url_or_none(cc_url)
137             if not cc_url:
138                 continue
139             sub_dict = automatic_captions if 'auto-translated' in cc_label else subtitles
140             lang = self._search_regex(
141                 r'/([a-z]{2})_', cc_url, 'lang', default=cc_label.split()[0])
142             sub_dict.setdefault(self._CC_LANGS.get(lang, lang), []).append({
143                 'url': cc_url,
144             })
145
146         return {
147             'id': lecture_id,
148             'title': title,
149             'formats': formats,
150             'subtitles': subtitles,
151             'automatic_captions': automatic_captions,
152         }
153
154
155 class LecturioCourseIE(LecturioBaseIE):
156     _VALID_URL = r'https://app\.lecturio\.com/[^/]+/(?P<id>[^/?#&]+)\.course'
157     _TEST = {
158         'url': 'https://app.lecturio.com/medical-courses/microbiology-introduction.course#/',
159         'info_dict': {
160             'id': 'microbiology-introduction',
161             'title': 'Microbiology: Introduction',
162         },
163         'playlist_count': 45,
164         'skip': 'Requires lecturio account credentials',
165     }
166
167     def _real_extract(self, url):
168         display_id = self._match_id(url)
169
170         webpage = self._download_webpage(url, display_id)
171
172         entries = []
173         for mobj in re.finditer(
174                 r'(?s)<[^>]+\bdata-url=(["\'])(?:(?!\1).)+\.lecture\b[^>]+>',
175                 webpage):
176             params = extract_attributes(mobj.group(0))
177             lecture_url = urljoin(url, params.get('data-url'))
178             lecture_id = params.get('data-id')
179             entries.append(self.url_result(
180                 lecture_url, ie=LecturioIE.ie_key(), video_id=lecture_id))
181
182         title = self._search_regex(
183             r'<span[^>]+class=["\']content-title[^>]+>([^<]+)', webpage,
184             'title', default=None)
185
186         return self.playlist_result(entries, display_id, title)