Class: UCEngine

Inherits:
Object
  • Object
show all
Defined in:
lib/ucengine.rb,
lib/ucengine/version.rb

Overview

This class is the main and only class in ucengine.rb, it handles connections and request to the U.C.Engine server.

uce = UCEngine.new("localhost", 4567)
uce.connect("[email protected]", :credential => 'pwd') do |uce|
        uce.subscribe("", :type => 'chat.message.new', :search => 'HTML5') do |event|
               uce.publish(:location => event['location'],
                           :from => 'bot',
                           :type => 'chat.message.new',
                           :metadata => {"text" => "Hey, you were talking about HTML5"})
        end
end

Constant Summary collapse

API_ROOT =

HTTP API conf.

'/api'
API_VERSION =
'0.5'
VERSION =
'0.5.3'
@@logger =
nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, level = Logger::UNKNOWN) ⇒ UCEngine

Create a new U.C.Engine object. ‘host’ is the hostname of the U.C.Engine server and ‘port’ is to TCP port to connect to. Note that this method doesn’t create a new connection, see the #connect method. An optional parameter ‘level’ can be used to set the logging level (default: Logger::UNKNOWN).



70
71
72
73
74
75
76
77
78
# File 'lib/ucengine.rb', line 70

def initialize(host, port, level = Logger::UNKNOWN)
  @host = host
  @port = port
  @http = Net::HTTP.new(host, port)
  @threads = []
  @logger = @@logger || Logger.new($stderr)
  @logger.level = level
  debug "Initialisation complete for #{host}:#{port}."
end

Instance Attribute Details

#connectedObject (readonly)

Returns the value of attribute connected.



36
37
38
# File 'lib/ucengine.rb', line 36

def connected
  @connected
end

#sidObject (readonly)

Returns the value of attribute sid.



36
37
38
# File 'lib/ucengine.rb', line 36

def sid
  @sid
end

#uidObject (readonly)

Returns the value of attribute uid.



36
37
38
# File 'lib/ucengine.rb', line 36

def uid
  @uid
end

Class Method Details

.load_config(path = 'config.yaml') ⇒ Object

Load configuration file (default: config.yaml). The returned configuration is a Hash, as returned by YAML.load_file().



42
43
44
# File 'lib/ucengine.rb', line 42

def self.load_config(path = 'config.yaml')
  YAML.load_file(path)
end

.logger=(logger) ⇒ Object

Set the default logger.



62
63
64
# File 'lib/ucengine.rb', line 62

def self.logger=(logger)
  @@logger = logger
end

.run(name, options = {}, &proc) ⇒ Object

Run the ucengine server with all the options from the ‘daemons’ gem. This function is not mandatory and it is possible to run a U.C.Engine client without having to run it in background. The ‘name’ parameter is the name you want to give to your brick.

UCEngine.run('test') do
        UCEngine.new(...)
        ...
end


57
58
59
# File 'lib/ucengine.rb', line 57

def self.run(name, options = {}, &proc)
  Daemons.run_proc(name, options, &proc)
end

Instance Method Details

#connect(name, params) {|_self| ... } ⇒ Object

Connect to the U.C.Engine server with the User Name ‘name’ and the its credential.

uce = UCEngine.new("localhost", 4567)
uce.connect("bibi", :credential => 'abcd') do |uce|
        ... your code goes here
end

Yields:

  • (_self)

Yield Parameters:

  • _self (UCEngine)

    the object that the method was called on



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/ucengine.rb', line 93

def connect(name, params)
  begin
    response = post("/presence/", {:name => name, :credential => params[:credential]})
    @connected = true
    @sid = response['result']['sid']
    @uid = response['result']['uid']
    debug "Authentification complete for #{@uid}/#{@sid}."
  rescue RestClient::Request::Unauthorized
    debug "Authentification error for #{name}."
    @connected = false
  end
  yield self if block_given?
  @threads.each do |thread|
    begin
      thread.join
    rescue => error
      warn "Thread aborted: #{error}"
    end
  end
end

#connected?Boolean

Return true if a connection to U.C.Engine has been established, return false otherwise.

Returns:

  • (Boolean)


81
82
83
# File 'lib/ucengine.rb', line 81

def connected?
  @connected
end

#delete(path, params = {}) ⇒ Object

Handle DELETE requests



296
297
298
299
# File 'lib/ucengine.rb', line 296

def delete(path, params = {})
  params['_method'] = 'DELETE'
  post path, params
end

#download(location, id) ⇒ Object

Download a file from UCEngine. The location parameter is where the file sits. The ‘id’ parameters is the file idenfication number

uce.download("demo_meeting", "file_43243243253253.pdf")


237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/ucengine.rb', line 237

def download(location, id)
  Net::HTTP.start @host, @port do |http|
    params = Hash.new
    params[:uid] = @uid if @uid
    params[:sid] = @sid if @sid
    url = URI.escape("http://#{@host}:#{@port}#{API_ROOT}/#{API_VERSION}/file/#{location}/#{id}")

    debug "Download: #{url}"
    result = RestClient.get(url, {:params => params})
    debug 'Download complete'
    return result
  end
end

#get(path, params = {}, http = @http) ⇒ Object

Handle GET requests



268
269
270
271
272
273
274
275
276
# File 'lib/ucengine.rb', line 268

def get(path, params = {}, http = @http)
  params[:uid] = @uid if @uid
  params[:sid] = @sid if @sid
  url = "http://#{@host}:#{@port}#{API_ROOT}/#{API_VERSION}#{path}"
  debug "Request: GET #{url}"
  result = JSON.parse(RestClient.get(url, {:params => params}))
  debug "Result: #{result}"
  return result
end

#post(path, params = {}, http = @http) ⇒ Object

Handle POST requests



279
280
281
282
283
284
285
286
287
# File 'lib/ucengine.rb', line 279

def post(path, params = {}, http = @http)
  params[:uid] = @uid if @uid
  params[:sid] = @sid if @sid
  url = "http://#{@host}:#{@port}#{API_ROOT}/#{API_VERSION}#{path}"
  debug "Request: POST #{url}"
  result = JSON.parse(RestClient.post(url, params, :accept => :json))
  debug "Result: #{result}"
  return result
end

#publish(event) ⇒ Object

Publish an event. Publishing an event require a few mandatories parameters:

:location

As described in the subscribe method: “meeting” publish the event in a specific meeting or “”: publish the event in the server root.

:type

The type of event to send, the format of this type is usually ‘namespace.object.action’, for example: ‘chat.message.new’, ‘twitter.tweet.new’, ‘internal.user.update’

Optional parameters:

:parent

The id of the parent, this parameter is useful to build event hierarchy.

:metadata

A hash of freely defined values to append to the event.

uce.publish(:location => "WebWorkersCamp",
            :type => 'presentation.slide.add'
            :metadata => {:url => 'http://myserver/slides/03.png',
                          :index => 3})


207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/ucengine.rb', line 207

def publish(event)
  debug "Publish to #{event[:location]}, type: #{event[:type]}, parent: #{event[:parent]}, metadata: #{event[:metadata]}"
  params = Hash.new
  params[:type] = event[:type]
  params[:parent] = event[:parent] if event[:parent]
  if event[:metadata]
    event[:metadata].each_key do |key|
      params["metadata[#{key}]"] = event[:metadata][key]
    end
  end
  post "/event/#{event[:location]}", params
end

#put(path, params = {}) ⇒ Object

Handle PUT requests



290
291
292
293
# File 'lib/ucengine.rb', line 290

def put(path, params = {})
  params['_method'] = 'PUT'
  post path, params
end

#roster(name) ⇒ Object

List users in a meeting room.

uce = UCEngine.new("localhost", 4567)
users = uce.roster('demo')


120
121
122
# File 'lib/ucengine.rb', line 120

def roster(name)
  get("/meeting/all/#{name}/roster")['result']
end

#search(location, params = {}) ⇒ Object

Search events. The ‘location’ parameter is where you’re expection the events to come:

  • “meeting”: event from a specific meeting.

  • “”: all events.

The function takes extra parameters: :count => the number of events to return :page => the number of the page to number (starting from 1) :type => the type of event (ex. ‘chat.message.new’, ‘internal.user.add’, etc). :from => the origin of the message, the value is an uid. :parent => the id of the the parent event. :search => list of keywords that match the metadata of the returned events :order => “asc” or “desc” datetimes

# Returns 30 events, starting from the 31th events, containing the keyword "HTML5"
events = uce.search("af83",
                        :type => 'internal.meeting.add',
                        :search => 'HTML5',
                        :count => 30, :page => 2)


143
144
145
146
# File 'lib/ucengine.rb', line 143

def search(location, params = {})
  debug "Search to #{location} with #{params}."
  get("/event/#{location}", params)['result']
end

#subscribe(location, params = {}) ⇒ Object

Subscribe to an event stream. The ‘location’ parameter is where you’re expecting the events to come:

  • “meeting”: events from a specific meeting.

  • “”: all events.

The function takes extra parameters: :type => the type of event (ex. ‘chat.message.new’, ‘internal.user.add’, etc). :from => the origin of the message, the value is an uid. :parent => the id of the the parent event. :search => list of keywords that match the metadata of the returned events

uce.subscribe("af83", :type => 'internal.meeting.add', :search => 'HTML5') do |event|
        puts "A new meeting about HTML5 was created"
end


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

def subscribe(location, params = {})
  debug "Subscribe to #{location} with #{params}."
  @threads << Thread.new do
    Net::HTTP.start @host, @port do |http|
      params[:_async] = 'lp'
      params[:start] = 0 if !params[:start]
      while true
        begin
          events = get("/event/#{location}", params, http)['result']
        rescue RestClient::RequestTimeout
          warn 'Subscribe timeout ... retry'
          retry
        rescue EOFError
          warn 'Subscribe closed ... retry'
          sleep 1
          retry
        rescue => boom
          error boom
          sleep 1
          retry
        end

        next if events == []

        events.each do |event|
          yield event
        end
        params[:start] = events[-1]['datetime'] + 1
      end
    end
  end
end

#timeObject

Return the current timestamp from the server. The timestamp is expressed in milliseconds from Epoch (january 1st 1970). This function can be useful if you need to search for events from now.

uce.time -> 1240394032


226
227
228
229
230
# File 'lib/ucengine.rb', line 226

def time
  time = get("/time", Hash.new)['result'].to_i
  debug "Fecth timestamp from UCEngine: #{time}"
  return time
end

#upload(location, file, metadata = {}) ⇒ Object

Upload a file to UCEngine. The location is where you want the file to be uploaded. The ‘file’ parameter is a File object. This function returns a JSON structure file_id where ‘file_id’ is the identification number of the file.

uce.upload(["demo_meeting"], File.new("/path/file_to_upload.pdf"))


258
259
260
261
262
263
264
265
# File 'lib/ucengine.rb', line 258

def upload(location, file, ={})
  url = "http://#{@host}:#{@port}#{API_ROOT}/#{API_VERSION}/file/#{location}?uid=#{@uid}&sid=#{@sid}"
  debug "Upload: #{file.path} to #{url}"
  result = JSON.parse(RestClient.post(url, { :content => file,
                                             :metadata =>  }))
  debug 'Upload complete'
  return result
end