]>
Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/udemy.py 
   1  from  __future__ 
import  unicode_literals
   5  from  . common 
import  InfoExtractor
  10      compat_urllib_request
,   26  class  UdemyIE ( InfoExtractor
):   33                              lecture/view/?\?lectureId=|   34                              [^/]+/learn/v4/t/lecture/   38      _LOGIN_URL 
=  'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'   39      _ORIGIN_URL 
=  'https://www.udemy.com'   40      _NETRC_MACHINE 
=  'udemy'   43          'url' :  'https://www.udemy.com/java-tutorial/#/lecture/172757' ,   44          'md5' :  '98eda5b657e752cf945d8445e261b5c5' ,   48              'title' :  'Introduction and Installation' ,   49              'description' :  'md5:c0d51f6f21ef4ec65f091055a5eef876' ,   52          'skip' :  'Requires udemy account credentials' ,   55          'url' :  'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906' ,   56          'only_matching' :  True ,   58          # no url in outputs format entry   59          'url' :  'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812' ,   60          'only_matching' :  True ,   63      def  _extract_course_info ( self
,  webpage
,  video_id
):   64          course 
=  self
._ parse
_ json
(   65              unescapeHTML ( self
._ search
_ regex
(   66                  r
'ng-init=["\' ].* \b course
=({.+ ?
})[; " \' ]',   67                  webpage, 'course', default='{}')),   68              video_id, fatal=False) or {}   69          course_id = course.get('id') or self._search_regex(   70              r'data-course-id=[" \' ]( \d
+) ', webpage, ' course 
id ')   71          return course_id, course.get(' title
')   73      def _enroll_course(self, base_url, webpage, course_id):   74          def combine_url(base_url, url):   75              return compat_urlparse.urljoin(base_url, url) if not url.startswith(' http
') else url   77          checkout_url = unescapeHTML(self._search_regex(   78              r' href
=([ " \' ])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',   79              webpage, 'checkout url', group='url', default=None))   82                  'Course  %s  is not free. You have to pay for it before you can download. '   83                  'Use this URL to confirm purchase:  %s '   84                  % (course_id, combine_url(base_url, checkout_url)),   87          enroll_url = unescapeHTML(self._search_regex(   88              r'href=([" \' ])( ?P
< url
>( ?
: https?
://( ?
: www\
.) ?udemy\
. com
) ?
/ course
/ subscribe
/.+ ?
) \
1 ',   89              webpage, ' enroll url
', group=' url
', default=None))   91              webpage = self._download_webpage(   92                  combine_url(base_url, enroll_url),   93                  course_id, ' Enrolling 
in  the course
',   94                  headers={' Referer
': base_url})   95              if ' > You have enrolled 
in ' in webpage:   96                  self.to_screen(' %s:  Successfully enrolled 
in  the course
' % course_id)   98      def _download_lecture(self, course_id, lecture_id):   99          return self._download_json(  100              ' https
:// www
. udemy
. com
/ api
- 2.0 / users
/ me
/ subscribed
- courses
/ %s/ lectures
/ %s ?
'  101              % (course_id, lecture_id),  102              lecture_id, ' Downloading lecture JSON
', query={  103                  ' fields
[ lecture
] ': ' title
, description
, view_html
, asset
',  104                  ' fields
[ asset
] ': ' asset_type
, stream_url
, thumbnail_url
, download_urls
, data
',  107      def _handle_error(self, response):  108          if not isinstance(response, dict):  110          error = response.get(' error
')  112              error_str = ' Udemy returned error 
#%s: %s' % (error.get('code'), error.get('message'))  113              error_data 
=  error
. get ( 'data' )  115                  error_str 
+=  ' -  %s '  %  error_data
. get ( 'formErrors' )  116              raise  ExtractorError ( error_str
,  expected
= True )  118      def  _download_webpage ( self
, * args
, ** kwargs
):  119          kwargs
. setdefault ( 'headers' , {})[ 'User-Agent' ] =  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4'  120          return  super ( UdemyIE
,  self
) ._ download
_ webpage
(  121              * args
, ** compat_kwargs ( kwargs
))  123      def  _download_json ( self
,  url_or_request
, * args
, ** kwargs
):  125              'X-Udemy-Snail-Case' :  'true' ,  126              'X-Requested-With' :  'XMLHttpRequest' ,  128          for  cookie 
in  self
._ downloader
. cookiejar
:  129              if  cookie
. name 
==  'client_id' :  130                  headers
[ 'X-Udemy-Client-Id' ] =  cookie
. value
 131              elif  cookie
. name 
==  'access_token' :  132                  headers
[ 'X-Udemy-Bearer-Token' ] =  cookie
. value
 133                  headers
[ 'X-Udemy-Authorization' ] =  'Bearer  %s '  %  cookie
. value
 135          if  isinstance ( url_or_request
,  compat_urllib_request
. Request
):  136              for  header
,  value 
in  headers
. items ():  137                  url_or_request
. add_header ( header
,  value
)  139              url_or_request 
=  sanitized_Request ( url_or_request
,  headers
= headers
)  141          response 
=  super ( UdemyIE
,  self
) ._ download
_ json
( url_or_request
, * args
, ** kwargs
)  142          self
._ handle
_ error
( response
)  145      def  _real_initialize ( self
):  149          ( username
,  password
) =  self
._ get
_l ogin
_ info
()  153          login_popup 
=  self
._ download
_ webpage
(  154              self
._L OGIN
_U RL
,  None ,  'Downloading login popup' )  156          def  is_logged ( webpage
):  157              return  any ( re
. search ( p
,  webpage
)  for  p 
in  (  158                  r
'href=["\' ]( ?
: https
:// www\
. udemy\
. com
) ?
/ user
/ logout
/ ',  162          if is_logged(login_popup):  165          login_form = self._form_hidden_inputs(' login
- form
', login_popup)  169              ' password
': password,  172          response = self._download_webpage(  173              self._LOGIN_URL, None, ' Logging 
in ',  174              data=urlencode_postdata(login_form),  176                  ' Referer
': self._ORIGIN_URL,  177                  ' Origin
': self._ORIGIN_URL,  180          if not is_logged(response):  181              error = self._html_search_regex(  182                  r' ( ?s
)< div
[ ^
>]+ class = "form-errors[^" ]* ">(.+?)</div>',  183                  response, 'error message', default=None)  185                  raise ExtractorError('Unable to login:  %s ' % error, expected=True)  186              raise ExtractorError('Unable to log in')  188      def _real_extract(self, url):  189          lecture_id = self._match_id(url)  191          webpage = self._download_webpage(url, lecture_id)  193          course_id, _ = self._extract_course_info(webpage, lecture_id)  196              lecture = self._download_lecture(course_id, lecture_id)  197          except ExtractorError as e:  198              # Error could possibly mean we are not enrolled in the course  199              if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:  200                  self._enroll_course(url, webpage, course_id)  201                  lecture = self._download_lecture(course_id, lecture_id)  205          title = lecture['title']  206          description = lecture.get('description')  208          asset = lecture['asset']  210          asset_type = asset.get('asset_type') or asset.get('assetType')  211          if asset_type != 'Video':  212              raise ExtractorError(  213                  'Lecture  %s  is not a video' % lecture_id, expected=True)  215          stream_url = asset.get('stream_url') or asset.get('streamUrl')  217              youtube_url = self._search_regex(  218                  r'(https?://www\.youtube\.com/watch \? v=.*)', stream_url, 'youtube URL', default=None)  220                  return self.url_result(youtube_url, 'Youtube')  222          video_id = compat_str(asset['id'])  223          thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')  224          duration = float_or_none(asset.get('data', {}).get('duration'))  227          automatic_captions = {}  231          def extract_output_format(src, f_id):  233                  'url': src.get('url'),  234                  'format_id': ' %s p' % (src.get('height') or f_id),  235                  'width': int_or_none(src.get('width')),  236                  'height': int_or_none(src.get('height')),  237                  'vbr': int_or_none(src.get('video_bitrate_in_kbps')),  238                  'vcodec': src.get('video_codec'),  239                  'fps': int_or_none(src.get('frame_rate')),  240                  'abr': int_or_none(src.get('audio_bitrate_in_kbps')),  241                  'acodec': src.get('audio_codec'),  242                  'asr': int_or_none(src.get('audio_sample_rate')),  243                  'tbr': int_or_none(src.get('total_bitrate_in_kbps')),  244                  'filesize': int_or_none(src.get('file_size_in_bytes')),  247          outputs = asset.get('data', {}).get('outputs')  248          if not isinstance(outputs, dict):  251          def add_output_format_meta(f, key):  252              output = outputs.get(key)  253              if isinstance(output, dict):  254                  output_format = extract_output_format(output, key)  255                  output_format.update(f)  259          def extract_formats(source_list):  260              if not isinstance(source_list, list):  262              for source in source_list:  263                  video_url = source.get('file') or source.get('src')  264                  if not video_url or not isinstance(video_url, compat_str):  266                  if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':  267                      formats.extend(self._extract_m3u8_formats(  268                          video_url, video_id, 'mp4', entry_protocol='m3u8_native',  269                          m3u8_id='hls', fatal=False))  271                  format_id = source.get('label')  274                      'format_id': ' %s p' % format_id,  275                      'height': int_or_none(format_id),  278                      # Some videos contain additional metadata (e.g.  279                      # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)  280                      f = add_output_format_meta(f, format_id)  283          def extract_subtitles(track_list):  284              if not isinstance(track_list, list):  286              for track in track_list:  287                  if not isinstance(track, dict):  289                  if track.get('kind') != 'captions':  291                  src = track.get('src')  292                  if not src or not isinstance(src, compat_str):  294                  lang = track.get('language') or track.get(  295                      'srclang') or track.get('label')  296                  sub_dict = automatic_captions if track.get(  297                      'autogenerated') is True else subtitles  298                  sub_dict.setdefault(lang, []).append({  302          download_urls = asset.get('download_urls')  303          if isinstance(download_urls, dict):  304              extract_formats(download_urls.get('Video'))  306          view_html = lecture.get('view_html')  308              view_html_urls = set()  309              for source in re.findall(r'<source[^>]+>', view_html):  310                  attributes = extract_attributes(source)  311                  src = attributes.get('src')  314                  res = attributes.get('data-res')  315                  height = int_or_none(res)  316                  if src in view_html_urls:  318                  view_html_urls.add(src)  319                  if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':  320                      m3u8_formats = self._extract_m3u8_formats(  321                          src, video_id, 'mp4', entry_protocol='m3u8_native',  322                          m3u8_id='hls', fatal=False)  323                      for f in m3u8_formats:  324                          m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])  326                              if not f.get('height'):  327                                  f['height'] = int(m.group('height'))  329                                  f['tbr'] = int(m.group('tbr'))  330                      formats.extend(m3u8_formats)  332                      formats.append(add_output_format_meta({  334                          'format_id': ' %d p' % height if height else None,  338              # react rendition since 2017.04.15 (see  339              # https://github.com/rg3/youtube-dl/issues/12744)  340              data = self._parse_json(  342                      r'videojs-setup-data=([" \' ])( ?P
< data
>{.+ ?
}) \
1 ', view_html,  343                      ' setup data
', default=' {} ', group=' data
'), video_id,  344                  transform_source=unescapeHTML, fatal=False)  345              if data and isinstance(data, dict):  346                  extract_formats(data.get(' sources
'))  348                      duration = int_or_none(data.get(' duration
'))  349                  extract_subtitles(data.get(' tracks
'))  351              if not subtitles and not automatic_captions:  352                  text_tracks = self._parse_json(  354                          r' text
- tracks
=([ " \' ])(?P<data>\[.+?\])\1', view_html,  355                          'text tracks', default='{}', group='data'), video_id,  356                      transform_source=lambda s: js_to_json(unescapeHTML(s)),  358                  extract_subtitles(text_tracks)  360          self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))  365              'description': description,  366              'thumbnail': thumbnail,  367              'duration': duration,  369              'subtitles': subtitles,  370              'automatic_captions': automatic_captions,  374  class UdemyCourseIE(UdemyIE):  375      IE_NAME = 'udemy:course'  376      _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'  380      def suitable(cls, url):  381          return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)  383      def _real_extract(self, url):  384          course_path = self._match_id(url)  386          webpage = self._download_webpage(url, course_path)  388          course_id, title = self._extract_course_info(webpage, course_path)  390          self._enroll_course(url, webpage, course_id)  392          response = self._download_json(  393              'https://www.udemy.com/api-2.0/courses/ %s /cached-subscriber-curriculum-items' % course_id,  394              course_id, 'Downloading course curriculum', query={  395                  'fields[chapter]': 'title,object_index',  396                  'fields[lecture]': 'title,asset',  401          chapter, chapter_number = [None] * 2  402          for entry in response['results']:  403              clazz = entry.get('_class')  404              if clazz == 'lecture':  405                  asset = entry.get('asset')  406                  if isinstance(asset, dict):  407                      asset_type = asset.get('asset_type') or asset.get('assetType')  408                      if asset_type != 'Video':  410                  lecture_id = entry.get('id')  413                          '_type': 'url_transparent',  414                          'url': 'https://www.udemy.com/ %s /learn/v4/t/lecture/ %s ' % (course_path, entry['id']),  415                          'title': entry.get('title'),  416                          'ie_key': UdemyIE.ie_key(),  419                          entry['chapter_number'] = chapter_number  421                          entry['chapter'] = chapter  422                      entries.append(entry)  423              elif clazz == 'chapter':  424                  chapter_number = entry.get('object_index')  425                  chapter = entry.get('title')  427          return self.playlist_result(entries, course_id, title)