Module: MiniFB

Defined in:
lib/photo_mini_fb.rb

Defined Under Namespace

Classes: FaceBookError, FaceBookSecret, Photos, Session, User

Constant Summary collapse

FB_URL =

Global constants

"http://api.facebook.com/restserver.php"
FB_API_VERSION =
"1.0"
BAD_JSON_METHODS =
["users.getloggedinuser", "auth.promotesession", "users.hasapppermission", "Auth.revokeExtendedPermission", "pages.isAdmin"].collect { |x| x.downcase }
@@logging =
false

Class Method Summary collapse

Class Method Details

.call(api_key, secret, method, kwargs) ⇒ Object

The secret argument should be an instance of FacebookSecret to hide value from simple introspection.



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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/photo_mini_fb.rb', line 138

def MiniFB.call( api_key, secret, method, kwargs )

    puts 'kwargs=' + kwargs.inspect if @@logging

    if secret.is_a? String
        secret = FaceBookSecret.new(secret)
    end

    # Prepare arguments for call
    call_id = kwargs.fetch("call_id", true)
    if call_id == true then
        kwargs["call_id"] = Time.now.tv_sec.to_s
    else
        kwargs.delete("call_id")
    end

    if method == "photos.upload"
      filename = kwargs.fetch("filename")
      kwargs.delete("filename")
    end

    custom_format = kwargs.include?("format") or kwargs.include?("callback")
    kwargs["format"] ||= "JSON"
    kwargs["v"] ||= FB_API_VERSION
    kwargs["api_key"]||= api_key
    kwargs["method"] ||= method

    # Hash with secret
    arg_string = String.new
    # todo: convert symbols to strings, symbols break the next line
    kwargs.sort.each { |kv| arg_string << kv[0] << "=" << kv[1].to_s }
    kwargs["sig"] = Digest::MD5.hexdigest( arg_string + secret.value.call )

    # Call website with POST request
    begin
      if method == "photos.upload"
        response = MiniFB.post_upload(filename, kwargs)
      else
        response = Net::HTTP.post_form( URI.parse(FB_URL), kwargs )
      end
    rescue SocketError => err
        raise IOError.new( "Cannot connect to the facebook server: " + err )
    end

    # Handle response
    return response.body if custom_format

    fb_method = kwargs["method"].downcase
    body = response.body

    puts 'response=' + body.inspect if @@logging
    begin
        data = JSON.parse( body )
        if data.include?( "error_msg" ) then
            raise FaceBookError.new( data["error_code"] || 1, data["error_msg"] )
        end

    rescue JSON::ParserError => ex
        if BAD_JSON_METHODS.include?(fb_method) # Little hack because this response isn't valid JSON
            if body == "0" || body == "false"
                return false
            end
            return body
        else
            raise ex
        end
    end
    return data
end

.disable_loggingObject



20
21
22
# File 'lib/photo_mini_fb.rb', line 20

def self.disable_logging
    @@logging = false
end

.enable_loggingObject



16
17
18
# File 'lib/photo_mini_fb.rb', line 16

def self.enable_logging
    @@logging = true
end

.login_url(api_key, options = {}) ⇒ Object

Returns the login/add app url for your application.

options:

- :next => a relative next page to go to. relative to your facebook connect url or if :canvas is true, then relative to facebook app url
- :canvas => true/false - to say whether this is a canvas app or not


264
265
266
267
268
269
# File 'lib/photo_mini_fb.rb', line 264

def self.(api_key, options={})
     = "http://api.facebook.com/login.php?api_key=#{api_key}"
     << "&next=#{options[:next]}" if options[:next]
     << "&canvas" if options[:canvas]
    
end

.post_upload(filename, kwargs) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/photo_mini_fb.rb', line 208

def MiniFB.post_upload(filename, kwargs)
  content = open(filename, 'rb') { |f| f.read }
  boundary = Digest::MD5.hexdigest(content)
  header = {'Content-type' => "multipart/form-data, boundary=#{boundary}"}

  # Build query
  query = ''
  kwargs.each { |a, v|
    query <<
      "--#{boundary}\r\n" <<
      "Content-Disposition: form-data; name=\"#{a}\"\r\n\r\n" <<
      "#{v}\r\n"
  }
  query <<
    "--#{boundary}\r\n" <<
    "Content-Disposition: form-data; filename=\"#{File.basename(filename)}\"\r\n" <<
    "Content-Transfer-Encoding: binary\r\n" <<
    "Content-Type: image/jpeg\r\n\r\n" <<
    content <<
    "\r\n" <<
    "--#{boundary}--"

  # Call Facebook with POST multipart/form-data request
  uri = URI.parse(FB_URL)
  Net::HTTP.start(uri.host) {|http| http.post uri.path, query, header}
end

.validate(secret, arguments) ⇒ Object

DEPRECATED, use verify_signature instead



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/photo_mini_fb.rb', line 289

def MiniFB.validate( secret, arguments )

    signature = arguments.delete( "fb_sig" )
    return arguments if signature.nil?

    unsigned = Hash.new
    signed = Hash.new

    arguments.each do |k, v|
        if k =~ /^fb_sig_(.*)/ then
            signed[$1] = v
        else
            unsigned[k] = v
        end
    end

    arg_string = String.new
    signed.sort.each { |kv| arg_string << kv[0] << "=" << kv[1] }
    if Digest::MD5.hexdigest( arg_string + secret ) != signature
        unsigned # Hash is incorrect, return only unsigned fields.
    else
        unsigned.merge signed
    end
end

.verify_signature(secret, arguments) ⇒ Object

Returns true is signature is valid, false otherwise.



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/photo_mini_fb.rb', line 236

def MiniFB.verify_signature( secret, arguments )
    signature = arguments.delete( "fb_sig" )
    return false if signature.nil?

    unsigned = Hash.new
    signed = Hash.new

    arguments.each do |k, v|
        if k =~ /^fb_sig_(.*)/ then
            signed[$1] = v
        else
            unsigned[k] = v
        end
    end

    arg_string = String.new
    signed.sort.each { |kv| arg_string << kv[0] << "=" << kv[1] }
    if Digest::MD5.hexdigest( arg_string + secret ) == signature
        return true
    end
    return false
end