]> gitweb.michael.orlitzky.com - dead/whatever-dl.git/blob - src/uri_utilities.rb
dcff2fe11c4ed330cf8ada0eb5df5f8d4acad371
[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 # 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, headers = {})
32 # We wrap the whole thing in a begin/rescue so that
33 # we can clean up afterwards in case of an error.
34 begin
35 File.open(outfile_name, 'wb') do |outfile|
36 pbar = nil
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
42 end
43 },
44 :progress_proc => lambda {|size|
45 pbar.set(size) if pbar
46 }
47 }.merge!(headers)) do |video_file|
48 outfile.write(video_file.read)
49 end
50 end
51
52 # Toss out an empty line to get rid of the progress bar.
53 # Normally, it would remain on the shell's "current" line.
54 puts ''
55
56 rescue Errno::EACCES => e
57 # Don't delete the file if it's unwritable.
58 raise(e)
59 rescue => e
60 # Here we get rid of the output file if there was an error.
61 # We test File.exists? first since the first line, the open()
62 # call, could theoretically fail.
63 File.delete(outfile_name) if File.exists?(outfile_name)
64 raise(e)
65 end
66 end
67
68 end