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

DEBUG =

Print every request and everything above.

0
WARNING =

Print everything that seems fishy.

1
ERROR =

Print regular errors, usually HTTP errors.

2
CRITICAL =

Only print critical errors (bad hostname or port, etc).

3
QUIET =

Don’t print anything (default).

4
API_ROOT =

HTTP API conf.

'/api'
API_VERSION =
'0.5'
VERSION =
'0.5.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, debug = UCEngine::QUIET) ⇒ 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 additional ‘debug’ parameter set the debug level of the library, all the debug information are written in the error output.



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

def initialize(host, port, debug = UCEngine::QUIET)
  @host = host
  @port = port
  @http = Net::HTTP.new(host, port)
  @threads = []
  @debug = debug
  debug "Initialisation complete for #{host}:#{port}."
end

Instance Attribute Details

#connectedObject (readonly)

Returns the value of attribute connected.



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

def connected
  @connected
end

#sidObject (readonly)

Returns the value of attribute sid.



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

def sid
  @sid
end

#uidObject (readonly)

Returns the value of attribute uid.



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

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().



45
46
47
# File 'lib/ucengine.rb', line 45

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

.run(name, &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


60
61
62
# File 'lib/ucengine.rb', line 60

def self.run(name, &proc)
  Daemons.run_proc(name, &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



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

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)


79
80
81
# File 'lib/ucengine.rb', line 79

def connected?
  @connected
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")


225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/ucengine.rb', line 225

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

#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})


195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/ucengine.rb', line 195

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

#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)


131
132
133
134
# File 'lib/ucengine.rb', line 131

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


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

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


214
215
216
217
218
# File 'lib/ucengine.rb', line 214

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

#upload(location, file) ⇒ 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"))


246
247
248
249
250
251
252
# File 'lib/ucengine.rb', line 246

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, {:upload => file}))
  debug 'Upload complete'
  return result
end