]>
gitweb.michael.orlitzky.com - dead/whatever-dl.git/blob - uri_utilities.rb
61d57af63ea29d84b03ef70b65dfebcbf34e6e32
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 # Get the filename portion of a given URI.
29 # Return nil if there is no filename portion.
31 return uri
.path
.split('/').last
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.
42 open(outfile_name
, 'wb') do |outfile
|
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
51 :progress_proc => lambda
{|size
|
52 pbar
.set(size
) if pbar
54 outfile
.write(video_file
.read
)
58 # Toss out an empty line to get rid of the progress bar.
59 # Normally, it would remain on the shell's "current" line.
62 rescue Errno
::EACCES => e
63 # Don't delete the file if it's unwritable.
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
)