Class: Dao::Upload

Inherits:
Map
  • Object
show all
Defined in:
lib/dao/upload.rb

Defined Under Namespace

Classes: Placeholder

Constant Summary collapse

UUIDPattern =
%r/^[a-zA-Z0-9-]+$/io
Age =
60 * 60 * 24
IOs =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conducer, *args, &block) ⇒ Upload

Returns a new instance of Upload.



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/dao/upload.rb', line 179

def initialize(conducer, *args, &block)
  @conducer   = conducer

  @options    = Map.options_for!(args)
  @key        = Dao.key_for(args)
  @hidden_key = Upload.hidden_key_for(@key)
  @name       = Upload.name_for(@hidden_key)

  @placeholder = Placeholder.new(@options[:placeholder])

  @path = nil
  @dirname, @basename = nil
  @value = nil
  @io = nil
  @tmpdir = nil

  url = @placeholder.url

  update(:file => @io, :cache => @value, :url => url)
end

Instance Attribute Details

#basenameObject

Returns the value of attribute basename.



173
174
175
# File 'lib/dao/upload.rb', line 173

def basename
  @basename
end

#conducerObject

Returns the value of attribute conducer.



165
166
167
# File 'lib/dao/upload.rb', line 165

def conducer
  @conducer
end

#dirnameObject

Returns the value of attribute dirname.



172
173
174
# File 'lib/dao/upload.rb', line 172

def dirname
  @dirname
end

#hidden_keyObject

Returns the value of attribute hidden_key.



168
169
170
# File 'lib/dao/upload.rb', line 168

def hidden_key
  @hidden_key
end

#ioObject

Returns the value of attribute io.



174
175
176
# File 'lib/dao/upload.rb', line 174

def io
  @io
end

#keyObject

Returns the value of attribute key.



166
167
168
# File 'lib/dao/upload.rb', line 166

def key
  @key
end

#nameObject

Returns the value of attribute name.



169
170
171
# File 'lib/dao/upload.rb', line 169

def name
  @name
end

#optionsObject

Returns the value of attribute options.



167
168
169
# File 'lib/dao/upload.rb', line 167

def options
  @options
end

#pathObject (readonly)

Returns the value of attribute path.



171
172
173
# File 'lib/dao/upload.rb', line 171

def path
  @path
end

#tmpdirObject

Returns the value of attribute tmpdir.



175
176
177
# File 'lib/dao/upload.rb', line 175

def tmpdir
  @tmpdir
end

#valueObject

Returns the value of attribute value.



170
171
172
# File 'lib/dao/upload.rb', line 170

def value
  @value
end

Class Method Details

.cleanname(path) ⇒ Object



48
49
50
51
# File 'lib/dao/upload.rb', line 48

def cleanname(path)
  basename = File.basename(path.to_s)
  CGI.unescape(basename).gsub(%r/[^0-9a-zA-Z_@)(~.-]/, '_').gsub(%r/_+/,'_')
end

.clear!(options = {}) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/dao/upload.rb', line 67

def clear!(options = {})
  return if Upload.turd?

  glob = File.join(root, '*')
  age = Integer(options[:age] || options['age'] || Age)
  since = options[:since] || options['since'] || Time.now

  Dir.glob(glob) do |entry|
    begin
      next unless test(?d, entry)
      next unless File.basename(entry) =~ UUIDPattern

      files = Dir.glob(File.join(entry, '**/**'))

      all_files_are_old =
        files.all? do |file|
          begin
            stat = File.stat(file)
            file_age = since - stat.atime
            file_age >= age
          rescue
            false
          end
        end

      FileUtils.rm_rf(entry) if all_files_are_old
    rescue
      next
    end
  end
end

.finalizer(object_id) ⇒ Object



57
58
59
60
61
62
# File 'lib/dao/upload.rb', line 57

def finalizer(object_id)
  if fd = IOs[object_id]
    ::IO.for_fd(fd).close rescue nil
    IOs.delete(object_id)
  end
end

.hidden_key_for(*key) ⇒ Object



53
54
55
# File 'lib/dao/upload.rb', line 53

def hidden_key_for(*key)
  Dao.key_for('uploads', *key)
end

.name_for(key, &block) ⇒ Object



118
119
120
121
122
123
124
# File 'lib/dao/upload.rb', line 118

def name_for(key, &block)
  if block
    @name_for = block
  else
    defined?(@name_for) ? @name_for.call(key) : [prefix, *Array(key)].compact.join('.')
  end
end

.path_for(arg) ⇒ Object



155
156
157
158
159
160
# File 'lib/dao/upload.rb', line 155

def path_for(arg)
  [:original_path, :original_filename, :path, :filename, :pathname].
    map{|msg| arg.send(msg).to_s if arg.respond_to?(msg)}.
    compact.
    first or raise("could not find path_for(#{ arg.inspect })")
end

.prefix(*value) ⇒ Object



126
127
128
129
# File 'lib/dao/upload.rb', line 126

def prefix(*value)
  @prefix = value.shift if value
  @prefix
end

.prefix=(value) ⇒ Object



131
132
133
# File 'lib/dao/upload.rb', line 131

def prefix=(value)
  @prefix = value
end

.rewind(io, &block) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/dao/upload.rb', line 135

def rewind(io, &block)
  begin
    pos = io.pos
    io.flush
    io.rewind
  rescue
    nil
  end

  begin
    block.call
  ensure
    begin
      io.pos = pos
    rescue
      nil
    end
  end
end

.rootObject



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/dao/upload.rb', line 18

def root
  @root ||= (
    if defined?(Rails.root) and Rails.root
      root = File.join(Rails.root, 'public', Upload.url)
      FileUtils.mkdir_p(root) unless test(?d, root)
      root
    else
      Dir.tmpdir
    end
  )
end

.root=(root) ⇒ Object



30
31
32
# File 'lib/dao/upload.rb', line 30

def root=(root)
  @root = File.expand_path(root)
end

.tmpdir(&block) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/dao/upload.rb', line 38

def tmpdir(&block)
  tmpdir = File.join(root, uuid)
  FileUtils.mkdir_p(tmpdir)
  if block
    block.call(tmpdir)
  else
    tmpdir
  end
end

.turd?Boolean

Returns:

  • (Boolean)


114
115
116
# File 'lib/dao/upload.rb', line 114

def turd?
  @turd ||= !!ENV['DAO_UPLOAD_TURD']
end

.urlObject



4
5
6
7
8
9
10
11
12
# File 'lib/dao/upload.rb', line 4

def url
  @url ||= (
    if defined?(Rails.root) and Rails.root
      '/system/uploads'
    else
      "file:/#{ root }"
    end
  )
end

.url=(url) ⇒ Object



14
15
16
# File 'lib/dao/upload.rb', line 14

def url=(url)
  @url = '/' + Array(url).join('/').squeeze('/').sub(%r|^/+|, '').sub(%r|/+$|, '')
end

.uuidObject



34
35
36
# File 'lib/dao/upload.rb', line 34

def uuid
  Dao.uuid
end

Instance Method Details

#_clearObject



239
240
241
# File 'lib/dao/upload.rb', line 239

def _clear
  clear!
end

#_keyObject



231
232
233
# File 'lib/dao/upload.rb', line 231

def _key
  key
end

#_set(value) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/dao/upload.rb', line 200

def _set(value)
  return unless value

  value =
    case
      when value.is_a?(Hash)
        Map.for(value)
      when value.respond_to?(:read)
        Map.for(:file => value)
      else
        Map.for(:cache => value.to_s)
    end

  cache = value[:cache]
  file = value[:file]

  unless cache.blank?
    process_previously_uploaded(cache)
  end

  unless file.blank?
    process_currently_uploaded(file)
  end

  url = @value ? File.join(Upload.url, @value) : @placeholder.url

  update(:file => @io, :cache => @value, :url => url)

  set_path(Upload.path_for(@io)) rescue nil
end

#_valueObject



235
236
237
# File 'lib/dao/upload.rb', line 235

def _value
  path
end

#blank?Boolean

Returns:

  • (Boolean)


247
248
249
# File 'lib/dao/upload.rb', line 247

def blank?
  @value.blank?
end

#clear!(&block) ⇒ Object Also known as: clear



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/dao/upload.rb', line 352

def clear!(&block)
  result = block ? block.call(@path) : nil 

  unless Upload.turd?
    begin
      FileUtils.rm_rf(@tmpdir) if test(?d, @tmpdir)
    rescue
      nil
    ensure
      @io.close rescue nil
      IOs.delete(object_id)
    end
  end

  result
end

#gcopen(path) ⇒ Object



317
318
319
320
321
322
323
# File 'lib/dao/upload.rb', line 317

def gcopen(path)
  set_path(path)
  @io = open(@path, 'rb')
  IOs[object_id] = @io.fileno
  ObjectSpace.define_finalizer(self, Upload.method(:finalizer).to_proc)
  @io
end

#hidden_valueObject



243
244
245
# File 'lib/dao/upload.rb', line 243

def hidden_value
  @value
end

#inspectObject



338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/dao/upload.rb', line 338

def inspect
  {
    Upload.name =>
      {
        :key          => key,
        :hidden_key   => hidden_key,
        :hidden_value => hidden_value,
        :name         => name,
        :path         => path,
        :io           => io
      }
  }.inspect
end

#placeholderObject



408
409
410
# File 'lib/dao/upload.rb', line 408

def placeholder
  @placeholder ||= Placeholder.new
end

#placeholder=(placeholder) ⇒ Object



412
413
414
# File 'lib/dao/upload.rb', line 412

def placeholder=(placeholder)
  @placeholder = placeholder.is_a?(Placeholder) ? placeholder : Placeholder.new(placeholder)
end

#process_currently_uploaded(io) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/dao/upload.rb', line 275

def process_currently_uploaded(io)
  unless @tmpdir
    @tmpdir = Upload.tmpdir
  end

  original_basename =
    [:original_path, :original_filename, :path, :filename, :pathname].
      map{|msg| io.send(msg).to_s if io.respond_to?(msg)}.
      compact.
      first

  basename = Upload.cleanname(original_basename)

  path = File.join(@tmpdir, basename)

  copied = false

  Upload.rewind(io) do
    src = Upload.path_for(io)
    dst = path

    strategies = [
      proc{ `ln -f #{ src.inspect } #{ dst.inspect } || cp -f #{ src.inspect } #{ dst.inspect }`},
      proc{ FileUtils.ln(src, dst) },
      proc{ FileUtils.cp(src, dst) },
      proc{ 
        open(dst, 'wb'){|fd| fd.write(io.read)} 
      }
    ]

    FileUtils.rm_f(dst)
    strategies.each do |strategy|
      strategy.call rescue nil
      break if((copied = test(?e, dst)))
    end
  end

  raise("failed to copy #{ io.path.inspect } -> #{ path.inspect }") unless copied

  gcopen(path) if test(?s, path)
end

#process_previously_uploaded(cache) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/dao/upload.rb', line 259

def process_previously_uploaded(cache)
  cache = cache.to_s.strip

  unless cache.empty?
    dirname, basename = File.split(File.expand_path(cache))
    relative_dirname = File.basename(dirname)
    relative_basename = File.join(relative_dirname, basename)
    path = Upload.root + '/' + relative_basename

    if test(?s, path)
      gcopen(path)
      @tmpdir = @dirname
    end
  end
end

#set_path(path) ⇒ Object Also known as: path=



325
326
327
328
329
330
331
332
333
334
# File 'lib/dao/upload.rb', line 325

def set_path(path)
  if path
    @path = path.to_s.strip
    @dirname, @basename = File.split(@path)
    @value = File.join(File.basename(@dirname), @basename).strip
    @path
  else
    @path, @dirname, @basename, @value = nil
  end
end

#to_sObject



255
256
257
# File 'lib/dao/upload.rb', line 255

def to_s
  self[:url]
end

#urlObject



251
252
253
# File 'lib/dao/upload.rb', line 251

def url
  self[:url]
end