File: servicehelper.rb

package info (click to toggle)
ruby-xmpp4r 0.5.6-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,384 kB
  • sloc: ruby: 17,382; xml: 74; sh: 12; makefile: 4
file content (490 lines) | stat: -rw-r--r-- 15,714 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
218
219
220
221
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# =XMPP4R - XMPP Library for Ruby
# License:: Ruby's license (see the LICENSE file) or GNU GPL, at your option.
# Website::http://xmpp4r.github.io
#
# It's recommented to read the XEP-0060 before you use this Helper. (Maybe its
# better not use the helper for now ) ;)
# The whole code is getting better, but may still contain bugs - be careful!
#
# Maybe the following structure is good
# ( taken from the xep-0060 )
#
# entity usecases
#  retrieve all subscriptions
#  retrieve all affiliations
# NOTE: the disco stuff will done by the nodebrowserhelper
# subscriber usecases
#   subscribe
#   unsubscribe
#   configure subscription options
#   retrieve items from a node
# publisher usecases
#   publish a item to a node
#   delete a item from a node
# owner usecases
#   create a node
#   configure a node
#   request default configuration options
#   delete a node
#   purge all node items
#   manage subscription requests
#   process pending subscriptions
#   manage subscriptions
#   manage affiliations
#
# collection nodes
#
#  If someone want to implement something i think its better to do this in
#  this order because everyone who reads the xep-0060 do know where to search in the file
#
require 'xmpp4r/pubsub/iq/pubsub'
require 'xmpp4r/pubsub/children/event'
require 'xmpp4r/pubsub/children/item'
require 'xmpp4r/pubsub/children/items'
require 'xmpp4r/pubsub/children/subscription'
require 'xmpp4r/pubsub/children/unsubscribe'
require 'xmpp4r/pubsub/children/node_config'
require 'xmpp4r/pubsub/children/subscription_config'
require 'xmpp4r/pubsub/children/retract'
require 'xmpp4r/dataforms'

module Jabber
  module PubSub
    ##
    # A Helper representing a PubSub Service
    class ServiceHelper

      ##
      # Creates a new representation of a pubsub service
      # stream:: [Jabber::Stream]
      # pubsubjid:: [String] or [Jabber::JID]
      def initialize(stream, pubsubjid)
        @stream = stream
        @pubsubjid = pubsubjid
        @event_cbs = CallbackList.new
        @stream.add_message_callback(200,self) { |message|
          handle_message(message)
        }
      end

      ##
      # get all subscriptions on a pubsub component
      # return:: [Hash] of [PubSub::Subscription]
      def get_subscriptions_from_all_nodes
        iq = basic_pubsub_query(:get)
        entities = iq.pubsub.add(REXML::Element.new('subscriptions'))
        res = nil
        @stream.send_with_id(iq) { |reply|
          if reply.pubsub.first_element('subscriptions')
            res = []
            reply.pubsub.first_element('subscriptions').each_element('subscription') { |subscription|
              res << Jabber::PubSub::Subscription.import(subscription)
            }
          end
        }

        res
      end

      ##
      # get subids for a passed node
      # return:: [Array] of subids
      def get_subids_for(node)
        ret = []
        get_subscriptions_from_all_nodes.each do |subscription|
          if subscription.node == node
            ret << subscription.subid
          end
        end
        return ret
      end

      ##
      # subscribe to a node
      # node:: [String]
      # return:: [Hash] of { attributename => value }
      def subscribe_to(node)
        iq = basic_pubsub_query(:set)
        sub = REXML::Element.new('subscribe')
        sub.attributes['node'] = node
        sub.attributes['jid'] = @stream.jid.strip.to_s
        iq.pubsub.add(sub)
        res = nil
        @stream.send_with_id(iq) do |reply|
          pubsubanswer = reply.pubsub
          if pubsubanswer.first_element('subscription')
            res = PubSub::Subscription.import(pubsubanswer.first_element('subscription'))
          end
        end # @stream.send_with_id(iq)
        res
      end

      ##
      # Unsubscribe from a node with an optional subscription id
      #
      # May raise ServerError
      # node:: [String]
      # subid:: [String] or nil (not supported)
      # return:: true
      def unsubscribe_from(node, subid=nil)
        ret = []
        if subid.nil?
          subids = get_subids_for(node)
        else
          subids = [ subid ]
        end
        subids << nil if subids.empty?
        subids.each do |sid|
          iq = basic_pubsub_query(:set)
          unsub = PubSub::Unsubscribe.new
          unsub.node = node
          unsub.jid = @stream.jid.strip
          unsub.subid = sid
          iq.pubsub.add(unsub)
          res = false
          @stream.send_with_id(iq) { |reply|
            res = reply.kind_of?(Jabber::Iq) and reply.type == :result
          } # @stream.send_with_id(iq)
          ret << res
        end
        ret
      end

      ##
      # gets all items from a pubsub node
      # node:: [String]
      # count:: [Fixnum]
      # subid:: [String]
      # return:: [Hash] { id => [Jabber::PubSub::Item] }
      def get_items_from(node, count=nil, subid=nil)
        if subid.nil?
          # Hm... no subid passed. Let's see if we can provide one.
          subids = get_subids_for(node)
          if ! subids.empty?
            # If more than one, sorry. We'll just respect the first.
            subid = subids[0]
          end
        end
        iq = basic_pubsub_query(:get)
        items = Jabber::PubSub::Items.new
        items.max_items = count
        items.subid = subid unless subid.nil?  # if subid is still nil, we haven't any... why bother?
        items.node = node
        iq.pubsub.add(items)
        res = nil
        @stream.send_with_id(iq) { |reply|
          if reply.kind_of?(Iq) and reply.pubsub and reply.pubsub.first_element('items')
            res = {}
            reply.pubsub.first_element('items').each_element('item') do |item|
              res[item.attributes['id']] = item.children.first if item.children.first
            end
          end
          true
        }
        res
      end

      ##
      # NOTE: this method sends only one item per publish request because some services
      # may not allow batch processing.  Maybe this will changed in the future?
      # node:: [String]
      # item:: [Jabber::PubSub::Item]
      # return:: true
      def publish_item_to(node,item)
        iq = basic_pubsub_query(:set)
        publish = iq.pubsub.add(REXML::Element.new('publish'))
        publish.attributes['node'] = node

        if item.kind_of?(Jabber::PubSub::Item)
          publish.add(item)
          @stream.send_with_id(iq)
        end
      end

      ##
      # node:: [String]
      # item:: [REXML::Element]
      # id:: [String]
      # return:: true
      def publish_item_with_id_to(node,item,id)
        iq = basic_pubsub_query(:set)
        publish = iq.pubsub.add(REXML::Element.new('publish'))
        publish.attributes['node'] = node

        if item.kind_of?(REXML::Element)
          xmlitem = Jabber::PubSub::Item.new
          xmlitem.id = id
          xmlitem.import(item)
          publish.add(xmlitem)
        else
          raise "given item is not a proper xml document or Jabber::PubSub::Item"
        end
        @stream.send_with_id(iq)
      end

      ##
      # deletes an item from a persistent node
      # node:: [String]
      # item_id:: [String] or [Array] of [String]
      # return:: true
      def delete_item_from(node, item_id)
        iq = basic_pubsub_query(:set)
        retract = iq.pubsub.add(Jabber::PubSub::Retract.new)
        retract.node = node

        if item_id.kind_of? Array
          item_id.each { |id|
            xmlitem = Jabber::PubSub::Item.new
            xmlitem.id = id
            retract.add(xmlitem)
          }
        else
          xmlitem = Jabber::PubSub::Item.new
          xmlitem.id = item_id
          retract.add(xmlitem)
        end

        @stream.send_with_id(iq)
      end

      ##
      # purges all items on a persistent node
      # node:: [String]
      # return:: true
      def purge_items_from(node)
        iq = basic_pubsub_query(:set, true)
        purge = REXML::Element.new('purge')
        purge.attributes['node'] = node
        iq.pubsub.add(purge)
        @stream.send_with_id(iq)
      end

      ##
      # Create a new node on the pubsub service
      # node:: [String] the node name - otherwise you get a automatically generated one (in most cases)
      # configure:: [Jabber::PubSub::NodeConfig] if you want to configure your node (default nil)
      # return:: [String]
      def create_node(node = nil, configure = Jabber::PubSub::NodeConfig.new)
        rnode = nil
        iq = basic_pubsub_query(:set)
        iq.pubsub.add(REXML::Element.new('create')).attributes['node'] = node
        if configure
          if configure.kind_of?(Jabber::PubSub::NodeConfig)
            iq.pubsub.add(configure)
          end
        end

        @stream.send_with_id(iq) do |reply|
          if reply.kind_of?(Jabber::Iq) and reply.type == :result
            rnode = node
          end
        end

        rnode
      end

      ##
      # Create a new collection node on the pubsub service
      # node:: [String] the node name - otherwise you get an automatically generated one (in most cases)
      # configure:: [Jabber::PubSub::NodeConfig] if you want to configure your node (default nil)
      # return:: [String]
      def create_collection_node(node = nil, configure = Jabber::PubSub::NodeConfig.new)
        if configure.options['pubsub#node_type'] && configure.options['pubsub#node_type'] != 'collection'
          raise Jabber::ArgumentError, "Invalid node_type specified in node configuration. Either do not specify one, or use 'collection'"
        end
        configure.options = configure.options.merge({'pubsub#node_type' => 'collection'})
        create_node(node, configure)
      end

      ##
      # get configuration from a node
      # node:: [String]
      # return:: [Jabber::PubSub::Configure]
      def get_config_from(node)
        iq = basic_pubsub_query(:get, true)
        iq.pubsub.add(Jabber::PubSub::OwnerNodeConfig.new(node))
        ret = nil
        @stream.send_with_id(iq) do |reply|
          ret = reply.pubsub.first_element('configure')
        end
        ret
      end

      ##
      # set configuration for a node
      # node:: [String]
      # options:: [Jabber::PubSub::NodeConfig]
      # return:: true on success
      def set_config_for(node, config)
        iq = basic_pubsub_query(:set, true)
        iq.pubsub.add(config)
        @stream.send_with_id(iq)
      end

      ##
      # Delete a pubsub node
      # node:: [String]
      # return:: true
      def delete_node(node)
        iq = basic_pubsub_query(:set,true)
        iq.pubsub.add(REXML::Element.new('delete')).attributes['node'] = node
        @stream.send_with_id(iq)
      end

      def set_affiliations(node, jid, role = 'publisher')
        iq = basic_pubsub_query(:set, true)
        affiliations = iq.pubsub.add(REXML::Element.new('affiliations'))
        affiliations.attributes['node'] = node
        affiliation = affiliations.add(REXML::Element.new('affiliation'))
        affiliation.attributes['jid'] = jid.to_s
        affiliation.attributes['affiliation'] = role.to_s
        res = nil
        @stream.send_with_id(iq) { |reply|
          true
        }
        res
      end

      ##
      # shows the affiliations on a pubsub service
      # node:: [String]
      # return:: [Hash] of { node => symbol }
      def get_affiliations(node = nil)
        iq = basic_pubsub_query(:get)
        affiliations = iq.pubsub.add(REXML::Element.new('affiliations'))
        affiliations.attributes['node'] = node
        res = nil
        @stream.send_with_id(iq) { |reply|
          if reply.pubsub.first_element('affiliations')
            res = {}
            reply.pubsub.first_element('affiliations').each_element('affiliation') do |affiliation|
              # TODO: This should be handled by an affiliation element class
              aff = case affiliation.attributes['affiliation']
                      when 'owner' then :owner
                      when 'publisher' then :publisher
                      when 'none' then :none
                      when 'outcast' then :outcast
                      else nil
                    end
              res[affiliation.attributes['node']] = aff
            end
          end
          true
        }
        res
      end

      ##
      # shows all subscriptions on the given node
      # node:: [String]
      # return:: [Array] of [Jabber::Pubsub::Subscription]
      def get_subscriptions_from(node)
        iq = basic_pubsub_query(:get)
        entities = iq.pubsub.add(REXML::Element.new('subscriptions'))
        entities.attributes['node'] = node
        res = nil
        @stream.send_with_id(iq) { |reply|
          if reply.pubsub.first_element('subscriptions')
            res = []
            if reply.pubsub.first_element('subscriptions').attributes['node'] == node
              reply.pubsub.first_element('subscriptions').each_element('subscription') { |subscription|
              res << PubSub::Subscription.import(subscription)
              }
            end
          end
          true
        }
        res
      end

      ##
      # shows all jids of subscribers of a node
      # node:: [String]
      # return:: [Array] of [String]
      def get_subscribers_from(node)
        res = []
        get_subscriptions_from(node).each { |sub|
          res << sub.jid
        }
        res
      end


      ##
      # get options from a subscription
      # node:: [String]
      # jid:: [Jabber::JID] or [String]
      # subid:: [String] or nil
      # return:: [Jabber::PubSub::OwnerConfigure]
      def get_options_from(node, jid, subid = nil)
        iq = basic_pubsub_query(:get)
        iq.pubsub.add(Jabber::PubSub::SubscriptionConfig.new(node, jid.kind_of?(String) ? Jabber::JID.new(jid).strip: jid.strip, subid))
        ret = nil
        @stream.send_with_id(iq) do |reply|
          ret = reply.pubsub.first_element('options')
        end
        ret
      end

      ##
      # set options for a subscription
      # node:: [String]
      # jid:: [Jabber::JID] or [String]
      # options:: [Jabber::PubSub::SubscriptionConfig} specifying configuration options
      # subid:: [String] or nil
      # return:: true
      def set_options_for(node, jid, options, subid = nil)
        iq = basic_pubsub_query(:set)
        iq.pubsub.add(Jabber::PubSub::SubscriptionConfig.new(node, jid.kind_of?(String) ? Jabber::JID.new(jid).strip: jid.strip, options, subid))
        ret = false
        @stream.send_with_id(iq) do  |reply|
          ret = ( reply.type == :result )
        end

        ret
      end

      ##
      # String representation
      # result:: [String] The PubSub service's JID
      def to_s
        @pubsubjid.to_s
      end

      ##
      # Register callbacks for incoming events
      # (i.e. Message stanzas containing) PubSub notifications
      def add_event_callback(prio = 200, ref = nil, &block)
        @event_cbs.add(prio, ref, block)
      end

      private

      ##
      # creates a basic pubsub iq
      # basic_pubsub_query(type)
      # type:: [Symbol]
      def basic_pubsub_query(type,ownerusecase = false)
        iq = Jabber::Iq.new(type,@pubsubjid)
        if ownerusecase
          iq.add(IqPubSubOwner.new)
        else
          iq.add(IqPubSub.new)
        end
        iq.from = @stream.jid #.strip
        iq
      end

      ##
      # handling incoming events
      # handle_message(message)
      # message:: [Jabber::Message]
      def handle_message(message)
        if message.from == @pubsubjid and message.first_element('event').kind_of?(Jabber::PubSub::Event)
          event = message.first_element('event')
          @event_cbs.process(event)
        end
      end
    end
  end
end