Class: WorkstreamerApi::Api

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

Overview

This is the main workstreamer class. The key and secret need to have been generated on the workstreamer site. If the user doesn’t have an AccessToken, this class can be used to generate a RequestToken.

Instance Method Summary collapse

Constructor Details

#initialize(key, secret, site = "http://localhost:3000", user_token = nil, user_secret = nil) ⇒ Api

Create a new workstreamer api instance.

key - the ClientApplication key generated for your application by
      workstreamer.com at http://alpha.workstreamer.com/oauth_clients
secret - that matches the key
site - normally "alpha.workstreamer.com"  TODO This needs to be domain aware

This is all that is needed to create a RequestToken for a user who hasn’t given permission. (See request_token for more info.) If the user has already granted access, be sure to pass in

user_token - the AccessToken back from the oath provider
user_secret - the secret.

See example/app/controllers/workstreamer_controller.callback for an example.



40
41
42
43
44
45
46
# File 'lib/workstreamer_api.rb', line 40

def initialize( key, secret, site = "http://localhost:3000", user_token = nil, user_secret = nil )
  @key = key
  @secret = secret
  @site = site
  @user_token = user_token
  @user_secret = user_secret
end

Instance Method Details

#access_tokenObject

This returns a (cached) OAuth::AccessToken which can, in turn, be used to make remote HTTP calls to workstreamer. All of the API wrapper calls use this method for the actual network transportation.



77
78
79
# File 'lib/workstreamer_api.rb', line 77

def access_token
  @access_token ||= OAuth::AccessToken.new( consumer, @user_token, @user_secret )
end

#consumerObject

Returns a (cached) OAuth::Consumer



53
54
55
# File 'lib/workstreamer_api.rb', line 53

def consumer
  @consumer ||= OAuth::Consumer.new @key, @secret, { :site => @site }
end

#convert_node_to_hash(xml) ⇒ Object

Simple method to turn a Nokogiri XML object into a ruby hash.



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/workstreamer_api.rb', line 149

def convert_node_to_hash( xml )
  ret = {}

  xml.children.each do |child|
    if child.is_a? Nokogiri::XML::Element
      subchildren = child.children
      if subchildren.size == 1
        ret[child.name] = child.inner_html
      else
        ret[child.name] = convert_node_to_hash( child )
      end
    end
  end

  ret
end

#create_comment(comment_text, parent_id) ⇒ Object

Create a comment on an existing content.

comment_text - the comment text
parent_id - the id of the MasterContent that you are commenting on.  This
            is NOT the id of the content itself, but the enclosing
            MasterContent


345
346
347
# File 'lib/workstreamer_api.rb', line 345

def create_comment( comment_text, parent_id )
  create_content({:comment => comment_text, :reply_to => parent_id})
end

#create_content(parameters) ⇒ Object

Generate create_content method, which all other content creating methods – except for FeedItems – delegate to. Depending upon the parameters, content of a different type is created.

See workstreamer.pbworks.com/Content-API for details on the parameters to pass in.



206
207
208
209
210
211
212
213
214
# File 'lib/workstreamer_api.rb', line 206

def create_content( parameters )
  xml = post( "/post_apis/create", parameters, false )

  return false if xml.nil?

  node = xml.at( "result" )
  return false if node.nil?
  node.content == "SUCCESS"
end

#create_event(title, start_date = Date.today, end_date = nil) ⇒ Object

Creates an event

title - Event title
start_date - Defaults to today
end_date - when the event ends

TODO Add project and permissions.



315
316
317
318
319
# File 'lib/workstreamer_api.rb', line 315

def create_event( title, start_date = Date.today, end_date = nil )
  params = {:title => title, :start_date => start_date }
  params[:end_date] = end_date if end_date
  create_content( params )
end

#create_task(title, assigned_to, content, project_id = nil) ⇒ Object

Creates a task

title - the Task title
assigned_to - The user name or user id of who the task is assigned to
content - the body of the task
project_id - the optional project


329
330
331
332
333
334
335
# File 'lib/workstreamer_api.rb', line 329

def create_task( title, assigned_to, content, project_id = nil )
  unless assigned_to =~ /^\d+$/
    assigned_to = lookup_user_ids( assigned_to ).first
  end

  create_content({:title => title, :assigned_to => assigned_to, :content => content, :project_id => project_id } )
end

#get(url, json = true) ⇒ Object

OAuth-orized HTTP GET to workstreamer. Passed in a URL it will return a parsed object. If JSON is requested, it will return a Hash. Otherwise, it will return a nogokiri XML object. (convert_node_to_hash will transform a nogokiri XML object to a Hash but won’t preserve the XML attributes.)



87
88
89
90
# File 'lib/workstreamer_api.rb', line 87

def get( url, json = true )
  ret = access_token.get( url )
  parse( ret, json )
end

#get_content(id) ⇒ Object

Return everything we know about a content.

id - The content id.


354
355
356
357
358
359
360
# File 'lib/workstreamer_api.rb', line 354

def get_content( id )
  url = "/post_apis/show?id=#{id}"

  xml = get url, false

  convert_node_to_hash xml
end

#lookup_project(project) ⇒ Object

Get project title and membership.

project - Project name or project id


268
269
270
# File 'lib/workstreamer_api.rb', line 268

def lookup_project( project )
  get "/projects/view?format=json&name=#{URI::escape project}"
end

#lookup_user_ids(users) ⇒ Object

Lookup multuple users but return an array of user_ids



259
260
261
# File 'lib/workstreamer_api.rb', line 259

def lookup_user_ids( users )
  lookup_users( users ).collect { |x| x[1]['id'] }
end

#lookup_users(users) ⇒ Object

Lookup multiple users at the same time. Returns an array of the same type as user_info returns.

users - list of users


245
246
247
248
249
250
251
252
253
254
# File 'lib/workstreamer_api.rb', line 245

def lookup_users( users )
  users = users.gsub( /([\s,]+)/, " " ).split( / / )

  ret = {}
  users.each do ||
    ret[] = (  )
  end

  ret
end

#parse(ret, json = true) ⇒ Object

Intepret a server response. Raise WsApi::Unauthorized or WsApi::HTTPSuccess if there was an error, otherwise process the body through JSON.parse or Nokogiri::XML.

TODO Should probably do this on the returned content-type rather than parameter



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/workstreamer_api.rb', line 110

def parse( ret, json = true )
  case ret
  when Net::HTTPSuccess
    # logger.debug ret.body
    if json
      return JSON.parse(ret.body)
    else
      return Nokogiri::XML( ret.body )
    end
  when Net::HTTPUnauthorized
    raise Unauthorized
  when Net::HTTPForbidden
    raise Forbidden
  else
    puts ret
    puts ret.body
    raise Unknown
  end
end

#post(url, parameters, json = true) ⇒ Object

OAuth-orized HTTP POST to workstreamer. Passed in a URL and a hash or parameters it will return a parsed object. If JSON is requested, it will return a Hash. Otherwise, it will return a nogokiri XML object. (convert_node_to_hash will transform a nogokiri XML object to a Hash but won’t preserve the XML attributes.)



99
100
101
102
# File 'lib/workstreamer_api.rb', line 99

def post( url, parameters, json = true )
  ret = access_token.post url, parameters
  parse( ret, json )
end

#post_direct_message(user_name, message) ⇒ Object

Create a direct message from the current user to user_name.

user_name - User to send the message to
message - The message


235
236
237
# File 'lib/workstreamer_api.rb', line 235

def post_direct_message( user_name, message )
  create_content( {:content => "d @#{user_name} #{message}"} )
end

#post_feed_item(params) ⇒ Object

Create a feed item. Params are

:remote_id - The remote id for this feed item (uninterpreted)
:created_at - The created_at/published date, defaults to now
:title - Title of the item
:summary - The body of the item shown when expanded
:url - The url that represents the "original" item


371
372
373
# File 'lib/workstreamer_api.rb', line 371

def post_feed_item( params )
  post "/feed/post_item", params, false
end

#post_message(title, body, options) ⇒ Object

Post a message with optional comma seperated tags.

title - the title of the message
body - the body of the message

Options include:

:tags => "tag1,tag2,tag3"

:recipient_ids => "user_id1,user_id2,user_id3" or [user1_id, user2_id, user3_id]
    or
:recipients => "tom,dick,harry" or ["tom", "dick", "harry"]

:project => "project_name"
    or
:project_id => "project_id"


290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/workstreamer_api.rb', line 290

def post_message( title, body, options )
  params = {:title => title, :content => body }
  set_options( params, :tags, options )
  options[:recipient_ids] = options[:recipient_ids].join( "," ) if options[:recipient_ids]
  options[:recipient_ids] = lookup_user_ids( options[:recipients] ) if options[:recipients]
  options[:recipients] = options[:recipient_ids]
  set_options( params, :recipients, options )

  options[:project_id] = lookup_project( options[:project] )['id'] if options[:project]

  set_options( params, :project_id, options )

  pp params

  create_content( params )
end

#post_status_update(message) ⇒ Object

Create a status update. The content is parsed on the worksteamer server, so if you use @user or #tag the status update with be directed to a user and/or tagged.

message - The status update.

TODO: Add project



225
226
227
# File 'lib/workstreamer_api.rb', line 225

def post_status_update( message )
  create_content( {:content => message } )
end

#request_tokenObject

This generates a request token for your application. Once a RequestToken is generated you then redirect the browser to the authorize_url. e.g.

request_token = workstreamer.request_token

session[:request_token] = request_token.token
session[:request_token_secret] = request_token.secret

redirect_to request_token.authorize_url


68
69
70
# File 'lib/workstreamer_api.rb', line 68

def request_token
  @request_token ||= consumer.get_request_token
end

#set_options(params, key, options) ⇒ Object

Used to build the parameter options; will only create an entry if the options is set, and will collapse arrays to comma seperated.

params - hash to set (destination)
key - the key to move over
options - hash that we're getting the data from (origin)


138
139
140
141
142
143
144
# File 'lib/workstreamer_api.rb', line 138

def set_options( params, key, options )
  if options[key].is_a? Array
    params[key] = options[key].join( "," )
  elsif options[key]
    params[key] = options[key]
  end
end

#streamObject

Returns the user’s current stream.

TODO Stream filters TODO Unread counts



186
187
188
189
190
191
192
193
194
195
196
# File 'lib/workstreamer_api.rb', line 186

def stream
  xml = get( "/post_apis/index?format=xml", false )

  ret = []

  (xml/'master-content').each do |mc|
    ret << convert_node_to_hash( mc )
  end

  ret
end

#user_info(login = nil) ⇒ Object

Looks up information on a specific user. If login is null, looks up the current/authorized user.

login - workstreamer login or user id


174
175
176
177
178
# File 'lib/workstreamer_api.rb', line 174

def (  = nil )
  url = "/user/info?format=json" 
  url += "&login=#{}" if 
  get url
end