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