Class: SelfSDK::MessagingClient

Inherits:
Object
  • Object
show all
Defined in:
lib/messaging.rb

Constant Summary collapse

DEFAULT_DEVICE =
"1"
DEFAULT_AUTO_RECONNECT =
true
PRIORITIES =
{ 
'chat.invite':                 SelfSDK::Messages::PRIORITY_VISIBLE,
'chat.join':                   SelfSDK::Messages::PRIORITY_INVISIBLE,
'chat.message':                SelfSDK::Messages::PRIORITY_VISIBLE,
'chat.message.delete':         SelfSDK::Messages::PRIORITY_INVISIBLE,
'chat.message.delivered':      SelfSDK::Messages::PRIORITY_INVISIBLE,
'chat.message.edit':           SelfSDK::Messages::PRIORITY_INVISIBLE,
'chat.message.read':           SelfSDK::Messages::PRIORITY_INVISIBLE,
'chat.remove':                 SelfSDK::Messages::PRIORITY_INVISIBLE,
'document.sign.req':           SelfSDK::Messages::PRIORITY_VISIBLE,
'identities.authenticate.req': SelfSDK::Messages::PRIORITY_VISIBLE,
'identities.connections.req':  SelfSDK::Messages::PRIORITY_VISIBLE,
'identities.facts.query.req':  SelfSDK::Messages::PRIORITY_VISIBLE,
'identities.facts.issue':      SelfSDK::Messages::PRIORITY_VISIBLE,
'identities.notify':           SelfSDK::Messages::PRIORITY_VISIBLE }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, client, storage_key, storage, options = {}) ⇒ MessagingClient

RestClient initializer

Parameters:

  • url (string)

    self-messaging url

  • opts (Hash)

    a customizable set of options



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
# File 'lib/messaging.rb', line 113

def initialize(url, client, storage_key, storage, options = {})
  @mon = Monitor.new
  @messages = {}
  @acks = {}
  @type_observer = {}
  @uuid_observer = {}
  @jwt = client.jwt
  @client = client
  @ack_timeout = 60 # seconds
  @timeout = 120 # seconds
  @auth_id = SecureRandom.uuid
  @device_id = options.fetch(:device_id, DEFAULT_DEVICE)
  @source = SelfSDK::Sources.new("#{__dir__}/sources.json")
  @storage = storage

  unless options.include? :no_crypto
    @encryption_client = Crypto.new(@client, @device_id, @storage, storage_key)
  end
  @offset = @storage.

  @ws = if options.include? :ws
          options[:ws]
        else
          WebsocketClient.new(url,
                              options.fetch(:auto_reconnect, DEFAULT_AUTO_RECONNECT),
                              -> { authenticate },
                              ->(event) { on_message(event) })
        end
end

Instance Attribute Details

#ack_timeoutObject

Returns the value of attribute ack_timeout.



102
103
104
# File 'lib/messaging.rb', line 102

def ack_timeout
  @ack_timeout
end

#clientObject

Returns the value of attribute client.



102
103
104
# File 'lib/messaging.rb', line 102

def client
  @client
end

#device_idObject

Returns the value of attribute device_id.



102
103
104
# File 'lib/messaging.rb', line 102

def device_id
  @device_id
end

#encryption_clientObject

Returns the value of attribute encryption_client.



102
103
104
# File 'lib/messaging.rb', line 102

def encryption_client
  @encryption_client
end

#jwtObject

Returns the value of attribute jwt.



102
103
104
# File 'lib/messaging.rb', line 102

def jwt
  @jwt
end

#sourceObject

Returns the value of attribute source.



102
103
104
# File 'lib/messaging.rb', line 102

def source
  @source
end

#timeoutObject

Returns the value of attribute timeout.



102
103
104
# File 'lib/messaging.rb', line 102

def timeout
  @timeout
end

#type_observerObject

Returns the value of attribute type_observer.



102
103
104
# File 'lib/messaging.rb', line 102

def type_observer
  @type_observer
end

#uuid_observerObject

Returns the value of attribute uuid_observer.



102
103
104
# File 'lib/messaging.rb', line 102

def uuid_observer
  @uuid_observer
end

Instance Method Details

#clean_observersObject



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/messaging.rb', line 320

def clean_observers
  live = {}
  @uuid_observer.clone.each do |id, msg|
    if msg[:timeout] < SelfSDK::Time.now
      message = SelfSDK::Messages::Base.new(self)
      message.status = "errored"

      @uuid_observer[id][:block].call(message)
      @uuid_observer.delete(id)
    else
      live[id] = msg
    end
  end
  @uuid_observer = live
end

#closeObject



192
193
194
# File 'lib/messaging.rb', line 192

def close
  @ws.close
end

#notify_observer(message) ⇒ Object

Notify the type observer for the given message



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
# File 'lib/messaging.rb', line 337

def notify_observer(message)
  if @uuid_observer.include? message.id
    SelfSDK.logger.debug " - notifying by id"
    observer = @uuid_observer[message.id]
    message.validate!(observer[:original_message]) if observer.include?(:original_message)
    Thread.new do
      @uuid_observer[message.id][:block].call(message)
      @uuid_observer.delete(message.id)
    end
    return
  end

  SelfSDK.logger.debug " - notifying by type"
  SelfSDK.logger.debug " - #{message.typ}"
  SelfSDK.logger.debug " - #{message.payload}"
  SelfSDK.logger.debug " - #{@type_observer.keys.join(',')}"

  # Return if there is no observer setup for this kind of message
  return unless @type_observer.include? message.typ

  SelfSDK.logger.debug " - notifying by type (Y)"
  Thread.new do
    @type_observer[message.typ][:block].call(message)
  end
end

#send_and_wait_for_response(msgs, original) ⇒ Object

Sends a message and waits for the response



248
249
250
251
252
253
254
255
# File 'lib/messaging.rb', line 248

def send_and_wait_for_response(msgs, original)
  SelfSDK.logger.debug "sending/wait for #{msgs.first.id}"
  wait_for msgs.first.id, original do
    msgs.each do |msg|
      send_message msg
    end
  end
end

#send_custom(recipients, request_body) ⇒ Object

Send custom mmessage

Parameters:

  • recipient (string)

    selfID to be requested

  • type (string)

    message type

  • request (hash)

    original message requesing information



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
# File 'lib/messaging.rb', line 207

def send_custom(recipients, request_body)
  # convert argument into an array if is a string
  recipients = [recipients] if recipients.is_a? String

  # send to current identity devices except the current one.
  recipients |= [@jwt.id]

  # build recipients list
  recs = []
  recipients.each do |r|
    @client.devices(r).each do |to_device|
      recs << { id: r, device_id: to_device }
    end
  end

  SelfSDK.logger.debug "sending custom message #{request_body.to_json}"
  current_device = "#{@jwt.id}:#{@device_id}"

  recs.each do |r|
    next if current_device == "#{r[:id]}:#{r[:device_id]}"

    request_body[:sub] = r[:id]
    request_body[:aud] = r[:id] unless request_body.key?(:aud)
    ciphertext = @encryption_client.encrypt(@jwt.prepare(request_body), recs)

    m = SelfMsg::Message.new
    m.id = SecureRandom.uuid
    m.sender = current_device
    m.recipient = "#{r[:id]}:#{r[:device_id]}"
    m.ciphertext = ciphertext
    m.message_type = r[:typ]
    m.priority = select_priority(r[:typ])

    SelfSDK.logger.debug "[#{m.id}] -> to #{m.recipient}"
    send_message m
  end
end

#send_message(msg) ⇒ Object

Send a message through self network



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
# File 'lib/messaging.rb', line 290

def send_message(msg)
  uuid = msg.id
  @mon.synchronize do
    @acks[uuid] = {
      waiting_cond: @mon.new_cond,
      waiting: true,
      timeout: SelfSDK::Time.now + @ack_timeout,
    }
  end
  @ws.send msg
  SelfSDK.logger.debug "waiting for acknowledgement #{uuid}"
  @mon.synchronize do
    @acks[uuid][:waiting_cond].wait_while do
      @acks[uuid][:waiting]
    end
  end

  # response has timed out
  if @acks[uuid][:timed_out]
    SelfSDK.logger.debug "acknowledgement response timed out re-sending message #{uuid}"
    return send_message(msg)
  end

  SelfSDK.logger.debug "acknowledged #{uuid}"
  true
ensure
  @acks.delete(uuid)
  false
end

#session?(identifier, device) ⇒ Boolean

Checks if the session with a specified identity / device is already created.

Returns:

  • (Boolean)


197
198
199
200
# File 'lib/messaging.rb', line 197

def session?(identifier, device)
  path = @encryption_client.session_path(identifier, device)
  File.file?(path)
end

#set_observer(original, options = {}, &block) ⇒ Object



363
364
365
366
# File 'lib/messaging.rb', line 363

def set_observer(original, options = {}, &block)
  request_timeout = options.fetch(:timeout, @timeout)
  @uuid_observer[original.id] = { original_message: original, block: block, timeout: SelfSDK::Time.now + request_timeout }
end

#startObject

Starts the underlying websocket connection.



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
# File 'lib/messaging.rb', line 144

def start
  SelfSDK.logger.debug "starting"
  auth_id = @auth_id.dup

  @mon.synchronize do
    @acks[auth_id] = { waiting_cond: @mon.new_cond,
                       waiting: true,
                       timeout: SelfSDK::Time.now + @ack_timeout }
  end

  Thread.new do
    EM.run start_connection
  end

  Thread.new do
    loop do
      sleep 10
      clean_timeouts
      @ws.ping
    end
  end

  @mon.synchronize do
    @acks[auth_id][:waiting_cond].wait_while { @acks[auth_id][:waiting] }
    @acks.delete(auth_id)
  end

  return unless @acks.include? auth_id

  # In case this does not succeed start the process again.
  if @acks[auth_id][:waiting]
    close
    start_connection
  end
  @acks.delete(auth_id)
end

#stopObject

Stops the underlying websocket connection.



182
183
184
185
186
187
188
189
190
# File 'lib/messaging.rb', line 182

def stop
  @acks.each do |k, _v|
    mark_as_acknowledged(k)
  end
  @messages.each do |k, _v|
    mark_as_acknowledged(k)
    mark_as_arrived(k)
  end
end

#subscribe(type, &block) ⇒ Object



368
369
370
371
372
# File 'lib/messaging.rb', line 368

def subscribe(type, &block)
  type = @source.message_type(type) if type.is_a? Symbol
  SelfSDK.logger.debug "Subscribing to messages by type: #{type}"
  @type_observer[type] = { block: block }
end

#wait_for(uuid, msg = nil) ⇒ Object

Executes the given block and waits for the message id specified on the uuid.



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
# File 'lib/messaging.rb', line 261

def wait_for(uuid, msg = nil)
  SelfSDK.logger.debug "sending #{uuid}"
  @mon.synchronize do
    @messages[uuid] = {
      waiting_cond: @mon.new_cond,
      waiting: true,
      timeout: SelfSDK::Time.now + @timeout,
      original_message: msg,
    }
  end

  yield

  SelfSDK.logger.debug "waiting for client to respond #{uuid}"
  @mon.synchronize do
    @messages[uuid][:waiting_cond].wait_while do
      @messages[uuid][:waiting]
    end
  end

  SelfSDK.logger.debug "response received for #{uuid}"
  @messages[uuid][:response]
ensure
  @messages.delete(uuid)
end