]>
gitweb.michael.orlitzky.com - dead/whatever-dl.git/blob - src/uri_utilities.rb
2 # Copyright Michael Orlitzky
4 # http://michael.orlitzky.com/
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # http://www.fsf.org/licensing/licenses/gpl.html
20 require 'vendor/ruby-progressbar/progressbar'
22 # Just a couple of convenience methods for URIs.
23 # These could be monkey-patched in, but with only
24 # a few methods, that'd be asking (unnecessarily)
28 # Download the given URI object to <outfile_name>.
29 # Should use the progress_proc parameter to show
30 # a progress bar using the Ruby/ProgressBar library.
31 def download_with_progress_bar(uri
, outfile_name
)
32 # We wrap the whole thing in a begin/rescue so that
33 # we can clean up afterwards in case of an error.
35 File
.open(outfile_name
, 'wb') do |outfile
|
37 uri
.open(:content_length_proc => lambda
{|content_length
|
38 if content_length
&& (0 < content_length
)
39 pbar
= ProgressBar
.new("Download", content_length
)
40 pbar
.instance_eval
{ @bar_mark = '=' }
41 pbar
.file_transfer_mode
44 :progress_proc => lambda
{|size
|
45 pbar
.set(size
) if pbar
47 outfile
.write(video_file
.read
)
51 # Toss out an empty line to get rid of the progress bar.
52 # Normally, it would remain on the shell's "current" line.
55 rescue Errno
::EACCES => e
56 # Don't delete the file if it's unwritable.
59 # Here we get rid of the output file if there was an error.
60 # We test File.exists? first since the first line, the open()
61 # call, could theoretically fail.
62 File
.delete(outfile_name
) if File
.exists
?(outfile_name
)