Class: Facebooker::User

Inherits:
Object
  • Object
show all
Includes:
Model
Defined in:
lib/facebooker/models/user.rb,
lib/facebooker/adapters/bebo_adapter.rb

Overview

Holds attributes and behavior for a Facebook User

Defined Under Namespace

Classes: Status

Constant Summary collapse

FIELDS =
[:status, :political, :pic_small, :name, :quotes, :is_app_user, :tv, :profile_update_time, :meeting_sex, :hs_info, :timezone, :relationship_status, :hometown_location, :about_me, :wall_count, :significant_other_id, :pic_big, :music, :work_history, :sex, :religion, :notes_count, :activities, :pic_square, :movies, :has_added_app, :education_history, :birthday, :birthday_date, :first_name, :meeting_for, :last_name, :interests, :current_location, :pic, :books, :affiliations, :locale, :profile_url, :proxied_email, :email_hashes, :allowed_restrictions, :pic_with_logo, :pic_big_with_logo, :pic_small_with_logo, :pic_square_with_logo]
STANDARD_FIELDS =
[:uid, :first_name, :last_name, :name, :timezone, :birthday, :sex, :affiliations, :locale, :profile_url, :proxied_email]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Model

#anon=, included, #populate_from_hash!, #populated?, #session

Constructor Details

#initialize(*args) ⇒ User

Can pass in these two forms: id, session, (optional) attribute_hash attribute_hash



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/facebooker/models/user.rb', line 31

def initialize(*args)
  @friends            = nil
  @current_location   = nil
  @pic                = nil
  @hometown_location  = nil
  @populated          = false
  @session            = nil
  @id                 = nil
  if (args.first.kind_of?(String) || args.first.kind_of?(Integer)) && args.size==1
    self.uid = args.shift
    @session = Session.current
  elsif (args.first.kind_of?(String) || args.first.kind_of?(Integer)) && args[1].kind_of?(Session)
    self.uid = args.shift
    @session = args.shift
  end
  if args.last.kind_of?(Hash)
    populate_from_hash!(args.pop)
  end
end

Instance Attribute Details

#affiliationsObject (readonly)

Returns the value of attribute affiliations.



18
19
20
# File 'lib/facebooker/models/user.rb', line 18

def affiliations
  @affiliations
end

Class Method Details

.cast_to_facebook_id(object) ⇒ Object



508
509
510
511
512
513
514
# File 'lib/facebooker/models/user.rb', line 508

def self.cast_to_facebook_id(object)
  if object.respond_to?(:facebook_id)
    object.facebook_id
  else
    object
  end
end

.hash_email(email) ⇒ Object



501
502
503
504
505
506
# File 'lib/facebooker/models/user.rb', line 501

def self.hash_email(email)
  email = email.downcase.strip
  crc=Zlib.crc32(email)
  md5=Digest::MD5.hexdigest(email)
  "#{crc}_#{md5}"
end

.register(users) ⇒ Object

register a user with Facebook users should be a hast with at least an :email field you can optionally provide an :account_id field as well



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/facebooker/models/user.rb', line 442

def self.register(users)
  user_map={}
  users=users.map do |h|
    returning h.dup do |d|
      if email=d.delete(:email)
        hash = hash_email(email)
        user_map[hash]=h
        d[:email_hash]=hash
      end
    end
  end
  Facebooker::Session.create.post("facebook.connect.registerUsers",:accounts=>users.to_json) do |ret|
    ret.each do |hash|
      user_map.delete(hash)
    end
    unless user_map.empty?
      e=Facebooker::Session::UserRegistrationFailed.new
      e.failed_users = user_map.values
      raise e
    end
    ret
  end
end

.standard_fields(fields = []) ⇒ Object



520
521
522
# File 'lib/facebooker/models/user.rb', line 520

def self.standard_fields(fields = [])
  valid_fields(fields,STANDARD_FIELDS)
end

.unregister(email_hashes) ⇒ Object

Unregister an array of email hashes



473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/facebooker/models/user.rb', line 473

def self.unregister(email_hashes)
  Facebooker::Session.create.post("facebook.connect.unregisterUsers",:email_hashes=>email_hashes.to_json) do |ret|
    ret.each do |hash|
      email_hashes.delete(hash)
    end
    unless email_hashes.empty?
      e=Facebooker::Session::UserUnRegistrationFailed.new
      e.failed_users = email_hashes
      raise e
    end
    ret
  end      
end

.unregister_emails(emails) ⇒ Object

unregister an array of email addresses



488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/facebooker/models/user.rb', line 488

def self.unregister_emails(emails)
  emails_hash  = {}
  emails.each {|e| emails_hash[hash_email(e)] = e}
  begin 
    unregister(emails_hash.keys).collect {|r| emails_hash[r]}
  rescue
    # re-raise with emails instead of hashes.
    e = Facebooker::Session::UserUnRegistrationFailed.new
    e.failed_users = $!.failed_users.collect { |f| emails_hash[f] }
    raise e
  end
end

.user_fields(fields = []) ⇒ Object



516
517
518
# File 'lib/facebooker/models/user.rb', line 516

def self.user_fields(fields = [])
  valid_fields(fields)
end

Instance Method Details

#==(other_user) ⇒ Object

Two Facebooker::User objects should be considered equal if their Facebook ids are equal



433
434
435
# File 'lib/facebooker/models/user.rb', line 433

def ==(other_user)
  other_user.is_a?(User) && id == other_user.id
end

#albumsObject



238
239
240
241
242
243
244
# File 'lib/facebooker/models/user.rb', line 238

def albums
  @albums ||= session.post('facebook.photos.getAlbums', :uid => self.id) do |response|
    response.map do |hash|
      Album.from_hash(hash)
    end
  end
end

#cast_to_friend_list_id(flid) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/facebooker/models/user.rb', line 91

def cast_to_friend_list_id(flid)
  case flid
  when String
    list=friend_lists.detect {|f| f.name==flid}
    raise Facebooker::Session::InvalidFriendList unless list
    list.flid
  when FriendList
    flid.flid
  else
    flid
  end
end

#comment_on(post_id, comment) ⇒ Object

Publish a comment on a post

See: wiki.developers.facebook.com/index.php/Stream.addComment

post_id the post_id for the post that is being commented on comment the text of the comment



168
169
170
# File 'lib/facebooker/models/user.rb', line 168

def comment_on(post_id, comment)
  @session.post('facebook.stream.addComment', {:post_id=>post_id, :comment=>comment})
end

#create_album(params) ⇒ Object



246
247
248
# File 'lib/facebooker/models/user.rb', line 246

def create_album(params)
  @album = session.post('facebook.photos.createAlbum', params) {|response| Album.from_hash(response)}
end

#events(params = {}) ⇒ Object

Returns a user’s events, params correspond to API call parameters (except UID): wiki.developers.facebook.com/index.php/Events.get E.g:

@user.events(:start_time => Time.now, :end_time => 1.month.from_now)
# => Returns events betwen now and a month from now


59
60
61
62
63
64
65
66
67
68
# File 'lib/facebooker/models/user.rb', line 59

def events(params={})
  @events ||= {}
  [:start_time,:end_time].compact.each do |key|
    params[key] = params[key].to_i
  end
#      puts @events[params.to_s].nil?
  @events[params.to_s] ||= @session.post('facebook.events.get', {:uid => self.id}.merge(params)).map do |event|
    Event.from_hash(event)
  end
end

#friend_idsObject



119
120
121
122
# File 'lib/facebooker/models/user.rb', line 119

def friend_ids
  options = {:uid => self.id}
  @session.post('facebook.friends.get', options, false)
end

#friend_ids_with_this_appObject



209
210
211
# File 'lib/facebooker/models/user.rb', line 209

def friend_ids_with_this_app
  @friend_ids_with_this_app ||= session.post('facebook.friends.getAppUsers')
end

#friend_listsObject



173
174
175
176
177
178
179
# File 'lib/facebooker/models/user.rb', line 173

def friend_lists
  @friend_lists ||= @session.post('facebook.friends.getLists').map do |hash|
    friend_list = FriendList.from_hash(hash)                               
    friend_list.session = session                                          
    friend_list                                                            
  end                                                                      
end

#friends(flid = nil) ⇒ Object

Retrieve friends



105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/facebooker/models/user.rb', line 105

def friends(flid = nil)
 	@friends_hash ||= {}
 	flid=cast_to_friend_list_id(flid)
  
 	#use __blank instead of nil so that this is cached
 	cache_key = flid||"__blank"
 	options = {:uid=>self.id}
 	options[:flid] = flid unless flid.nil?
 	@friends_hash[cache_key] ||= @session.post('facebook.friends.get', options,false).map do |uid|
      User.new(uid, @session)
  end
  @friends_hash[cache_key]
end

#friends!(*fields) ⇒ Object

Retrieve friends with user info populated Subsequent calls will be retrieved from memory. Optional: list of fields to retrieve as symbols



184
185
186
187
188
# File 'lib/facebooker/models/user.rb', line 184

def friends!(*fields)
  @friends ||= session.post('facebook.users.getInfo', :fields => collect(fields), :uids => friends.map{|f| f.id}.join(',')).map do |hash|  
    User.new(hash['uid'], session, hash)
  end
end

#friends=(list_of_friends, flid = nil) ⇒ Object

Set the list of friends, given an array of User objects. If the list has been retrieved previously, will not set



82
83
84
85
86
87
88
89
# File 'lib/facebooker/models/user.rb', line 82

def friends=(list_of_friends,flid=nil)
  @friends_hash ||= {}
 	flid=cast_to_friend_list_id(flid)
 	#use __blank instead of nil so that this is cached
 	cache_key = flid||"__blank"
 	
  @friends_hash[cache_key] ||= list_of_friends
end

#friends_with?(user_or_id) ⇒ Boolean

Returns:

  • (Boolean)


199
200
201
# File 'lib/facebooker/models/user.rb', line 199

def friends_with?(user_or_id)
  friends.map{|f| f.to_i}.include?(user_or_id.to_i)  
end

#friends_with_this_appObject



203
204
205
206
207
# File 'lib/facebooker/models/user.rb', line 203

def friends_with_this_app
  @friends_with_this_app ||= friend_ids_with_this_app.map do |uid|
    User.new(uid, session)
  end
end

#get_cookies(name = nil) ⇒ Object

Convenience method to get cookies for the current user



417
418
419
# File 'lib/facebooker/models/user.rb', line 417

def get_cookies(name=nil)
  session.data.get_cookies(id, name)
end

#get_profile_infoObject



362
363
364
# File 'lib/facebooker/models/user.rb', line 362

def get_profile_info
  session.post('facebook.profile.getInfo', :uid => id)
end

#getUnconnectedFriendsCountObject

Get a count of unconnected friends



467
468
469
# File 'lib/facebooker/models/user.rb', line 467

def getUnconnectedFriendsCount
  session.post("facebook.connect.getUnconnectedFriendsCount")
end

#groups(gids = []) ⇒ Object



213
214
215
216
217
218
219
220
# File 'lib/facebooker/models/user.rb', line 213

def groups(gids = [])
  args = gids.empty? ? {} : {:gids => gids}
  @groups ||= session.post('facebook.groups.get', args).map do |hash|
    group = Group.from_hash(hash)
    group.session = session
    group
  end
end

#has_permission?(ext_perm) ⇒ Boolean

Checks to see if the user has enabled the given extended permission

Returns:

  • (Boolean)


392
393
394
# File 'lib/facebooker/models/user.rb', line 392

def has_permission?(ext_perm) # ext_perm = email, offline_access, status_update, photo_upload, create_listing, create_event, rsvp_event, sms
  session.post('facebook.users.hasAppPermission', {:ext_perm=>ext_perm, :uid => uid}, false) == "1"
end

#has_permissions?(ext_perms) ⇒ Boolean

Convenience method to check multiple permissions at once

Returns:

  • (Boolean)


398
399
400
# File 'lib/facebooker/models/user.rb', line 398

def has_permissions?(ext_perms)
  ext_perms.all?{|p| has_permission?(p)}
end

#mobile_fbml=(markup) ⇒ Object

Set the mobile profile FBML



331
332
333
# File 'lib/facebooker/models/user.rb', line 331

def mobile_fbml=(markup)
  set_profile_fbml(nil, markup, nil,nil)
end

#notificationsObject



222
223
224
# File 'lib/facebooker/models/user.rb', line 222

def notifications
  @notifications ||= Notifications.from_hash(session.post('facebook.notifications.get'))
end

#populate(*fields) ⇒ Object

Retrieve profile data for logged in user Optional: list of fields to retrieve as symbols



193
194
195
196
197
# File 'lib/facebooker/models/user.rb', line 193

def populate(*fields)
  session.post('facebook.users.getInfo', :fields => collect(fields), :uids => id) do |response|
    populate_from_hash!(response.first)
  end
end

#prepare_publish_to_options(target, options) ⇒ Object

Prepares options for the stream.publish



147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/facebooker/models/user.rb', line 147

def prepare_publish_to_options(target, options)
  opts = {:uid          => self.id,
          :target_id    => target.id,
          :message      => options[:message]} 

  if(attachment = options[:attachment] && Facebooker.json_encode(options[:attachment]))
    opts[:attachment] = attachment
  end
  if (links = options[:action_links] && Facebooker.json_encode(options[:action_links]))
    opts[:action_links] = links
  end
  opts
end

#profile_action=(markup) ⇒ Object



335
336
337
# File 'lib/facebooker/models/user.rb', line 335

def profile_action=(markup)
  set_profile_fbml(nil, nil, markup,nil)
end

#profile_fbmlObject



317
318
319
# File 'lib/facebooker/models/user.rb', line 317

def profile_fbml
  session.post('facebook.profile.getFBML', :uid => id)  
end

#profile_fbml=(markup) ⇒ Object

Set the profile FBML for this user

This does not set profile actions, that should be done with profile_action=



325
326
327
# File 'lib/facebooker/models/user.rb', line 325

def profile_fbml=(markup)
  set_profile_fbml(markup, nil, nil, nil)
end

#profile_main=(markup) ⇒ Object



339
340
341
# File 'lib/facebooker/models/user.rb', line 339

def profile_main=(markup)
 set_profile_fbml(nil,nil,nil,markup)
end

#profile_photosObject



250
251
252
# File 'lib/facebooker/models/user.rb', line 250

def profile_photos
  session.get_photos(nil, nil, profile_pic_album_id)
end

#publish_action(action) ⇒ Object



230
231
232
# File 'lib/facebooker/models/user.rb', line 230

def publish_action(action)
  publish(action)
end

#publish_story(story) ⇒ Object



226
227
228
# File 'lib/facebooker/models/user.rb', line 226

def publish_story(story)
  publish(story)
end

#publish_templatized_action(action) ⇒ Object



234
235
236
# File 'lib/facebooker/models/user.rb', line 234

def publish_templatized_action(action)
  publish(action)
end

#publish_to(target, options = {}) ⇒ Object

Publish a post into the stream on the user’s Wall and News Feed. This post also appears in the user’s friend’s streams. The publish_stream extended permission must be granted in order to use this method.

See: wiki.developers.facebook.com/index.php/Stream.publish

target can be the current user or some other user.

Example:

# Publish a message to my own wall:
me.publish_to(me, :message => 'hello world')

# Publish to a friend's wall with an action link:
me.publish_to(my_friend,  :message => 'how are you?', :action_links => [
  :text => 'my website',
  :href => 'http://tenderlovemaking.com/'
])


142
143
144
# File 'lib/facebooker/models/user.rb', line 142

def publish_to(target, options = {})
  @session.post('facebook.stream.publish', prepare_publish_to_options(target, options), false)
end

#rsvp_event(eid, rsvp_status, options = {}) ⇒ Object

Rsvp to an event with the eid and rsvp_status which can be ‘attending’, ‘unsure’, or ‘declined’. wiki.developers.facebook.com/index.php/Events.rsvp E.g:

@user.rsvp_event('100321123', 'attending')
# => Returns true if all went well


75
76
77
78
# File 'lib/facebooker/models/user.rb', line 75

def rsvp_event(eid, rsvp_status, options = {})
  result = @session.post('facebook.events.rsvp', options.merge(:eid => eid, :rsvp_status => rsvp_status))
  result == '1' ? true : false
end

#send_email(subject, text = nil, fbml = nil) ⇒ Object

Convenience method to send email to the current user



405
406
407
# File 'lib/facebooker/models/user.rb', line 405

def send_email(subject, text=nil, fbml=nil)
  session.send_email([id], subject, text, fbml)
end

Convenience method to set cookie for the current user



411
412
413
# File 'lib/facebooker/models/user.rb', line 411

def set_cookie(name, value, expires=nil, path=nil)
  session.data.set_cookie(id, name, value, expires, path)
end

#set_profile_fbml_with_bebo_adapter(profile_fbml, mobile_fbml, profile_action_fbml, profile_main = nil) ⇒ Object Also known as: set_profile_fbml



38
39
40
41
42
43
44
# File 'lib/facebooker/adapters/bebo_adapter.rb', line 38

def set_profile_fbml_with_bebo_adapter(profile_fbml, mobile_fbml, profile_action_fbml, profile_main = nil)
  if(Facebooker.is_for?(:bebo))
    self.session.post('facebook.profile.setFBML', :uid => @id, :markup => profile_fbml)
  else
    set_profile_fbml_without_bebo_adapter(profile_fbml,mobile_fbml, profile_action_fbml, profile_main)
  end
end

#set_profile_info(title, info_fields, format = :text) ⇒ Object

** NEW PROFILE DESIGN *** Set a info section for this user

Note: using set_profile_info as I feel using user.set_info could be confused with the user.getInfo facebook method.

Also, I feel it fits in line with user.set_profile_fbml.


357
358
359
360
# File 'lib/facebooker/models/user.rb', line 357

def set_profile_info(title, info_fields, format = :text)
  session.post('facebook.profile.setInfo', :title => title, :uid => id, 
    :type => format.to_s == "text" ? 1 : 5, :info_fields => info_fields.to_json)
end

#set_status(message) ⇒ Object

Set the status for a user DOES NOT prepend “is” to the message

requires extended permission.



383
384
385
386
387
388
# File 'lib/facebooker/models/user.rb', line 383

def set_status(message)
  self.status=message
  session.post('facebook.users.setStatus',{:status=>message,:status_includes_verb=>1,:uid => uid}, false) do |ret|
    ret
  end
end

#status=(message) ⇒ Object

This DOES NOT set the status of a user on Facebook Use the set_status method instead



369
370
371
372
373
374
375
376
# File 'lib/facebooker/models/user.rb', line 369

def status=(message)
  case message
  when String,Status
    @status = message
  when Hash
    @status = Status.from_hash(message)
  end
end

#to_iObject

Returns the user’s id as an integer



423
424
425
# File 'lib/facebooker/models/user.rb', line 423

def to_i
  id
end

#to_sObject



427
428
429
# File 'lib/facebooker/models/user.rb', line 427

def to_s
  id.to_s
end

#upload_photo(multipart_post_file, options = {}) ⇒ Object

Upload a photo to the user’s profile.

In your view, create a multipart form that posts directly to your application (not through canvas):

<% form_tag photos_url(:canvas => false), :html => {:multipart => true, :promptpermission => 'photo_upload'} do %>
  Photo: <%= file_field_tag 'photo' %>
  Caption: <%= text_area_tag 'caption' %>
  <%= submit_tag 'Upload Photo', :class => 'inputsubmit' %>
<% end %>

And in your controller:

class PhotosController < ApplicationController
  def create
    file = Net::HTTP::MultipartPostFile.new(
      params[:photo].original_filename,
      params[:photo].content_type,
      params[:photo].read
    )

    @photo = facebook_session.user.upload_photo(file, :caption => params[:caption])
    redirect_to photos_url(:canvas => true)
  end
end

Options correspond to wiki.developers.facebook.com/index.php/Photos.upload



280
281
282
283
# File 'lib/facebooker/models/user.rb', line 280

def upload_photo(multipart_post_file, options = {})
  Photo.from_hash(session.post_file('facebook.photos.upload',
    options.merge(nil => multipart_post_file)))
end

#upload_video(multipart_post_file, options = {}) ⇒ Object

Upload a video to the user’s profile.

In your view, create a multipart form that posts directly to your application (not through canvas):

<% form_tag videos_url(:canvas => false), :html => {:multipart => true, :promptpermission => 'video_upload'} do %>
  Video: <%= file_field_tag 'video' %>
  Title: <%= text_area_tag 'title' %>
  Description: <%= text_area_tag 'description' %>
  <%= submit_tag 'Upload Video', :class => 'inputsubmit' %>
<% end %>

And in your controller:

class VideosController < ApplicationController
  def create
    file = Net::HTTP::MultipartPostFile.new(
      params[:photo].original_filename,
      params[:photo].content_type,
      params[:photo].read
    )

    @video = facebook_session.user.upload_video(file, :description => params[:description])
    redirect_to videos_url(:canvas => true)
  end
end

Options correspond to wiki.developers.facebook.com/index.php/Video.upload



312
313
314
315
# File 'lib/facebooker/models/user.rb', line 312

def upload_video(multipart_post_file, options = {})
  Video.from_hash(session.post_file('facebook.video.upload',
    options.merge(nil => multipart_post_file, :base => Facebooker.video_server_base)))
end