Merge remote-tracking branch 'rzhxeo/RTL_T'
[youtube-dl] / youtube_dl / YoutubeDL.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from __future__ import absolute_import
5
6 import io
7 import os
8 import re
9 import shutil
10 import socket
11 import sys
12 import time
13 import traceback
14
15 from .utils import *
16 from .extractor import get_info_extractor, gen_extractors
17 from .FileDownloader import FileDownloader
18
19
20 class YoutubeDL(object):
21     """YoutubeDL class.
22
23     YoutubeDL objects are the ones responsible of downloading the
24     actual video file and writing it to disk if the user has requested
25     it, among some other tasks. In most cases there should be one per
26     program. As, given a video URL, the downloader doesn't know how to
27     extract all the needed information, task that InfoExtractors do, it
28     has to pass the URL to one of them.
29
30     For this, YoutubeDL objects have a method that allows
31     InfoExtractors to be registered in a given order. When it is passed
32     a URL, the YoutubeDL object handles it to the first InfoExtractor it
33     finds that reports being able to handle it. The InfoExtractor extracts
34     all the information about the video or videos the URL refers to, and
35     YoutubeDL process the extracted information, possibly using a File
36     Downloader to download the video.
37
38     YoutubeDL objects accept a lot of parameters. In order not to saturate
39     the object constructor with arguments, it receives a dictionary of
40     options instead. These options are available through the params
41     attribute for the InfoExtractors to use. The YoutubeDL also
42     registers itself as the downloader in charge for the InfoExtractors
43     that are added to it, so this is a "mutual registration".
44
45     Available options:
46
47     username:          Username for authentication purposes.
48     password:          Password for authentication purposes.
49     videopassword:     Password for acces a video.
50     usenetrc:          Use netrc for authentication instead.
51     verbose:           Print additional info to stdout.
52     quiet:             Do not print messages to stdout.
53     forceurl:          Force printing final URL.
54     forcetitle:        Force printing title.
55     forceid:           Force printing ID.
56     forcethumbnail:    Force printing thumbnail URL.
57     forcedescription:  Force printing description.
58     forcefilename:     Force printing final filename.
59     simulate:          Do not download the video files.
60     format:            Video format code.
61     format_limit:      Highest quality format to try.
62     outtmpl:           Template for output names.
63     restrictfilenames: Do not allow "&" and spaces in file names
64     ignoreerrors:      Do not stop on download errors.
65     nooverwrites:      Prevent overwriting files.
66     playliststart:     Playlist item to start at.
67     playlistend:       Playlist item to end at.
68     matchtitle:        Download only matching titles.
69     rejecttitle:       Reject downloads for matching titles.
70     logtostderr:       Log messages to stderr instead of stdout.
71     writedescription:  Write the video description to a .description file
72     writeinfojson:     Write the video description to a .info.json file
73     writethumbnail:    Write the thumbnail image to a file
74     writesubtitles:    Write the video subtitles to a file
75     writeautomaticsub: Write the automatic subtitles to a file
76     allsubtitles:      Downloads all the subtitles of the video
77                        (requires writesubtitles or writeautomaticsub)
78     listsubtitles:     Lists all available subtitles for the video
79     subtitlesformat:   Subtitle format [srt/sbv/vtt] (default=srt)
80     subtitleslangs:    List of languages of the subtitles to download
81     keepvideo:         Keep the video file after post-processing
82     daterange:         A DateRange object, download only if the upload_date is in the range.
83     skip_download:     Skip the actual download of the video file
84     cachedir:          Location of the cache files in the filesystem.
85                        None to disable filesystem cache.
86     
87     The following parameters are not used by YoutubeDL itself, they are used by
88     the FileDownloader:
89     nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
90     noresizebuffer, retries, continuedl, noprogress, consoletitle
91     """
92
93     params = None
94     _ies = []
95     _pps = []
96     _download_retcode = None
97     _num_downloads = None
98     _screen_file = None
99
100     def __init__(self, params):
101         """Create a FileDownloader object with the given options."""
102         self._ies = []
103         self._ies_instances = {}
104         self._pps = []
105         self._progress_hooks = []
106         self._download_retcode = 0
107         self._num_downloads = 0
108         self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
109
110         if (sys.version_info >= (3,) and sys.platform != 'win32' and
111                 sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
112                 and not params['restrictfilenames']):
113             # On Python 3, the Unicode filesystem API will throw errors (#1474)
114             self.report_warning(
115                 u'Assuming --restrict-filenames isnce file system encoding '
116                 u'cannot encode all charactes. '
117                 u'Set the LC_ALL environment variable to fix this.')
118             params['restrictfilenames'] = True
119
120         self.params = params
121         self.fd = FileDownloader(self, self.params)
122
123         if '%(stitle)s' in self.params['outtmpl']:
124             self.report_warning(u'%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
125
126     def add_info_extractor(self, ie):
127         """Add an InfoExtractor object to the end of the list."""
128         self._ies.append(ie)
129         self._ies_instances[ie.ie_key()] = ie
130         ie.set_downloader(self)
131
132     def get_info_extractor(self, ie_key):
133         """
134         Get an instance of an IE with name ie_key, it will try to get one from
135         the _ies list, if there's no instance it will create a new one and add
136         it to the extractor list.
137         """
138         ie = self._ies_instances.get(ie_key)
139         if ie is None:
140             ie = get_info_extractor(ie_key)()
141             self.add_info_extractor(ie)
142         return ie
143
144     def add_default_info_extractors(self):
145         """
146         Add the InfoExtractors returned by gen_extractors to the end of the list
147         """
148         for ie in gen_extractors():
149             self.add_info_extractor(ie)
150
151     def add_post_processor(self, pp):
152         """Add a PostProcessor object to the end of the chain."""
153         self._pps.append(pp)
154         pp.set_downloader(self)
155
156     def to_screen(self, message, skip_eol=False):
157         """Print message to stdout if not in quiet mode."""
158         if not self.params.get('quiet', False):
159             terminator = [u'\n', u''][skip_eol]
160             output = message + terminator
161             write_string(output, self._screen_file)
162
163     def to_stderr(self, message):
164         """Print message to stderr."""
165         assert type(message) == type(u'')
166         output = message + u'\n'
167         if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
168             output = output.encode(preferredencoding())
169         sys.stderr.write(output)
170
171     def fixed_template(self):
172         """Checks if the output template is fixed."""
173         return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
174
175     def trouble(self, message=None, tb=None):
176         """Determine action to take when a download problem appears.
177
178         Depending on if the downloader has been configured to ignore
179         download errors or not, this method may throw an exception or
180         not when errors are found, after printing the message.
181
182         tb, if given, is additional traceback information.
183         """
184         if message is not None:
185             self.to_stderr(message)
186         if self.params.get('verbose'):
187             if tb is None:
188                 if sys.exc_info()[0]:  # if .trouble has been called from an except block
189                     tb = u''
190                     if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
191                         tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
192                     tb += compat_str(traceback.format_exc())
193                 else:
194                     tb_data = traceback.format_list(traceback.extract_stack())
195                     tb = u''.join(tb_data)
196             self.to_stderr(tb)
197         if not self.params.get('ignoreerrors', False):
198             if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
199                 exc_info = sys.exc_info()[1].exc_info
200             else:
201                 exc_info = sys.exc_info()
202             raise DownloadError(message, exc_info)
203         self._download_retcode = 1
204
205     def report_warning(self, message):
206         '''
207         Print the message to stderr, it will be prefixed with 'WARNING:'
208         If stderr is a tty file the 'WARNING:' will be colored
209         '''
210         if sys.stderr.isatty() and os.name != 'nt':
211             _msg_header=u'\033[0;33mWARNING:\033[0m'
212         else:
213             _msg_header=u'WARNING:'
214         warning_message=u'%s %s' % (_msg_header,message)
215         self.to_stderr(warning_message)
216
217     def report_error(self, message, tb=None):
218         '''
219         Do the same as trouble, but prefixes the message with 'ERROR:', colored
220         in red if stderr is a tty file.
221         '''
222         if sys.stderr.isatty() and os.name != 'nt':
223             _msg_header = u'\033[0;31mERROR:\033[0m'
224         else:
225             _msg_header = u'ERROR:'
226         error_message = u'%s %s' % (_msg_header, message)
227         self.trouble(error_message, tb)
228
229     def slow_down(self, start_time, byte_counter):
230         """Sleep if the download speed is over the rate limit."""
231         rate_limit = self.params.get('ratelimit', None)
232         if rate_limit is None or byte_counter == 0:
233             return
234         now = time.time()
235         elapsed = now - start_time
236         if elapsed <= 0.0:
237             return
238         speed = float(byte_counter) / elapsed
239         if speed > rate_limit:
240             time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
241
242     def report_writedescription(self, descfn):
243         """ Report that the description file is being written """
244         self.to_screen(u'[info] Writing video description to: ' + descfn)
245
246     def report_writesubtitles(self, sub_filename):
247         """ Report that the subtitles file is being written """
248         self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
249
250     def report_writeinfojson(self, infofn):
251         """ Report that the metadata file has been written """
252         self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
253
254     def report_file_already_downloaded(self, file_name):
255         """Report file has already been fully downloaded."""
256         try:
257             self.to_screen(u'[download] %s has already been downloaded' % file_name)
258         except (UnicodeEncodeError) as err:
259             self.to_screen(u'[download] The file has already been downloaded')
260
261     def increment_downloads(self):
262         """Increment the ordinal that assigns a number to each file."""
263         self._num_downloads += 1
264
265     def prepare_filename(self, info_dict):
266         """Generate the output filename."""
267         try:
268             template_dict = dict(info_dict)
269
270             template_dict['epoch'] = int(time.time())
271             autonumber_size = self.params.get('autonumber_size')
272             if autonumber_size is None:
273                 autonumber_size = 5
274             autonumber_templ = u'%0' + str(autonumber_size) + u'd'
275             template_dict['autonumber'] = autonumber_templ % self._num_downloads
276             if template_dict['playlist_index'] is not None:
277                 template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
278
279             sanitize = lambda k,v: sanitize_filename(
280                 u'NA' if v is None else compat_str(v),
281                 restricted=self.params.get('restrictfilenames'),
282                 is_id=(k==u'id'))
283             template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
284
285             filename = self.params['outtmpl'] % template_dict
286             return filename
287         except KeyError as err:
288             self.report_error(u'Erroneous output template')
289             return None
290         except ValueError as err:
291             self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
292             return None
293
294     def _match_entry(self, info_dict):
295         """ Returns None iff the file should be downloaded """
296
297         title = info_dict['title']
298         matchtitle = self.params.get('matchtitle', False)
299         if matchtitle:
300             if not re.search(matchtitle, title, re.IGNORECASE):
301                 return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
302         rejecttitle = self.params.get('rejecttitle', False)
303         if rejecttitle:
304             if re.search(rejecttitle, title, re.IGNORECASE):
305                 return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
306         date = info_dict.get('upload_date', None)
307         if date is not None:
308             dateRange = self.params.get('daterange', DateRange())
309             if date not in dateRange:
310                 return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
311         return None
312         
313     def extract_info(self, url, download=True, ie_key=None, extra_info={}):
314         '''
315         Returns a list with a dictionary for each video we find.
316         If 'download', also downloads the videos.
317         extra_info is a dict containing the extra values to add to each result
318          '''
319         
320         if ie_key:
321             ies = [self.get_info_extractor(ie_key)]
322         else:
323             ies = self._ies
324
325         for ie in ies:
326             if not ie.suitable(url):
327                 continue
328
329             if not ie.working():
330                 self.report_warning(u'The program functionality for this site has been marked as broken, '
331                                     u'and will probably not work.')
332
333             try:
334                 ie_result = ie.extract(url)
335                 if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
336                     break
337                 if isinstance(ie_result, list):
338                     # Backwards compatibility: old IE result format
339                     for result in ie_result:
340                         result.update(extra_info)
341                     ie_result = {
342                         '_type': 'compat_list',
343                         'entries': ie_result,
344                     }
345                 else:
346                     ie_result.update(extra_info)
347                 if 'extractor' not in ie_result:
348                     ie_result['extractor'] = ie.IE_NAME
349                 return self.process_ie_result(ie_result, download=download)
350             except ExtractorError as de: # An error we somewhat expected
351                 self.report_error(compat_str(de), de.format_traceback())
352                 break
353             except Exception as e:
354                 if self.params.get('ignoreerrors', False):
355                     self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
356                     break
357                 else:
358                     raise
359         else:
360             self.report_error(u'no suitable InfoExtractor: %s' % url)
361         
362     def process_ie_result(self, ie_result, download=True, extra_info={}):
363         """
364         Take the result of the ie(may be modified) and resolve all unresolved
365         references (URLs, playlist items).
366
367         It will also download the videos if 'download'.
368         Returns the resolved ie_result.
369         """
370
371         result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
372         if result_type == 'video':
373             ie_result.update(extra_info)
374             if 'playlist' not in ie_result:
375                 # It isn't part of a playlist
376                 ie_result['playlist'] = None
377                 ie_result['playlist_index'] = None
378             if download:
379                 self.process_info(ie_result)
380             return ie_result
381         elif result_type == 'url':
382             # We have to add extra_info to the results because it may be
383             # contained in a playlist
384             return self.extract_info(ie_result['url'],
385                                      download,
386                                      ie_key=ie_result.get('ie_key'),
387                                      extra_info=extra_info)
388         elif result_type == 'playlist':
389             # We process each entry in the playlist
390             playlist = ie_result.get('title', None) or ie_result.get('id', None)
391             self.to_screen(u'[download] Downloading playlist: %s'  % playlist)
392
393             playlist_results = []
394
395             n_all_entries = len(ie_result['entries'])
396             playliststart = self.params.get('playliststart', 1) - 1
397             playlistend = self.params.get('playlistend', -1)
398
399             if playlistend == -1:
400                 entries = ie_result['entries'][playliststart:]
401             else:
402                 entries = ie_result['entries'][playliststart:playlistend]
403
404             n_entries = len(entries)
405
406             self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
407                 (ie_result['extractor'], playlist, n_all_entries, n_entries))
408
409             for i,entry in enumerate(entries,1):
410                 self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
411                 extra = {
412                          'playlist': playlist, 
413                          'playlist_index': i + playliststart,
414                          }
415                 if not 'extractor' in entry:
416                     # We set the extractor, if it's an url it will be set then to
417                     # the new extractor, but if it's already a video we must make
418                     # sure it's present: see issue #877
419                     entry['extractor'] = ie_result['extractor']
420                 entry_result = self.process_ie_result(entry,
421                                                       download=download,
422                                                       extra_info=extra)
423                 playlist_results.append(entry_result)
424             ie_result['entries'] = playlist_results
425             return ie_result
426         elif result_type == 'compat_list':
427             def _fixup(r):
428                 r.setdefault('extractor', ie_result['extractor'])
429                 return r
430             ie_result['entries'] = [
431                 self.process_ie_result(_fixup(r), download=download)
432                 for r in ie_result['entries']
433             ]
434             return ie_result
435         else:
436             raise Exception('Invalid result type: %s' % result_type)
437
438     def process_info(self, info_dict):
439         """Process a single resolved IE result."""
440
441         assert info_dict.get('_type', 'video') == 'video'
442         #We increment the download the download count here to match the previous behaviour.
443         self.increment_downloads()
444
445         info_dict['fulltitle'] = info_dict['title']
446         if len(info_dict['title']) > 200:
447             info_dict['title'] = info_dict['title'][:197] + u'...'
448
449         # Keep for backwards compatibility
450         info_dict['stitle'] = info_dict['title']
451
452         if not 'format' in info_dict:
453             info_dict['format'] = info_dict['ext']
454
455         reason = self._match_entry(info_dict)
456         if reason is not None:
457             self.to_screen(u'[download] ' + reason)
458             return
459
460         max_downloads = self.params.get('max_downloads')
461         if max_downloads is not None:
462             if self._num_downloads > int(max_downloads):
463                 raise MaxDownloadsReached()
464
465         filename = self.prepare_filename(info_dict)
466
467         # Forced printings
468         if self.params.get('forcetitle', False):
469             compat_print(info_dict['title'])
470         if self.params.get('forceid', False):
471             compat_print(info_dict['id'])
472         if self.params.get('forceurl', False):
473             # For RTMP URLs, also include the playpath
474             compat_print(info_dict['url'] + info_dict.get('play_path', u''))
475         if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
476             compat_print(info_dict['thumbnail'])
477         if self.params.get('forcedescription', False) and 'description' in info_dict:
478             compat_print(info_dict['description'])
479         if self.params.get('forcefilename', False) and filename is not None:
480             compat_print(filename)
481         if self.params.get('forceformat', False):
482             compat_print(info_dict['format'])
483
484         # Do nothing else if in simulate mode
485         if self.params.get('simulate', False):
486             return
487
488         if filename is None:
489             return
490
491         try:
492             dn = os.path.dirname(encodeFilename(filename))
493             if dn != '' and not os.path.exists(dn):
494                 os.makedirs(dn)
495         except (OSError, IOError) as err:
496             self.report_error(u'unable to create directory ' + compat_str(err))
497             return
498
499         if self.params.get('writedescription', False):
500             try:
501                 descfn = filename + u'.description'
502                 self.report_writedescription(descfn)
503                 with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
504                     descfile.write(info_dict['description'])
505             except (KeyError, TypeError):
506                 self.report_warning(u'There\'s no description to write.')
507             except (OSError, IOError):
508                 self.report_error(u'Cannot write description file ' + descfn)
509                 return
510
511         subtitles_are_requested = any([self.params.get('writesubtitles', False),
512                                        self.params.get('writeautomaticsub')])
513
514         if  subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
515             # subtitles download errors are already managed as troubles in relevant IE
516             # that way it will silently go on when used with unsupporting IE
517             subtitles = info_dict['subtitles']
518             sub_format = self.params.get('subtitlesformat')
519             for sub_lang in subtitles.keys():
520                 sub = subtitles[sub_lang]
521                 if sub is None:
522                     continue
523                 try:
524                     sub_filename = subtitles_filename(filename, sub_lang, sub_format)
525                     self.report_writesubtitles(sub_filename)
526                     with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
527                             subfile.write(sub)
528                 except (OSError, IOError):
529                     self.report_error(u'Cannot write subtitles file ' + descfn)
530                     return
531
532         if self.params.get('writeinfojson', False):
533             infofn = filename + u'.info.json'
534             self.report_writeinfojson(infofn)
535             try:
536                 json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
537                 write_json_file(json_info_dict, encodeFilename(infofn))
538             except (OSError, IOError):
539                 self.report_error(u'Cannot write metadata to JSON file ' + infofn)
540                 return
541
542         if self.params.get('writethumbnail', False):
543             if info_dict.get('thumbnail') is not None:
544                 thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
545                 thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
546                 self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
547                                (info_dict['extractor'], info_dict['id']))
548                 uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
549                 with open(thumb_filename, 'wb') as thumbf:
550                     shutil.copyfileobj(uf, thumbf)
551                 self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
552                                (info_dict['extractor'], info_dict['id'], thumb_filename))
553
554         if not self.params.get('skip_download', False):
555             if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
556                 success = True
557             else:
558                 try:
559                     success = self.fd._do_download(filename, info_dict)
560                 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
561                     self.report_error(u'unable to download video data: %s' % str(err))
562                     return
563                 except (OSError, IOError) as err:
564                     raise UnavailableVideoError(err)
565                 except (ContentTooShortError, ) as err:
566                     self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
567                     return
568
569             if success:
570                 try:
571                     self.post_process(filename, info_dict)
572                 except (PostProcessingError) as err:
573                     self.report_error(u'postprocessing: %s' % str(err))
574                     return
575
576     def download(self, url_list):
577         """Download a given list of URLs."""
578         if len(url_list) > 1 and self.fixed_template():
579             raise SameFileError(self.params['outtmpl'])
580
581         for url in url_list:
582             try:
583                 #It also downloads the videos
584                 videos = self.extract_info(url)
585             except UnavailableVideoError:
586                 self.report_error(u'unable to download video')
587             except MaxDownloadsReached:
588                 self.to_screen(u'[info] Maximum number of downloaded files reached.')
589                 raise
590
591         return self._download_retcode
592
593     def post_process(self, filename, ie_info):
594         """Run all the postprocessors on the given file."""
595         info = dict(ie_info)
596         info['filepath'] = filename
597         keep_video = None
598         for pp in self._pps:
599             try:
600                 keep_video_wish,new_info = pp.run(info)
601                 if keep_video_wish is not None:
602                     if keep_video_wish:
603                         keep_video = keep_video_wish
604                     elif keep_video is None:
605                         # No clear decision yet, let IE decide
606                         keep_video = keep_video_wish
607             except PostProcessingError as e:
608                 self.report_error(e.msg)
609         if keep_video is False and not self.params.get('keepvideo', False):
610             try:
611                 self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
612                 os.remove(encodeFilename(filename))
613             except (IOError, OSError):
614                 self.report_warning(u'Unable to remove downloaded video file')