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