Class: DAV4Rack::MongoResource

Inherits:
Resource
  • Object
show all
Defined in:
lib/dav4rack/resources/mongo_resource.rb

Constant Summary

Constants included from HTTPStatus

HTTPStatus::StatusMessage

Instance Attribute Summary

Attributes inherited from Resource

#options, #path, #propstat_relative_path, #public_path, #request, #response, #root_xml_attributes, #user

Instance Method Summary collapse

Methods inherited from Resource

#==, #allows_redirect?, #descendants, #display_name, #get_property, #index_page, #is_ms_client?, #lock, #lock_check, #method_missing, method_missing, #name, #parent, #parent_collection?, #parent_exists?, #properties, #remove_property, #resource_type, #set_property, #supports_locking?, #unlock, #use_compat_mkcol_response?, #use_ms_compat_creationdate?

Constructor Details

#initialize(public_path, path, request, response, options) ⇒ MongoResource

@@logger = Rails.logger



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/dav4rack/resources/mongo_resource.rb', line 10

def initialize(public_path, path, request, response, options)
  # 'ASCII-8BIT'で渡される場合があるので'UTF-8'を指定しておく
  _force_encoding!(public_path)
  _force_encoding!(path)
  super(public_path, path, request, response, options)
  @filesystem = Mongo::GridFileSystem.new(Mongoid.database)
  @collection = Mongoid.database.collection('fs.files')
  if options[:bson]
    @bson = options[:bson]
  elsif path.length <= 1
    # ルートの場合 (''の場合と'/'の場合がある)
    @bson = {'filename' => root + '/'}
  else
    # ファイルかディレクトリが、パラメータだけでは判断できない。ので \/? が必要。
    # だから、ディレクトリと同名のファイルは、作成できない。
    @bson = @collection.find_one({:filename => /^#{Regexp.escape(file_path)}\/?$/}) rescue nil
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class DAV4Rack::Resource

Instance Method Details

#child(bson) ⇒ Object



29
30
31
32
33
34
# File 'lib/dav4rack/resources/mongo_resource.rb', line 29

def child(bson)
  path = remove(bson['filename'], root)
  public_path = @options[:root_uri_path] + path
  @options[:bson] = bson
  self.class.new(public_path, path, @request, @response, @options)
end

#childrenObject

If this is a collection, return the child resources.



37
38
39
40
41
42
43
44
# File 'lib/dav4rack/resources/mongo_resource.rb', line 37

def children
#     Dir[file_path + '/*'].map do |path|
#       child File.basename(path)
#     end
  @collection.find({:filename => /^#{Regexp.escape(@bson['filename'])}[^\/]+\/?$/}).map do |bson|
    child bson
  end
end

#collection?Boolean

Is this resource a collection?

Returns:

  • (Boolean)


47
48
49
50
# File 'lib/dav4rack/resources/mongo_resource.rb', line 47

def collection?
#     File.directory?(file_path)
  @bson && _collection?(@bson['filename'])
end

#content_lengthObject

Return the size in bytes for this resource.



92
93
94
95
# File 'lib/dav4rack/resources/mongo_resource.rb', line 92

def content_length
#     stat.size
  @bson['length'] || 0
end

#content_typeObject

Return the mime type of this resource.



82
83
84
85
86
87
88
89
# File 'lib/dav4rack/resources/mongo_resource.rb', line 82

def content_type
#     if stat.directory?
#       "text/html"
#     else 
#       mime_type(file_path, DefaultMimeTypes)
#     end
  @bson['contentType'] || "text/html"
end

#copy(dest, overwrite = false) ⇒ Object

HTTP COPY request.

Copy this resource to given destination resource.



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
208
209
210
211
212
213
214
215
216
217
# File 'lib/dav4rack/resources/mongo_resource.rb', line 170

def copy(dest, overwrite = false)
#     if(dest.path == path)
#       Conflict
#     elsif(stat.directory?)
#       dest.make_collection
#       FileUtils.cp_r("#{file_path}/.", "#{dest.send(:file_path)}/")
#       OK
#     else
#       exists = File.exists?(file_path)
#       if(exists && !overwrite)
#         PreconditionFailed
#       else
#         open(file_path, "rb") do |file|
#           dest.write(file)
#         end
#         exists ? NoContent : Created
#       end
#     end

  # ディレクトリなら末尾に「/」をつける。
  # (dstにもともと「/」が付いているかどうか、クライアントに依存している)
  # CarotDAV : 「/」が付いていない
  # TeamFile : 「/」が付いている
  dest.collection! if collection?

  src = @bson['filename']
  dst = dest.file_path
  exists = nil

  @collection.find({:filename => /^#{Regexp.escape(src)}/}).each do |bson|
    src_name = bson['filename']
    dst_name = dst + src_name.slice(src.length, src_name.length)

    exists = @collection.find_one({:filename => dst_name}) rescue nil

    return PreconditionFailed if (exists && !overwrite && !collection?)

    @filesystem.open(src_name, "r") do |src|
    @filesystem.open(dst_name, "w") do |dst|
      dst.write(src) if src.file_length > 0
    end
    end

    @collection.remove(exists) if exists
  end

  collection? ? Created : (exists ? NoContent : Created)
end

#creation_dateObject

Return the creation time.



59
60
61
62
# File 'lib/dav4rack/resources/mongo_resource.rb', line 59

def creation_date
#     stat.ctime
  @bson['uploadDate'] || Date.new
end

#deleteObject

HTTP DELETE request.

Delete this resource.



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/dav4rack/resources/mongo_resource.rb', line 151

def delete
#     if stat.directory?
#       FileUtils.rm_rf(file_path)
#     else
#       File.unlink(file_path)
#     end
  if collection?
    @collection.find({:filename => /^#{Regexp.escape(@bson['filename'])}/}).each do |bson|
      @collection.remove(bson)
    end
  else
    @collection.remove(@bson)
  end
  NoContent
end

#etagObject

Return an Etag, an unique hash value for this resource.



76
77
78
79
# File 'lib/dav4rack/resources/mongo_resource.rb', line 76

def etag
#     sprintf('%x-%x-%x', stat.ino, stat.size, stat.mtime.to_i)
  @bson['_id'].to_s
end

#exist?Boolean

Does this recource exist?

Returns:

  • (Boolean)


53
54
55
56
# File 'lib/dav4rack/resources/mongo_resource.rb', line 53

def exist?
#     File.exist?(file_path)
  @bson
end

#get(request, response) ⇒ Object

HTTP GET request.

Write the content of the resource to the response.body.

Raises:

  • (NotFound)


100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/dav4rack/resources/mongo_resource.rb', line 100

def get(request, response)
  raise NotFound unless exist?
#     if stat.directory?
#       response.body = ""
#       Rack::Directory.new(root).call(request.env)[2].each do |line|
#         response.body << line
#       end
#       response['Content-Length'] = response.body.size.to_s
#     else
#       file = Rack::File.new(root)
#       response.body = file
#     end
  if collection?
    response.body = "<html>"
    response.body << "<h2>" + file_path.html_safe + "</h2>"
    children.each do |child|
      name = child.file_path.html_safe
      path = child.public_path
      response.body << "<a href='" + path + "'>" + name + "</a>"
      response.body << "</br>"
    end
    response.body << "</html>"
    response['Content-Length'] = response.body.size.to_s
    response['Content-Type'] = 'text/html'
  else
    @filesystem.open(file_path, 'r') do |f|
      response.body = f
      response['Content-Type'] = @bson['contentType']
    end
  end

end

#last_modifiedObject

Return the time of last modification.



65
66
67
68
# File 'lib/dav4rack/resources/mongo_resource.rb', line 65

def last_modified
#     stat.mtime
  @bson['uploadDate'] || Date.new
end

#last_modified=(time) ⇒ Object

Set the time of last modification.



71
72
73
# File 'lib/dav4rack/resources/mongo_resource.rb', line 71

def last_modified=(time)
#      File.utime(Time.now, time, file_path)
end

#make_collectionObject

HTTP MKCOL request.

Create this resource as collection.



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/dav4rack/resources/mongo_resource.rb', line 253

def make_collection
#     Dir.mkdir(file_path)
#     Created

  # ディレクトリなら末尾に「/」をつける。
  # (dstにもともと「/」が付いているかどうか、クライアントに依存している)
  # CarotDAV : 「/」が付いていない
  # TeamFile : 「/」が付いている
  collection!

  bson = @collection.find_one({:filename => file_path}) rescue nil

  # 0バイトのファイルを作成しディレクトリの代わりとする
  @filesystem.open(file_path, "w") { |f| } if !bson
 
#      @@logger.error('make_collection : ' + file_path)

  Created
end

#move(dest, overwrite = false) ⇒ Object

HTTP MOVE request.

Move this resource to given destination resource.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/dav4rack/resources/mongo_resource.rb', line 222

def move(dest, overwrite = false)

  # ディレクトリなら末尾に「/」をつける。
  # (dstにもともと「/」が付いているかどうか、クライアントに依存している)
  # CarotDAV : 「/」が付いていない
  # TeamFile : 「/」が付いている
  dest.collection! if collection?

  src = @bson['filename']
  dst = dest.file_path
  exists = nil

  @collection.find({:filename => /^#{Regexp.escape(src)}/}).each do |bson|
    src_name = bson['filename']
    dst_name = dst + src_name.slice(src.length, src_name.length)

    exists = @collection.find_one({:filename => dst_name}) rescue nil

    # http://mongoid.org/docs/persistence/atomic.html
    # http://rubydoc.info/github/mongoid/mongoid/master/Mongoid/Collection#update-instance_method
    @collection.update({'_id' => bson['_id']}, {'$set' => {'filename' => dst_name}}, :safe => true)
    
    @collection.remove(exists) if exists
  end

  collection? ? Created : (exists ? NoContent : Created)
end

#post(request, response) ⇒ Object

HTTP POST request.

Usually forbidden.

Raises:

  • (HTTPStatus::Forbidden)


144
145
146
# File 'lib/dav4rack/resources/mongo_resource.rb', line 144

def post(request, response)
  raise HTTPStatus::Forbidden
end

#put(request, response) ⇒ Object

HTTP PUT request.

Save the content of the request.body.



136
137
138
139
# File 'lib/dav4rack/resources/mongo_resource.rb', line 136

def put(request, response)
  write(request.body)
  Created
end

#write(io) ⇒ Object

Write to this resource from given IO.



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/dav4rack/resources/mongo_resource.rb', line 274

def write(io)
#     tempfile = "#{file_path}.#{Process.pid}.#{object_id}"
#     open(tempfile, "wb") do |file|
#       while part = io.read(8192)
#         file << part
#       end
#     end
#     File.rename(tempfile, file_path)
#     ensure
#       File.unlink(tempfile) rescue nil

  # 同名のファイルができないように
  bson = @collection.find_one({:filename => file_path}) rescue nil

  @filesystem.open(file_path, "w", :content_type => _content_type(file_path)) { |f| f.write(io) }

  # 同名のファイルができないように
  @collection.remove(bson) if bson

end