]> gitweb.michael.orlitzky.com - dead/whatever-dl.git/blob - src/uri_utilities.rb
Clean up the code for UriUtilities.
[dead/whatever-dl.git] / src / uri_utilities.rb
1 #
2 # Copyright Michael Orlitzky
3 #
4 # http://michael.orlitzky.com/
5 #
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.
10 #
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.
15 #
16 # http://www.fsf.org/licensing/licenses/gpl.html
17 #
18
19 require 'open-uri'
20 require 'vendor/ruby-progressbar/progressbar'
21
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)
25 # for trouble.
26 class UriUtilities
27
28 def initialize()
29 @pbar = nil
30 end
31
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
37 end
38 end
39
40 def progress_callback(size)
41 @pbar.set(size) if @pbar
42 end
43
44
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.
51 begin
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)
56
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}
60
61 # Add the headers as additional parameters to the open() call.
62 open_params.merge!(headers)
63
64 uri.open(open_params) do |video_file|
65 outfile.write(video_file.read)
66 end
67 end
68
69 # Toss out an empty line to get rid of the progress bar.
70 # Normally, it would remain on the shell's "current" line.
71 puts ''
72
73 rescue Errno::EACCES => e
74 # Don't delete the file if it's unwritable.
75 raise(e)
76 rescue => e
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)
81 raise(e)
82 end
83 end
84
85 end