[pluralsight] Fix subtitles extraction (closes #17726, closes #17728)
[youtube-dl] / youtube_dl / extractor / pluralsight.py
1 from __future__ import unicode_literals
2
3 import collections
4 import json
5 import os
6 import random
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_str,
11     compat_urlparse,
12 )
13 from ..utils import (
14     dict_get,
15     ExtractorError,
16     float_or_none,
17     int_or_none,
18     parse_duration,
19     qualities,
20     srt_subtitles_timecode,
21     try_get,
22     update_url_query,
23     urlencode_postdata,
24 )
25
26
27 class PluralsightBaseIE(InfoExtractor):
28     _API_BASE = 'https://app.pluralsight.com'
29
30     _GRAPHQL_EP = '%s/player/api/graphql' % _API_BASE
31     _GRAPHQL_HEADERS = {
32         'Content-Type': 'application/json;charset=UTF-8',
33     }
34     _GRAPHQL_COURSE_TMPL = '''
35 query BootstrapPlayer {
36   rpc {
37     bootstrapPlayer {
38       profile {
39         firstName
40         lastName
41         email
42         username
43         userHandle
44         authed
45         isAuthed
46         plan
47       }
48       course(courseId: "%s") {
49         name
50         title
51         courseHasCaptions
52         translationLanguages {
53           code
54           name
55         }
56         supportsWideScreenVideoFormats
57         timestamp
58         modules {
59           name
60           title
61           duration
62           formattedDuration
63           author
64           authorized
65           clips {
66             authorized
67             clipId
68             duration
69             formattedDuration
70             id
71             index
72             moduleIndex
73             moduleTitle
74             name
75             title
76             watched
77           }
78         }
79       }
80     }
81   }
82 }'''
83
84     def _download_course(self, course_id, url, display_id):
85         try:
86             return self._download_course_rpc(course_id, url, display_id)
87         except ExtractorError:
88             # Old API fallback
89             return self._download_json(
90                 'https://app.pluralsight.com/player/user/api/v1/player/payload',
91                 display_id, data=urlencode_postdata({'courseId': course_id}),
92                 headers={'Referer': url})
93
94     def _download_course_rpc(self, course_id, url, display_id):
95         response = self._download_json(
96             self._GRAPHQL_EP, display_id, data=json.dumps({
97                 'query': self._GRAPHQL_COURSE_TMPL % course_id,
98                 'variables': {}
99             }).encode('utf-8'), headers=self._GRAPHQL_HEADERS)
100
101         course = try_get(
102             response, lambda x: x['data']['rpc']['bootstrapPlayer']['course'],
103             dict)
104         if course:
105             return course
106
107         raise ExtractorError(
108             '%s said: %s' % (self.IE_NAME, response['error']['message']),
109             expected=True)
110
111
112 class PluralsightIE(PluralsightBaseIE):
113     IE_NAME = 'pluralsight'
114     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
115     _LOGIN_URL = 'https://app.pluralsight.com/id/'
116
117     _NETRC_MACHINE = 'pluralsight'
118
119     _TESTS = [{
120         'url': 'http://www.pluralsight.com/training/player?author=mike-mckeown&name=hosting-sql-server-windows-azure-iaas-m7-mgmt&mode=live&clip=3&course=hosting-sql-server-windows-azure-iaas',
121         'md5': '4d458cf5cf4c593788672419a8dd4cf8',
122         'info_dict': {
123             'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
124             'ext': 'mp4',
125             'title': 'Demo Monitoring',
126             'duration': 338,
127         },
128         'skip': 'Requires pluralsight account credentials',
129     }, {
130         'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
131         'only_matching': True,
132     }, {
133         # available without pluralsight account
134         'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
135         'only_matching': True,
136     }, {
137         'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
138         'only_matching': True,
139     }]
140
141     GRAPHQL_VIEWCLIP_TMPL = '''
142 query viewClip {
143   viewClip(input: {
144     author: "%(author)s",
145     clipIndex: %(clipIndex)d,
146     courseName: "%(courseName)s",
147     includeCaptions: %(includeCaptions)s,
148     locale: "%(locale)s",
149     mediaType: "%(mediaType)s",
150     moduleName: "%(moduleName)s",
151     quality: "%(quality)s"
152   }) {
153     urls {
154       url
155       cdn
156       rank
157       source
158     },
159     status
160   }
161 }'''
162
163     def _real_initialize(self):
164         self._login()
165
166     def _login(self):
167         username, password = self._get_login_info()
168         if username is None:
169             return
170
171         login_page = self._download_webpage(
172             self._LOGIN_URL, None, 'Downloading login page')
173
174         login_form = self._hidden_inputs(login_page)
175
176         login_form.update({
177             'Username': username,
178             'Password': password,
179         })
180
181         post_url = self._search_regex(
182             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
183             'post url', default=self._LOGIN_URL, group='url')
184
185         if not post_url.startswith('http'):
186             post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
187
188         response = self._download_webpage(
189             post_url, None, 'Logging in',
190             data=urlencode_postdata(login_form),
191             headers={'Content-Type': 'application/x-www-form-urlencoded'})
192
193         error = self._search_regex(
194             r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
195             response, 'error message', default=None)
196         if error:
197             raise ExtractorError('Unable to login: %s' % error, expected=True)
198
199         if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
200             BLOCKED = 'Your account has been blocked due to suspicious activity'
201             if BLOCKED in response:
202                 raise ExtractorError(
203                     'Unable to login: %s' % BLOCKED, expected=True)
204             MUST_AGREE = 'To continue using Pluralsight, you must agree to'
205             if any(p in response for p in (MUST_AGREE, '>Disagree<', '>Agree<')):
206                 raise ExtractorError(
207                     'Unable to login: %s some documents. Go to pluralsight.com, '
208                     'log in and agree with what Pluralsight requires.'
209                     % MUST_AGREE, expected=True)
210
211             raise ExtractorError('Unable to log in')
212
213     def _get_subtitles(self, author, clip_idx, clip_id, lang, name, duration, video_id):
214         captions = None
215         if clip_id:
216             captions = self._download_json(
217                 '%s/transcript/api/v1/caption/json/%s/%s'
218                 % (self._API_BASE, clip_id, lang), video_id,
219                 'Downloading captions JSON', 'Unable to download captions JSON',
220                 fatal=False)
221         if not captions:
222             captions_post = {
223                 'a': author,
224                 'cn': int(clip_idx),
225                 'lc': lang,
226                 'm': name,
227             }
228             captions = self._download_json(
229                 '%s/player/retrieve-captions' % self._API_BASE, video_id,
230                 'Downloading captions JSON', 'Unable to download captions JSON',
231                 fatal=False, data=json.dumps(captions_post).encode('utf-8'),
232                 headers={'Content-Type': 'application/json;charset=utf-8'})
233         if captions:
234             return {
235                 lang: [{
236                     'ext': 'json',
237                     'data': json.dumps(captions),
238                 }, {
239                     'ext': 'srt',
240                     'data': self._convert_subtitles(duration, captions),
241                 }]
242             }
243
244     @staticmethod
245     def _convert_subtitles(duration, subs):
246         srt = ''
247         TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
248         TEXT_KEYS = ('text', 'Text')
249         for num, current in enumerate(subs):
250             current = subs[num]
251             start, text = (
252                 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
253                 dict_get(current, TEXT_KEYS))
254             if start is None or text is None:
255                 continue
256             end = duration if num == len(subs) - 1 else float_or_none(
257                 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
258             if end is None:
259                 continue
260             srt += os.linesep.join(
261                 (
262                     '%d' % num,
263                     '%s --> %s' % (
264                         srt_subtitles_timecode(start),
265                         srt_subtitles_timecode(end)),
266                     text,
267                     os.linesep,
268                 ))
269         return srt
270
271     def _real_extract(self, url):
272         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
273
274         author = qs.get('author', [None])[0]
275         name = qs.get('name', [None])[0]
276         clip_idx = qs.get('clip', [None])[0]
277         course_name = qs.get('course', [None])[0]
278
279         if any(not f for f in (author, name, clip_idx, course_name,)):
280             raise ExtractorError('Invalid URL', expected=True)
281
282         display_id = '%s-%s' % (name, clip_idx)
283
284         course = self._download_course(course_name, url, display_id)
285
286         collection = course['modules']
287
288         clip = None
289
290         for module_ in collection:
291             if name in (module_.get('moduleName'), module_.get('name')):
292                 for clip_ in module_.get('clips', []):
293                     clip_index = clip_.get('clipIndex')
294                     if clip_index is None:
295                         clip_index = clip_.get('index')
296                     if clip_index is None:
297                         continue
298                     if compat_str(clip_index) == clip_idx:
299                         clip = clip_
300                         break
301
302         if not clip:
303             raise ExtractorError('Unable to resolve clip')
304
305         title = clip['title']
306         clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
307
308         QUALITIES = {
309             'low': {'width': 640, 'height': 480},
310             'medium': {'width': 848, 'height': 640},
311             'high': {'width': 1024, 'height': 768},
312             'high-widescreen': {'width': 1280, 'height': 720},
313         }
314
315         QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
316         quality_key = qualities(QUALITIES_PREFERENCE)
317
318         AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
319
320         ALLOWED_QUALITIES = (
321             AllowedQuality('webm', ['high', ]),
322             AllowedQuality('mp4', ['low', 'medium', 'high', ]),
323         )
324
325         # Some courses also offer widescreen resolution for high quality (see
326         # https://github.com/rg3/youtube-dl/issues/7766)
327         widescreen = course.get('supportsWideScreenVideoFormats') is True
328         best_quality = 'high-widescreen' if widescreen else 'high'
329         if widescreen:
330             for allowed_quality in ALLOWED_QUALITIES:
331                 allowed_quality.qualities.append(best_quality)
332
333         # In order to minimize the number of calls to ViewClip API and reduce
334         # the probability of being throttled or banned by Pluralsight we will request
335         # only single format until formats listing was explicitly requested.
336         if self._downloader.params.get('listformats', False):
337             allowed_qualities = ALLOWED_QUALITIES
338         else:
339             def guess_allowed_qualities():
340                 req_format = self._downloader.params.get('format') or 'best'
341                 req_format_split = req_format.split('-', 1)
342                 if len(req_format_split) > 1:
343                     req_ext, req_quality = req_format_split
344                     req_quality = '-'.join(req_quality.split('-')[:2])
345                     for allowed_quality in ALLOWED_QUALITIES:
346                         if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
347                             return (AllowedQuality(req_ext, (req_quality, )), )
348                 req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
349                 return (AllowedQuality(req_ext, (best_quality, )), )
350             allowed_qualities = guess_allowed_qualities()
351
352         formats = []
353         for ext, qualities_ in allowed_qualities:
354             for quality in qualities_:
355                 f = QUALITIES[quality].copy()
356                 clip_post = {
357                     'author': author,
358                     'includeCaptions': 'false',
359                     'clipIndex': int(clip_idx),
360                     'courseName': course_name,
361                     'locale': 'en',
362                     'moduleName': name,
363                     'mediaType': ext,
364                     'quality': '%dx%d' % (f['width'], f['height']),
365                 }
366                 format_id = '%s-%s' % (ext, quality)
367
368                 try:
369                     viewclip = self._download_json(
370                         self._GRAPHQL_EP, display_id,
371                         'Downloading %s viewclip graphql' % format_id,
372                         data=json.dumps({
373                             'query': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
374                             'variables': {}
375                         }).encode('utf-8'),
376                         headers=self._GRAPHQL_HEADERS)['data']['viewClip']
377                 except ExtractorError:
378                     # Still works but most likely will go soon
379                     viewclip = self._download_json(
380                         '%s/video/clips/viewclip' % self._API_BASE, display_id,
381                         'Downloading %s viewclip JSON' % format_id, fatal=False,
382                         data=json.dumps(clip_post).encode('utf-8'),
383                         headers={'Content-Type': 'application/json;charset=utf-8'})
384
385                 # Pluralsight tracks multiple sequential calls to ViewClip API and start
386                 # to return 429 HTTP errors after some time (see
387                 # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
388                 # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
389                 # To somewhat reduce the probability of these consequences
390                 # we will sleep random amount of time before each call to ViewClip.
391                 self._sleep(
392                     random.randint(2, 5), display_id,
393                     '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
394
395                 if not viewclip:
396                     continue
397
398                 clip_urls = viewclip.get('urls')
399                 if not isinstance(clip_urls, list):
400                     continue
401
402                 for clip_url_data in clip_urls:
403                     clip_url = clip_url_data.get('url')
404                     if not clip_url:
405                         continue
406                     cdn = clip_url_data.get('cdn')
407                     clip_f = f.copy()
408                     clip_f.update({
409                         'url': clip_url,
410                         'ext': ext,
411                         'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
412                         'quality': quality_key(quality),
413                         'source_preference': int_or_none(clip_url_data.get('rank')),
414                     })
415                     formats.append(clip_f)
416
417         self._sort_formats(formats)
418
419         duration = int_or_none(
420             clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
421
422         # TODO: other languages?
423         subtitles = self.extract_subtitles(
424             author, clip_idx, clip.get('clipId'), 'en', name, duration, display_id)
425
426         return {
427             'id': clip_id,
428             'title': title,
429             'duration': duration,
430             'creator': author,
431             'formats': formats,
432             'subtitles': subtitles,
433         }
434
435
436 class PluralsightCourseIE(PluralsightBaseIE):
437     IE_NAME = 'pluralsight:course'
438     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
439     _TESTS = [{
440         # Free course from Pluralsight Starter Subscription for Microsoft TechNet
441         # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
442         'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
443         'info_dict': {
444             'id': 'hosting-sql-server-windows-azure-iaas',
445             'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
446             'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
447         },
448         'playlist_count': 31,
449     }, {
450         # available without pluralsight account
451         'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
452         'only_matching': True,
453     }, {
454         'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
455         'only_matching': True,
456     }]
457
458     def _real_extract(self, url):
459         course_id = self._match_id(url)
460
461         # TODO: PSM cookie
462
463         course = self._download_course(course_id, url, course_id)
464
465         title = course['title']
466         course_name = course['name']
467         course_data = course['modules']
468         description = course.get('description') or course.get('shortDescription')
469
470         entries = []
471         for num, module in enumerate(course_data, 1):
472             author = module.get('author')
473             module_name = module.get('name')
474             if not author or not module_name:
475                 continue
476             for clip in module.get('clips', []):
477                 clip_index = int_or_none(clip.get('index'))
478                 if clip_index is None:
479                     continue
480                 clip_url = update_url_query(
481                     '%s/player' % self._API_BASE, query={
482                         'mode': 'live',
483                         'course': course_name,
484                         'author': author,
485                         'name': module_name,
486                         'clip': clip_index,
487                     })
488                 entries.append({
489                     '_type': 'url_transparent',
490                     'url': clip_url,
491                     'ie_key': PluralsightIE.ie_key(),
492                     'chapter': module.get('title'),
493                     'chapter_number': num,
494                     'chapter_id': module.get('moduleRef'),
495                 })
496
497         return self.playlist_result(entries, course_id, title, description)