Class: UCEngine

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

Overview

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

uce = UCEngine.new("localhost", 4567)
uce.connect("[email protected]", :password => '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 =
"/api"
API_VERSION =
"0.3"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, debug = UCEngine::QUIET) ⇒ UCEngine

Create a new UCEngine object. ‘host’ is the hostname of the UCEngine 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.



74
75
76
77
78
79
80
81
# File 'lib/ucengine.rb', line 74

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

Instance Attribute Details

#connectedObject (readonly)

Returns the value of attribute connected.



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

def connected
  @connected
end

#sidObject (readonly)

Returns the value of attribute sid.



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

def sid
  @sid
end

#uidObject (readonly)

Returns the value of attribute uid.



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

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



50
51
52
# File 'lib/ucengine.rb', line 50

def UCEngine.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 UCEngine 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


65
66
67
# File 'lib/ucengine.rb', line 65

def UCEngine.run(name, &proc)
  Daemons.run_proc(name, &proc)
end

Instance Method Details

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

Connect to the UCEngine server with the User ID ‘uid’ 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



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

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

#connected?Boolean

Returns:

  • (Boolean)


83
84
85
# File 'lib/ucengine.rb', line 83

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


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

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(UCEngine::DEBUG, "Download: #{url}")
    result = RestClient.get(url, {:params => params})
    debug(UCEngine::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’

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


174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/ucengine.rb', line 174

def publish(event)
  debug(UCEngine::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

#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


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

def subscribe(location, params = {})
  debug(UCEngine::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
          debug(UCEngine::WARNING, "Subscribe timeout ... retry")
          retry
        rescue EOFError
          debug(UCEngine::WARNING, "Subscribe closed ... retry")
          sleep 1
          retry
        rescue => error
          debug(UCEngine::ERROR, error)
          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


193
194
195
196
197
# File 'lib/ucengine.rb', line 193

def time
  time = get("/time", Hash.new)['result'].to_i
  debug(UCEngine::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"))


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

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