Module: Open

Defined in:
lib/rbbt/util/open.rb

Defined Under Namespace

Classes: OpenGzipError, OpenURLError

Constant Summary collapse

REMOTE_CACHEDIR =
"/tmp/open_cache"
LAST_TIME =

Remote WGET

{}

Class Method Summary collapse

Class Method Details

.add_cache(url, data, options = {}) ⇒ Object



105
106
107
108
# File 'lib/rbbt/util/open.rb', line 105

def self.add_cache(url, data, options = {})
  file = File.join(REMOTE_CACHEDIR, digest_url(url, options))
  Misc.sensiblewrite(file, data)
end

.cachedirObject



19
20
21
# File 'lib/rbbt/util/open.rb', line 19

def self.cachedir
  REMOTE_CACHEDIR
end

.cachedir=(cachedir) ⇒ Object



14
15
16
17
# File 'lib/rbbt/util/open.rb', line 14

def self.cachedir=(cachedir)
  REMOTE_CACHEDIR.replace cachedir
  FileUtils.mkdir REMOTE_CACHEDIR unless File.exist? REMOTE_CACHEDIR
end

.can_open?(file) ⇒ Boolean

Returns:

  • (Boolean)


209
210
211
# File 'lib/rbbt/util/open.rb', line 209

def self.can_open?(file)
  String === file and (File.exists?(file) or remote?(file))
end

.digest_url(url, options = {}) ⇒ Object



79
80
81
82
# File 'lib/rbbt/util/open.rb', line 79

def self.digest_url(url, options = {})
  params = [url, options.values_at("--post-data", "--post-data="), (options.include?("--post-file")? Open.read(options["--post-file"]).split("\n").sort * "\n" : "")]
  digest = Misc.digest(params.inspect)
end

.file_open(file, grep) ⇒ Object



123
124
125
126
127
128
129
# File 'lib/rbbt/util/open.rb', line 123

def self.file_open(file, grep)
  if grep
    grep(File.open(file), grep)
  else
    File.open(file)
  end
end

.grep(stream, grep) ⇒ Object

Grep



112
113
114
115
116
117
118
119
120
121
# File 'lib/rbbt/util/open.rb', line 112

def self.grep(stream, grep)
  case 
  when Array === grep
    TmpFile.with_file(grep * "\n", false) do |f|
      CMD.cmd("grep", "-w" => true, "-f" => f, :in => stream, :pipe => true, :post => proc{FileUtils.rm f})
    end
  else
    CMD.cmd("grep '#{grep}' -", :in => stream, :pipe => true, :post => proc{stream.force_close if stream.respond_to? :force_close})
  end
end

.gunzip(stream) ⇒ Object

Decompression



133
134
135
136
137
138
139
# File 'lib/rbbt/util/open.rb', line 133

def self.gunzip(stream)
  if String === stream
    Zlib::Inflate.inflate(stream)
  else
    CMD.cmd("gunzip", :pipe => true, :in => stream, :post => proc{stream.force_close if stream.respond_to? :force_close})
  end
end

.gzip?(file) ⇒ Boolean

Returns:

  • (Boolean)


153
154
155
# File 'lib/rbbt/util/open.rb', line 153

def self.gzip?(file)
  !! (file =~ /\.gz$/)
end

.in_cache(url, options = {}) ⇒ Object

Cache



85
86
87
88
89
90
91
92
# File 'lib/rbbt/util/open.rb', line 85

def self.in_cache(url, options = {})
  filename = File.join(REMOTE_CACHEDIR, digest_url(url, options))
  if File.exists? filename
    return filename 
  else
    nil
  end
end

.open(url, options = {}) ⇒ Object

Open Read Write



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/rbbt/util/open.rb', line 164

def self.open(url, options = {})
  options = Misc.add_defaults options, :noz => false

  wget_options = options[:wget_options] || {}
  wget_options[:nice] = options.delete(:nice)
  wget_options[:nice_key] = options.delete(:nice_key)
  wget_options[:quiet] = options.delete(:quiet)
  wget_options["--post-data="] = options.delete(:post) if options.include? :post
  wget_options["--post-file"] = options.delete("--post-file") if options.include? "--post-file"
  wget_options["--post-file="] = options.delete("--post-file=") if options.include? "--post-file="
  wget_options[:cookies] = options.delete(:cookies)

  io = case
       when (not remote?(url))
         file_open(url, options[:grep])
       when (options[:nocache] and options[:nocache] != :update)
         # What about grep?
         wget(url, wget_options)
       when (options[:nocache] != :update and in_cache(url, wget_options))
         Misc.lock(in_cache(url, wget_options)) do
           file_open(in_cache(url, wget_options), options[:grep])
         end
       else
         io = wget(url, wget_options)
         add_cache(url, io, wget_options)
         io.close
         file_open(in_cache(url, wget_options), options[:grep])
       end
  io = unzip(io)  if (zip?(url)  and not options[:noz]) or options[:zip]
  io = gunzip(io) if (gzip?(url) and not options[:noz]) or options[:gzip]

  if block_given?
    yield io 
  else
    io
  end

  class << io;
    attr_accessor :filename
  end

  io.filename = url.to_s
  io
end

.read(file, options = {}, &block) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/rbbt/util/open.rb', line 213

def self.read(file, options = {}, &block)
  f = open(file, options)

  if block_given?
    while not f.eof?
      l = f.gets
      l = fixutf8(l) if l.respond_to?(:valid_encoding?) && ! l.valid_encoding?
      yield l
    end
    f.close
  else
    text = Misc.fixutf8(f.read)
    f.close unless f.closed?
    text 
  end
end

.remote?(file) ⇒ Boolean

Questions

Returns:

  • (Boolean)


149
150
151
# File 'lib/rbbt/util/open.rb', line 149

def self.remote?(file)
  !! (file =~ /^(?:https?|ftp):\/\//)
end

.remove_from_cache(url, options = {}) ⇒ Object



94
95
96
97
98
99
100
101
102
103
# File 'lib/rbbt/util/open.rb', line 94

def self.remove_from_cache(url, options = {})
  digest = Misc.digest([url, options.values_at("--post-data", "--post-data="), (options.include?("--post-file")? Open.read(options["--post-file"]) : "")].inspect)

  filename = File.join(REMOTE_CACHEDIR, digest)
  if File.exists? filename
    FileUtils.rm filename 
  else
    nil
  end
end

.unzip(stream) ⇒ Object



141
142
143
144
145
# File 'lib/rbbt/util/open.rb', line 141

def self.unzip(stream)
  TmpFile.with_file(stream.read) do |filename|
    StringIO.new(CMD.cmd("unzip '{opt}' #{filename}", "-p" => true, :pipe => true).read)
  end
end

.wait(lag, key = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/rbbt/util/open.rb', line 25

def self.wait(lag, key = nil)
  time = Time.now   

  if LAST_TIME[key] != nil && (time < LAST_TIME[key] + lag)
    sleep (LAST_TIME[key] + lag) - time
  end

  LAST_TIME[key] = Time.now   
end

.wget(url, options = {}) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/rbbt/util/open.rb', line 35

def self.wget(url, options = {})
  Log.low "WGET:\n -URL: #{ url }\n -OPTIONS: #{options.inspect}"
  options = Misc.add_defaults options, "--user-agent=" => 'firefox', :pipe => true

  wait(options[:nice], options[:nice_key]) if options[:nice]
  options.delete(:nice)
  options.delete(:nice_key)

  pipe  = options.delete(:pipe)
  quiet = options.delete(:quiet)
  post  = options.delete(:post)
  cookies = options.delete(:cookies)

  options["--quiet"]     = quiet if options["--quiet"].nil?
  options["--post-data="] ||= post if post

  if cookies
    options["--save-cookies"] = cookies
    options["--load-cookies"] = cookies
    options["--keep-session-cookies"] = true
  end


  stderr = case
           when options['stderr']
             options['stderr'] 
           when options['--quiet']
             false
           else
             nil
           end

  begin
    CMD.cmd("wget '#{ url }'", options.merge(
      '-O' => '-', 
      :pipe => pipe, 
      :stderr => stderr
    ))
  rescue
   STDERR.puts $!.backtrace.inspect
   raise OpenURLError, "Error reading remote url: #{ url }.\n#{$!.message}"
  end
end

.write(file, content = nil) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/rbbt/util/open.rb', line 230

def self.write(file, content = nil)
  FileUtils.mkdir_p File.dirname(file)
  case
  when content.nil?
    begin
      File.open(file, 'w') do |f| 
        yield f
      end
    rescue Exception
      FileUtils.rm file if File.exists? file
      raise $!
    end
  when String === content
    File.open(file, 'w') do |f|
      f.flock(File::LOCK_EX)
      f.write content 
      f.flock(File::LOCK_UN)
    end
  else
    begin
      File.open(file, 'w') do |f| 
        f.flock(File::LOCK_EX)
        while not content.eof?
          f.write content.gets
        end
        f.flock(File::LOCK_UN)
      end
    rescue Exception
      FileUtils.rm file if File.exists? file
      raise $!
    end
    content.close
  end
end

.zip?(file) ⇒ Boolean

Returns:

  • (Boolean)


157
158
159
# File 'lib/rbbt/util/open.rb', line 157

def self.zip?(file)
  !! (file =~ /\.zip/)
end