]> gitweb.michael.orlitzky.com - dead/whatever-dl.git/blob - src/uri_utilities.rb
61d57af63ea29d84b03ef70b65dfebcbf34e6e32
[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 # Get the filename portion of a given URI.
29 # Return nil if there is no filename portion.
30 def get_filename(uri)
31 return uri.path.split('/').last
32 end
33
34
35 # Download the given URI object to <outfile_name>.
36 # Should use the progress_proc parameter to show
37 # a progress bar using the Ruby/ProgressBar library.
38 def download_with_progress_bar(uri, outfile_name)
39 # We wrap the whole thing in a begin/rescue so that
40 # we can clean up afterwards in case of an error.
41 begin
42 open(outfile_name, 'wb') do |outfile|
43 pbar = nil
44 uri.open(:content_length_proc => lambda {|content_length|
45 if content_length && (0 < content_length)
46 pbar = ProgressBar.new("Download", content_length)
47 pbar.instance_eval { @bar_mark = '=' }
48 pbar.file_transfer_mode
49 end
50 },
51 :progress_proc => lambda {|size|
52 pbar.set(size) if pbar
53 }) do |video_file|
54 outfile.write(video_file.read)
55 end
56 end
57
58 # Toss out an empty line to get rid of the progress bar.
59 # Normally, it would remain on the shell's "current" line.
60 puts ''
61
62 rescue Errno::EACCES => e
63 # Don't delete the file if it's unwritable.
64 raise(e)
65 rescue => e
66 # Here we get rid of the output file if there was an error.
67 # We test File.exists? first since the first line, the open()
68 # call, could theoretically fail.
69 File.delete(outfile_name) if File.exists?(outfile_name)
70 raise(e)
71 end
72 end
73
74 end