CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/anemone/storage/mongodb.rb
Views: 11780
1
begin
2
require 'mongo'
3
rescue LoadError
4
puts "You need the mongo gem to use Anemone::Storage::MongoDB"
5
exit
6
end
7
8
module Anemone
9
module Storage
10
class MongoDB
11
12
BINARY_FIELDS = %w(body headers data)
13
14
def initialize(mongo_db, collection_name)
15
@db = mongo_db
16
@collection = @db[collection_name]
17
@collection.remove
18
@collection.create_index 'url'
19
end
20
21
def [](url)
22
if value = @collection.find_one('url' => url.to_s)
23
load_page(value)
24
end
25
end
26
27
def []=(url, page)
28
hash = page.to_hash
29
BINARY_FIELDS.each do |field|
30
hash[field] = BSON::Binary.new(hash[field]) unless hash[field].nil?
31
end
32
@collection.update(
33
{'url' => page.url.to_s},
34
hash,
35
:upsert => true
36
)
37
end
38
39
def delete(url)
40
page = self[url]
41
@collection.remove('url' => url.to_s)
42
page
43
end
44
45
def each
46
@collection.find do |cursor|
47
cursor.each do |doc|
48
page = load_page(doc)
49
yield page.url.to_s, page
50
end
51
end
52
end
53
54
def merge!(hash)
55
hash.each { |key, value| self[key] = value }
56
self
57
end
58
59
def size
60
@collection.count
61
end
62
63
def keys
64
keys = []
65
self.each { |k, v| keys << k.to_s }
66
keys
67
end
68
69
def has_key?(url)
70
!!@collection.find_one('url' => url.to_s)
71
end
72
73
def close
74
@db.connection.close
75
end
76
77
private
78
79
def load_page(hash)
80
BINARY_FIELDS.each do |field|
81
hash[field] = hash[field].to_s
82
end
83
Page.from_hash(hash)
84
end
85
86
end
87
end
88
end
89
90
91