Class: Vines::Storage::CouchDB

Inherits:
Vines::Storage show all
Defined in:
lib/vines/storage/couchdb.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ CouchDB

Returns a new instance of CouchDB.



20
21
22
23
24
25
# File 'lib/vines/storage/couchdb.rb', line 20

def initialize(&block)
  @config = {}
  instance_eval(&block)
  [:host, :port, :database].each {|key| raise "Must provide #{key}" unless @config[key] }
  @url = url(@config)
end

Instance Method Details

#find_fragment(jid, node) ⇒ Object



75
76
77
78
79
80
81
# File 'lib/vines/storage/couchdb.rb', line 75

def find_fragment(jid, node)
  jid = JID.new(jid).bare.to_s
  return if jid.empty?
  doc = get(fragment_id(jid, node))
  return unless doc && doc['type'] == 'Fragment'
  Nokogiri::XML(doc['xml']).root rescue nil
end

#find_user(jid) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/vines/storage/couchdb.rb', line 27

def find_user(jid)
  jid = JID.new(jid).bare.to_s
  return if jid.empty?
  doc = get("user:#{jid}")
  return unless doc && doc['type'] == 'User'
  User.new(jid: jid).tap do |user|
    user.name, user.password = doc.values_at('name', 'password')
    (doc['roster'] || {}).each_pair do |jid, props|
      user.roster << Contact.new(
        jid: jid,
        name: props['name'],
        subscription: props['subscription'],
        ask: props['ask'],
        groups: props['groups'] || [])
    end
  end
end

#find_vcard(jid) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/vines/storage/couchdb.rb', line 58

def find_vcard(jid)
  jid = JID.new(jid).bare.to_s
  return if jid.empty?
  doc = get("vcard:#{jid}")
  return unless doc && doc['type'] == 'Vcard'
  Nokogiri::XML(doc['card']).root rescue nil
end

#save_fragment(jid, node) ⇒ Object



83
84
85
86
87
88
89
90
# File 'lib/vines/storage/couchdb.rb', line 83

def save_fragment(jid, node)
  jid = JID.new(jid).bare.to_s
  id = fragment_id(jid, node)
  doc = get(id) || {'_id' => id}
  doc['type'] = 'Fragment'
  doc['xml'] = node.to_xml
  save_doc(doc)
end

#save_user(user) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/vines/storage/couchdb.rb', line 45

def save_user(user)
  id = "user:#{user.jid.bare}"
  doc = get(id) || {'_id' => id}
  doc['type'] = 'User'
  doc['name'] = user.name
  doc['password'] = user.password
  doc['roster'] = {}
  user.roster.each do |contact|
    doc['roster'][contact.jid.bare.to_s] = contact.to_h
  end
  save_doc(doc)
end

#save_vcard(jid, card) ⇒ Object



66
67
68
69
70
71
72
73
# File 'lib/vines/storage/couchdb.rb', line 66

def save_vcard(jid, card)
  jid = JID.new(jid).bare.to_s
  id = "vcard:#{jid}"
  doc = get(id) || {'_id' => id}
  doc['type'] = 'Vcard'
  doc['card'] = card.to_xml
  save_doc(doc)
end