Class: OmniFiles::Storage
- Inherits:
-
Object
- Object
- OmniFiles::Storage
- Defined in:
- lib/omnifiles/storage.rb
Instance Method Summary collapse
- #delete_file(shortened) ⇒ Object
- #enumerate_docs ⇒ Object
-
#get_file(shortened) ⇒ Object
returns full url.
-
#get_file_and_bump(shortened) ⇒ Object
returns full url and update statistics.
-
#initialize(mongo_host, mongo_port, mongo_name, logger) ⇒ Storage
constructor
A new instance of Storage.
- #put_file(shortened, filename, mime) ⇒ Object
-
#shorten_file(sample, filename, mime) ⇒ Object
returns shortened url.
Constructor Details
#initialize(mongo_host, mongo_port, mongo_name, logger) ⇒ Storage
Returns a new instance of Storage.
11 12 13 14 15 16 17 18 19 |
# File 'lib/omnifiles/storage.rb', line 11 def initialize mongo_host, mongo_port, mongo_name, logger @logger = logger db = Mongo::Client.new([ mongo_host + ':' + mongo_port.to_s ], :database => mongo_name) raise 'No mongo found' unless db @coll = db[:files] raise 'Cannot use collection' unless @coll @shortener = UrlShortener.new(SecureRandom.hex(8), 1) end |
Instance Method Details
#delete_file(shortened) ⇒ Object
57 58 59 60 |
# File 'lib/omnifiles/storage.rb', line 57 def delete_file shortened resp = @coll.delete_many(shortened: shortened) resp.ok? && resp.n > 0 end |
#enumerate_docs ⇒ Object
62 63 64 |
# File 'lib/omnifiles/storage.rb', line 62 def enumerate_docs @coll.find.each { |doc| yield doc } end |
#get_file(shortened) ⇒ Object
returns full url
45 46 47 |
# File 'lib/omnifiles/storage.rb', line 45 def get_file shortened @coll.find(shortened: shortened).limit(1).first end |
#get_file_and_bump(shortened) ⇒ Object
returns full url and update statistics
50 51 52 53 54 55 |
# File 'lib/omnifiles/storage.rb', line 50 def get_file_and_bump shortened @coll.find_one_and_update({ shortened: shortened }, { "$inc" => { "accessed.count" => 1 }, "$set" => { "accessed.time" => Time.now.utc } }, return_document: :after ) end |
#put_file(shortened, filename, mime) ⇒ Object
37 38 39 40 41 42 |
# File 'lib/omnifiles/storage.rb', line 37 def put_file shortened, filename, mime doc = { original_filename: filename, shortened: shortened, mime: mime, accessed: { count: 0 }, created: { time: Time.now.utc } } res = @coll.insert_one(doc) @logger.info "mongo put result: #{res}" end |
#shorten_file(sample, filename, mime) ⇒ Object
returns shortened url
22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/omnifiles/storage.rb', line 22 def shorten_file sample, filename, mime counter = 0 begin # filename can be null hashing = [filename.to_s, mime, sample, counter.to_s].join '|' @logger.info "Hashing value " + hashing shortened = @shortener.shorten hashing counter += 1 next if shortened.size < 5 same_shortened = @coll.find(shortened: shortened).count > 0 raise 'Something goes wrong' if counter > 100 end while same_shortened shortened end |