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/redis.rb
Views: 11780
1
require 'redis'
2
3
module Anemone
4
module Storage
5
class Redis
6
7
MARSHAL_FIELDS = %w(links visited fetched)
8
9
def initialize(opts = {})
10
@redis = ::Redis.new(opts)
11
@key_prefix = opts[:key_prefix] || 'anemone'
12
keys.each { |key| delete(key) }
13
end
14
15
def [](key)
16
rkey = "#{@key_prefix}:pages:#{key.to_s}"
17
rget(rkey)
18
end
19
20
def []=(key, value)
21
rkey = "#{@key_prefix}:pages:#{key.to_s}"
22
hash = value.to_hash
23
MARSHAL_FIELDS.each do |field|
24
hash[field] = Marshal.dump(hash[field])
25
end
26
hash.each do |field, value|
27
@redis.hset(rkey, field, value)
28
end
29
end
30
31
def delete(key)
32
rkey = "#{@key_prefix}:pages:#{key.to_s}"
33
page = self[key]
34
@redis.del(rkey)
35
page
36
end
37
38
def each
39
rkeys = @redis.keys("#{@key_prefix}:pages:*")
40
rkeys.each do |rkey|
41
page = rget(rkey)
42
yield page.url.to_s, page
43
end
44
end
45
46
def merge!(hash)
47
hash.each { |key, value| self[key] = value }
48
self
49
end
50
51
def size
52
@redis.keys("#{@key_prefix}:pages:*").size
53
end
54
55
def keys
56
keys = []
57
self.each { |k, v| keys << k.to_s }
58
keys
59
end
60
61
def has_key?(key)
62
rkey = "#{@key_prefix}:pages:#{key.to_s}"
63
@redis.exists(rkey)
64
end
65
66
def close
67
@redis.quit
68
end
69
70
private
71
72
def load_value(hash)
73
MARSHAL_FIELDS.each do |field|
74
unless hash[field].nil? || hash[field] == ''
75
hash[field] = Marshal.load(hash[field])
76
end
77
end
78
Page.from_hash(hash)
79
end
80
81
def rget(rkey)
82
hash = @redis.hgetall(rkey)
83
if !!hash
84
load_value(hash)
85
end
86
end
87
88
end
89
end
90
end
91
92