Class: Mogli::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty, Event, User
Defined in:
lib/mogli/client.rb,
lib/mogli/client/user.rb,
lib/mogli/client/event.rb

Defined Under Namespace

Modules: Event, User Classes: ClientException, FeedActionRequestLimitExceeded, OAuthAccessTokenException, OAuthException, OAuthUnauthorizedClientException, QueryParseException, UnrecognizeableClassError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from User

#user

Methods included from Event

#event

Constructor Details

#initialize(access_token = nil, expiration = nil) ⇒ Client

Returns a new instance of Client.



31
32
33
34
35
36
37
# File 'lib/mogli/client.rb', line 31

def initialize(access_token = nil,expiration=nil)
  @access_token = access_token
  # nil expiration means extended access
  expiration = Time.now.to_i + 10*365*24*60*60 if expiration.nil? or expiration == 0
  @expiration = Time.at(expiration)
  @default_params = @access_token ? {:access_token=>access_token} : {}
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



6
7
8
# File 'lib/mogli/client.rb', line 6

def access_token
  @access_token
end

#default_paramsObject (readonly)

Returns the value of attribute default_params.



7
8
9
# File 'lib/mogli/client.rb', line 7

def default_params
  @default_params
end

#expirationObject (readonly)

Returns the value of attribute expiration.



8
9
10
# File 'lib/mogli/client.rb', line 8

def expiration
  @expiration
end

Class Method Details

.create_and_authenticate_as_application(client_id, secret) ⇒ Object



83
84
85
86
87
# File 'lib/mogli/client.rb', line 83

def self.create_and_authenticate_as_application(client_id, secret)
  authenticator = Mogli::Authenticator.new(client_id, secret, nil)
  access_data = authenticator.get_access_token_for_application
  new(access_data)
end

.create_from_code_and_authenticator(code, authenticator) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/mogli/client.rb', line 43

def self.create_from_code_and_authenticator(code,authenticator)
  post_data = get(authenticator.access_token_url(code))
  if (response_is_error?(post_data))
    raise_client_exception(post_data)
  end        
  parts = post_data.split("&")
  hash = {}
  parts.each do |p| (k,v) = p.split("=")
    hash[k]=CGI.unescape(v)
  end
  new(hash["access_token"],hash["expires"].to_s.to_i)
end

.create_from_session_key(session_key, client_id, secret) ⇒ Object



76
77
78
79
80
81
# File 'lib/mogli/client.rb', line 76

def self.create_from_session_key(session_key, client_id, secret)
  authenticator = Mogli::Authenticator.new(client_id, secret, nil)
  access_data = authenticator.get_access_token_for_session_key(session_key)
  new(access_data['access_token'],
      Time.now.to_i + access_data['expires'].to_i)
end

.raise_client_exception(post_data) ⇒ Object



56
57
58
# File 'lib/mogli/client.rb', line 56

def self.raise_client_exception(post_data)
  raise_error_by_type_and_message(post_data["error"]["type"], post_data["error"]["message"])
end

.raise_error_by_type_and_message(type, message) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/mogli/client.rb', line 60

def self.raise_error_by_type_and_message(type, message)
  if type == 'OAuthException' && message =~ /Feed action request limit reached/
    raise FeedActionRequestLimitExceeded.new(message)
  elsif Mogli::Client.const_defined?(type)
    raise Mogli::Client.const_get(type).new(message)
  else
    raise ClientException.new("#{type}: #{message}")
  end
end

.response_is_error?(post_data) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
73
74
# File 'lib/mogli/client.rb', line 70

def self.response_is_error?(post_data)
  post_data.is_a?(HTTParty::Response) and
   post_data.parsed_response.kind_of?(Hash) and
   !post_data.parsed_response["error"].blank?
end

Instance Method Details

#api_path(path) ⇒ Object



23
24
25
# File 'lib/mogli/client.rb', line 23

def api_path(path)
  "https://graph.facebook.com/#{path}"
end

#constantize_string(klass) ⇒ Object



160
161
162
# File 'lib/mogli/client.rb', line 160

def constantize_string(klass)
  klass.is_a?(String) ? Mogli.const_get(klass.capitalize) : klass
end

#create_instance(klass, data) ⇒ Object



152
153
154
155
156
157
158
# File 'lib/mogli/client.rb', line 152

def create_instance(klass,data)
  klass_to_create =  determine_class(klass,data)
  if klass_to_create.nil?
    raise UnrecognizeableClassError.new("unable to recognize klass for #{klass.inspect} => #{data.inspect}")
  end
  klass_to_create.new(data,self)
end

#delete(path) ⇒ Object



94
95
96
# File 'lib/mogli/client.rb', line 94

def delete(path)
  self.class.delete(api_path(path),:query=>default_params)
end

#determine_class(klass_or_klasses, data) ⇒ Object



164
165
166
167
168
# File 'lib/mogli/client.rb', line 164

def determine_class(klass_or_klasses,data)
  return constantize_string(data['type']) if data.key?('type') && klass_or_klasses == Mogli::Model
  klasses = Array(klass_or_klasses).map { |k| constantize_string(k)}
  klasses.detect {|klass| klass.recognize?(data)} || klasses.first
end

#expired?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/mogli/client.rb', line 39

def expired?
  expiration and expiration < Time.now
end

#extract_fetching_array(hash, klass) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
# File 'lib/mogli/client.rb', line 131

def extract_fetching_array(hash,klass)
  f = Mogli::FetchingArray.new
  f.concat(hash["data"])
  f.client = self
  f.classes = Array(klass)
  if hash["paging"]
    f.next_url = hash["paging"]["next"]
    f.previous_url = hash["paging"]["previous"]
  end
  f
end

#extract_hash_or_array(hash_or_array, klass) ⇒ Object

protected



124
125
126
127
128
129
# File 'lib/mogli/client.rb', line 124

def extract_hash_or_array(hash_or_array,klass)
  return nil if hash_or_array == false
  return hash_or_array if hash_or_array.nil? or hash_or_array.kind_of?(Array)
  return extract_fetching_array(hash_or_array,klass) if hash_or_array.has_key?("data")
  return hash_or_array
end

#fields_to_serializeObject



178
179
180
# File 'lib/mogli/client.rb', line 178

def fields_to_serialize
  [:access_token,:default_params,:expiration]
end

#fql_pathObject



27
28
29
# File 'lib/mogli/client.rb', line 27

def fql_path
  "https://api.facebook.com/method/fql.query"
end

#fql_query(query, klass = nil, format = "json") ⇒ Object



98
99
100
101
102
# File 'lib/mogli/client.rb', line 98

def fql_query(query,klass=nil,format="json")
  data = self.class.post(fql_path,:body=>default_params.merge({:query=>query,:format=>format}))
  return data unless format=="json"
  map_data(data,klass)
end

#get_and_map(path, klass = nil, body_args = {}) ⇒ Object



104
105
106
107
108
# File 'lib/mogli/client.rb', line 104

def get_and_map(path,klass=nil,body_args = {})
  data = self.class.get(api_path(path),:query=>default_params.merge(body_args))
  data = data.values if body_args.key?(:ids) && !data.key?('error')
  map_data(data,klass)
end

#get_and_map_url(url, klass = nil) ⇒ Object



110
111
112
113
# File 'lib/mogli/client.rb', line 110

def get_and_map_url(url,klass=nil)
  data = self.class.get(url)
  map_data(data,klass)
end

#map_data(data, klass = nil) ⇒ Object



115
116
117
118
119
120
# File 'lib/mogli/client.rb', line 115

def map_data(data,klass=nil)
  raise_error_if_necessary(data)
  hash_or_array = extract_hash_or_array(data,klass)
  hash_or_array = map_to_class(hash_or_array,klass) if klass
  hash_or_array
end

#map_to_class(hash_or_array, klass) ⇒ Object



143
144
145
146
147
148
149
150
# File 'lib/mogli/client.rb', line 143

def map_to_class(hash_or_array,klass)
  return nil if hash_or_array.nil?
  if hash_or_array.kind_of?(Array)
    hash_or_array.map! {|i| create_instance(klass,i)}
  else
    hash_or_array = create_instance(klass,hash_or_array)
  end
end

#marshal_dumpObject

Only serialize the bare minimum to recreate the session.



188
189
190
# File 'lib/mogli/client.rb', line 188

def marshal_dump#:nodoc:
  fields_to_serialize.map{|field| send(field)}
end

#marshal_load(variables) ⇒ Object

Only serialize the bare minimum to recreate the session.



183
184
185
# File 'lib/mogli/client.rb', line 183

def marshal_load(variables)#:nodoc:
  fields_to_serialize.each_with_index{|field, index| instance_variable_set("@#{field}", variables[index])}
end

#post(path, klass, body_args) ⇒ Object



89
90
91
92
# File 'lib/mogli/client.rb', line 89

def post(path,klass,body_args)
  data = self.class.post(api_path(path),:body=>default_params.merge(body_args))
  map_data(data,klass)
end

#raise_error_if_necessary(data) ⇒ Object



170
171
172
173
174
175
176
# File 'lib/mogli/client.rb', line 170

def raise_error_if_necessary(data)
  if data.kind_of?(Hash)
    if data.keys.size == 1 and data["error"]
      self.class.raise_error_by_type_and_message(data["error"]["type"], data["error"]["message"])
    end
  end
end

#to_yaml(opts = {}) ⇒ Object

Only serialize the bare minimum to recreate the session.



193
194
195
196
197
198
199
200
201
# File 'lib/mogli/client.rb', line 193

def to_yaml( opts = {} )#nodoc
  YAML::quick_emit(self.object_id, opts) do |out|
    out.map(taguri) do |map|
      fields_to_serialize.each do |field|
        map.add(field, send(field))
      end
    end
  end
end