[teachable] Extract chapter metadata (closes #24421)
[ytdl] / youtube_dl / extractor / teachable.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from .wistia import WistiaIE
7 from ..utils import (
8     clean_html,
9     ExtractorError,
10     int_or_none,
11     get_element_by_class,
12     strip_or_none,
13     urlencode_postdata,
14     urljoin,
15 )
16
17
18 class TeachableBaseIE(InfoExtractor):
19     _NETRC_MACHINE = 'teachable'
20     _URL_PREFIX = 'teachable:'
21
22     _SITES = {
23         # Only notable ones here
24         'upskillcourses.com': 'upskill',
25         'academy.gns3.com': 'gns3',
26         'academyhacker.com': 'academyhacker',
27         'stackskills.com': 'stackskills',
28         'market.saleshacker.com': 'saleshacker',
29         'learnability.org': 'learnability',
30         'edurila.com': 'edurila',
31         'courses.workitdaily.com': 'workitdaily',
32     }
33
34     _VALID_URL_SUB_TUPLE = (_URL_PREFIX, '|'.join(re.escape(site) for site in _SITES.keys()))
35
36     def _real_initialize(self):
37         self._logged_in = False
38
39     def _login(self, site):
40         if self._logged_in:
41             return
42
43         username, password = self._get_login_info(
44             netrc_machine=self._SITES.get(site, site))
45         if username is None:
46             return
47
48         login_page, urlh = self._download_webpage_handle(
49             'https://%s/sign_in' % site, None,
50             'Downloading %s login page' % site)
51
52         def is_logged(webpage):
53             return any(re.search(p, webpage) for p in (
54                 r'class=["\']user-signout',
55                 r'<a[^>]+\bhref=["\']/sign_out',
56                 r'Log\s+[Oo]ut\s*<'))
57
58         if is_logged(login_page):
59             self._logged_in = True
60             return
61
62         login_url = urlh.geturl()
63
64         login_form = self._hidden_inputs(login_page)
65
66         login_form.update({
67             'user[email]': username,
68             'user[password]': password,
69         })
70
71         post_url = self._search_regex(
72             r'<form[^>]+action=(["\'])(?P<url>(?:(?!\1).)+)\1', login_page,
73             'post url', default=login_url, group='url')
74
75         if not post_url.startswith('http'):
76             post_url = urljoin(login_url, post_url)
77
78         response = self._download_webpage(
79             post_url, None, 'Logging in to %s' % site,
80             data=urlencode_postdata(login_form),
81             headers={
82                 'Content-Type': 'application/x-www-form-urlencoded',
83                 'Referer': login_url,
84             })
85
86         if '>I accept the new Privacy Policy<' in response:
87             raise ExtractorError(
88                 'Unable to login: %s asks you to accept new Privacy Policy. '
89                 'Go to https://%s/ and accept.' % (site, site), expected=True)
90
91         # Successful login
92         if is_logged(response):
93             self._logged_in = True
94             return
95
96         message = get_element_by_class('alert', response)
97         if message is not None:
98             raise ExtractorError(
99                 'Unable to login: %s' % clean_html(message), expected=True)
100
101         raise ExtractorError('Unable to log in')
102
103
104 class TeachableIE(TeachableBaseIE):
105     _VALID_URL = r'''(?x)
106                     (?:
107                         %shttps?://(?P<site_t>[^/]+)|
108                         https?://(?:www\.)?(?P<site>%s)
109                     )
110                     /courses/[^/]+/lectures/(?P<id>\d+)
111                     ''' % TeachableBaseIE._VALID_URL_SUB_TUPLE
112
113     _TESTS = [{
114         'url': 'http://upskillcourses.com/courses/essential-web-developer-course/lectures/1747100',
115         'info_dict': {
116             'id': 'uzw6zw58or',
117             'ext': 'mp4',
118             'title': 'Welcome to the Course!',
119             'description': 'md5:65edb0affa582974de4625b9cdea1107',
120             'duration': 138.763,
121             'timestamp': 1479846621,
122             'upload_date': '20161122',
123         },
124         'params': {
125             'skip_download': True,
126         },
127     }, {
128         'url': 'http://upskillcourses.com/courses/119763/lectures/1747100',
129         'only_matching': True,
130     }, {
131         'url': 'https://academy.gns3.com/courses/423415/lectures/6885939',
132         'only_matching': True,
133     }, {
134         'url': 'teachable:https://upskillcourses.com/courses/essential-web-developer-course/lectures/1747100',
135         'only_matching': True,
136     }]
137
138     @staticmethod
139     def _is_teachable(webpage):
140         return 'teachableTracker.linker:autoLink' in webpage and re.search(
141             r'<link[^>]+href=["\']https?://process\.fs\.teachablecdn\.com',
142             webpage)
143
144     @staticmethod
145     def _extract_url(webpage, source_url):
146         if not TeachableIE._is_teachable(webpage):
147             return
148         if re.match(r'https?://[^/]+/(?:courses|p)', source_url):
149             return '%s%s' % (TeachableBaseIE._URL_PREFIX, source_url)
150
151     def _real_extract(self, url):
152         mobj = re.match(self._VALID_URL, url)
153         site = mobj.group('site') or mobj.group('site_t')
154         video_id = mobj.group('id')
155
156         self._login(site)
157
158         prefixed = url.startswith(self._URL_PREFIX)
159         if prefixed:
160             url = url[len(self._URL_PREFIX):]
161
162         webpage = self._download_webpage(url, video_id)
163
164         wistia_urls = WistiaIE._extract_urls(webpage)
165         if not wistia_urls:
166             if any(re.search(p, webpage) for p in (
167                     r'class=["\']lecture-contents-locked',
168                     r'>\s*Lecture contents locked',
169                     r'id=["\']lecture-locked',
170                     # https://academy.tailoredtutors.co.uk/courses/108779/lectures/1955313
171                     r'class=["\'](?:inner-)?lesson-locked',
172                     r'>LESSON LOCKED<')):
173                 self.raise_login_required('Lecture contents locked')
174             raise ExtractorError('Unable to find video URL')
175
176         title = self._og_search_title(webpage, default=None)
177
178         chapter = None
179         chapter_number = None
180         section_item = self._search_regex(
181             r'(?s)(?P<li><li[^>]+\bdata-lecture-id=["\']%s[^>]+>.+?</li>)' % video_id,
182             webpage, 'section item', default=None, group='li')
183         if section_item:
184             chapter_number = int_or_none(self._search_regex(
185                 r'data-ss-position=["\'](\d+)', section_item, 'section id',
186                 default=None))
187             if chapter_number is not None:
188                 sections = []
189                 for s in re.findall(
190                         r'(?s)<div[^>]+\bclass=["\']section-title[^>]+>(.+?)</div>', webpage):
191                     section = strip_or_none(clean_html(s))
192                     if not section:
193                         sections = []
194                         break
195                     sections.append(section)
196                 if chapter_number <= len(sections):
197                     chapter = sections[chapter_number - 1]
198
199         entries = [{
200             '_type': 'url_transparent',
201             'url': wistia_url,
202             'ie_key': WistiaIE.ie_key(),
203             'title': title,
204             'chapter': chapter,
205             'chapter_number': chapter_number,
206         } for wistia_url in wistia_urls]
207
208         return self.playlist_result(entries, video_id, title)
209
210
211 class TeachableCourseIE(TeachableBaseIE):
212     _VALID_URL = r'''(?x)
213                         (?:
214                             %shttps?://(?P<site_t>[^/]+)|
215                             https?://(?:www\.)?(?P<site>%s)
216                         )
217                         /(?:courses|p)/(?:enrolled/)?(?P<id>[^/?#&]+)
218                     ''' % TeachableBaseIE._VALID_URL_SUB_TUPLE
219     _TESTS = [{
220         'url': 'http://upskillcourses.com/courses/essential-web-developer-course/',
221         'info_dict': {
222             'id': 'essential-web-developer-course',
223             'title': 'The Essential Web Developer Course (Free)',
224         },
225         'playlist_count': 192,
226     }, {
227         'url': 'http://upskillcourses.com/courses/119763/',
228         'only_matching': True,
229     }, {
230         'url': 'http://upskillcourses.com/courses/enrolled/119763',
231         'only_matching': True,
232     }, {
233         'url': 'https://academy.gns3.com/courses/enrolled/423415',
234         'only_matching': True,
235     }, {
236         'url': 'teachable:https://learn.vrdev.school/p/gear-vr-developer-mini',
237         'only_matching': True,
238     }, {
239         'url': 'teachable:https://filmsimplified.com/p/davinci-resolve-15-crash-course',
240         'only_matching': True,
241     }]
242
243     @classmethod
244     def suitable(cls, url):
245         return False if TeachableIE.suitable(url) else super(
246             TeachableCourseIE, cls).suitable(url)
247
248     def _real_extract(self, url):
249         mobj = re.match(self._VALID_URL, url)
250         site = mobj.group('site') or mobj.group('site_t')
251         course_id = mobj.group('id')
252
253         self._login(site)
254
255         prefixed = url.startswith(self._URL_PREFIX)
256         if prefixed:
257             prefix = self._URL_PREFIX
258             url = url[len(prefix):]
259
260         webpage = self._download_webpage(url, course_id)
261
262         url_base = 'https://%s/' % site
263
264         entries = []
265
266         for mobj in re.finditer(
267                 r'(?s)(?P<li><li[^>]+class=(["\'])(?:(?!\2).)*?section-item[^>]+>.+?</li>)',
268                 webpage):
269             li = mobj.group('li')
270             if 'fa-youtube-play' not in li:
271                 continue
272             lecture_url = self._search_regex(
273                 r'<a[^>]+href=(["\'])(?P<url>(?:(?!\1).)+)\1', li,
274                 'lecture url', default=None, group='url')
275             if not lecture_url:
276                 continue
277             lecture_id = self._search_regex(
278                 r'/lectures/(\d+)', lecture_url, 'lecture id', default=None)
279             title = self._html_search_regex(
280                 r'<span[^>]+class=["\']lecture-name[^>]+>([^<]+)', li,
281                 'title', default=None)
282             entry_url = urljoin(url_base, lecture_url)
283             if prefixed:
284                 entry_url = self._URL_PREFIX + entry_url
285             entries.append(
286                 self.url_result(
287                     entry_url,
288                     ie=TeachableIE.ie_key(), video_id=lecture_id,
289                     video_title=clean_html(title)))
290
291         course_title = self._html_search_regex(
292             (r'(?s)<img[^>]+class=["\']course-image[^>]+>\s*<h\d>(.+?)</h',
293              r'(?s)<h\d[^>]+class=["\']course-title[^>]+>(.+?)</h'),
294             webpage, 'course title', fatal=False)
295
296         return self.playlist_result(entries, course_id, course_title)