]>
gitweb.michael.orlitzky.com - dead/whatever-dl.git/blob - uri_utilities.rb
f7ff3180de845194d6f6f6602b483ed58d11af5b
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 '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)
32 def content_length_callback(content_length
)
33 if content_length
&& (0 < content_length
)
34 @pbar = ProgressBar
.new("Download", content_length
)
35 @pbar.instance_eval
{ @bar_mark = '=' }
36 @pbar.file_transfer_mode
40 def progress_callback(size
)
41 @pbar.set(size
) if @pbar
45 # Download the given URI object to <outfile_name>.
46 # Should use the progress_proc parameter to show
47 # a progress bar using the Ruby/ProgressBar library.
48 def download_with_progress_bar(uri
, outfile_name
, headers
= {})
49 # We wrap the whole thing in a begin/rescue so that
50 # we can clean up afterwards in case of an error.
52 File
.open(outfile_name
, 'wb') do |outfile
|
53 # Convert our methods to Proc objects.
54 content_length_callback
= method(:content_length_callback)
55 progress_callback
= method(:progress_callback)
57 # So that they can be passed as arguments to open().
58 open_params
= { :content_length_proc => content_length_callback
,
59 :progress_proc => progress_callback
}
61 # Add the headers as additional parameters to the open() call.
62 open_params
.merge!
(headers
)
64 uri
.open(open_params
) do |video_file
|
65 outfile
.write(video_file
.read
)
69 # Toss out an empty line to get rid of the progress bar.
70 # Normally, it would remain on the shell's "current" line.
73 rescue Errno
::EACCES => e
74 # Don't delete the file if it's unwritable.
77 # Here we get rid of the output file if there was an error.
78 # We test File.exists? first since the first line, the open()
79 # call, could theoretically fail.
80 File
.delete(outfile_name
) if File
.exists
?(outfile_name
)