[lynda] Fix download if subtitles were not requested
[youtube-dl] / youtube_dl / extractor / lynda.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5
6 from .subtitles import SubtitlesInfoExtractor
7 from .common import InfoExtractor
8 from ..utils import ExtractorError
9
10
11 class LyndaIE(SubtitlesInfoExtractor):
12     IE_NAME = 'lynda'
13     IE_DESC = 'lynda.com videos'
14     _VALID_URL = r'https?://www\.lynda\.com/[^/]+/[^/]+/\d+/(\d+)-\d\.html'
15
16     _TEST = {
17         'url': 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
18         'file': '114408.mp4',
19         'md5': 'ecfc6862da89489161fb9cd5f5a6fac1',
20         'info_dict': {
21             'title': 'Using the exercise files',
22             'duration': 68
23         }
24     }
25     
26     def _real_extract(self, url):
27         mobj = re.match(self._VALID_URL, url)
28         video_id = mobj.group(1)
29
30         page = self._download_webpage('http://www.lynda.com/ajax/player?videoId=%s&type=video' % video_id,
31                                       video_id, 'Downloading video JSON')
32         video_json = json.loads(page)
33
34         if 'Status' in video_json and video_json['Status'] == 'NotFound':
35             raise ExtractorError('Video %s does not exist' % video_id, expected=True)
36
37         if video_json['HasAccess'] is False:
38             raise ExtractorError('Video %s is only available for members' % video_id, expected=True)
39
40         video_id = video_json['ID']
41         duration = video_json['DurationInSeconds']
42         title = video_json['Title']
43
44         formats = [{'url': fmt['Url'],
45                     'ext': fmt['Extension'],
46                     'width': fmt['Width'],
47                     'height': fmt['Height'],
48                     'filesize': fmt['FileSize'],
49                     'format_id': str(fmt['Resolution'])
50                     } for fmt in video_json['Formats']]
51
52         self._sort_formats(formats)
53         
54         if self._downloader.params.get('listsubtitles', False):
55             self._list_available_subtitles(video_id, page)
56             return
57         
58         subtitles = self._fix_subtitles(self.extract_subtitles(video_id, page))
59         
60         return {
61             'id': video_id,
62             'title': title,
63             'duration': duration,
64             'subtitles': subtitles,
65             'formats': formats
66         }
67         
68     _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
69
70     def _fix_subtitles(self, subtitles):
71         if subtitles is None:
72             return subtitles  # subtitles not requested
73
74         fixed_subtitles = {}
75         for k, v in subtitles.items():
76             subs = json.loads(v)
77             if len(subs) == 0:
78                 continue
79             srt = ''
80             for pos in range(0, len(subs) - 1):
81                 seq_current = subs[pos]
82                 m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
83                 if m_current is None:
84                     continue
85                 seq_next = subs[pos + 1]
86                 m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
87                 if m_next is None:
88                     continue
89                 appear_time = m_current.group('timecode')
90                 disappear_time = m_next.group('timecode')
91                 text = seq_current['Caption']
92                 srt += '%s\r\n%s --> %s\r\n%s' % (str(pos), appear_time, disappear_time, text)
93             if srt:
94                 fixed_subtitles[k] = srt
95         return fixed_subtitles
96         
97     def _get_available_subtitles(self, video_id, webpage):
98         url = 'http://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
99         sub = self._download_webpage(url, None, note=False)
100         sub_json = json.loads(sub)
101         return {'en': url} if len(sub_json) > 0 else {}
102
103
104 class LyndaCourseIE(InfoExtractor):
105     IE_NAME = 'lynda:course'
106     IE_DESC = 'lynda.com online courses'
107
108     # Course link equals to welcome/introduction video link of same course
109     # We will recognize it as course link
110     _VALID_URL = r'https?://(?:www|m)\.lynda\.com/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
111
112     def _real_extract(self, url):
113         mobj = re.match(self._VALID_URL, url)
114         course_path = mobj.group('coursepath')
115         course_id = mobj.group('courseid')
116
117         page = self._download_webpage('http://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
118                                       course_id, 'Downloading course JSON')
119         course_json = json.loads(page)
120
121         if 'Status' in course_json and course_json['Status'] == 'NotFound':
122             raise ExtractorError('Course %s does not exist' % course_id, expected=True)
123
124         unaccessible_videos = 0
125         videos = []
126
127         for chapter in course_json['Chapters']:
128             for video in chapter['Videos']:
129                 if video['HasAccess'] is not True:
130                     unaccessible_videos += 1
131                     continue
132                 videos.append(video['ID'])
133
134         if unaccessible_videos > 0:
135             self._downloader.report_warning('%s videos are only available for members and will not be downloaded' % unaccessible_videos)
136
137         entries = [
138             self.url_result('http://www.lynda.com/%s/%s-4.html' %
139                             (course_path, video_id),
140                             'Lynda')
141             for video_id in videos]
142
143         course_title = course_json['Title']
144
145         return self.playlist_result(entries, course_id, course_title)