Skip to content

Instantly share code, notes, and snippets.

@petewarden
Created November 28, 2011 03:20

Revisions

  1. petewarden created this gist Nov 28, 2011.
    51 changes: 51 additions & 0 deletions photoupload.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@

    require 'rubygems' if RUBY_VERSION < '1.9'
    require 'net/https'
    require 'uri'
    require 'multipart'

    FACEBOOK_GRAPH_SERVER='https://graph.facebook.com'

    def post_https(url, data, header)

    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    # http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Don't use this in production, only to diagnose if you have a common config problem

    begin
    response = http.request_post(uri.request_uri, data, header)

    result = nil
    if response.code != '200'
    log "Bad response code #{response.status} for '#{url}'"
    result = nil
    else
    result = response.body
    end
    rescue NoMethodError
    result = nil
    end

    result
    end

    def upload_photo_to_facebook(facebook_id, access_token, image_data, message)

    multipart_post = Multipart::Post.new()
    multipart_params = { 'source' => { 'path' => 'screenshot.png', 'read' => image_data },
    'message' => message,
    }
    post_data, post_header = multipart_post.prepare_query(multipart_params)

    host = FACEBOOK_GRAPH_SERVER
    method = '/me/photos?'
    arguments = [
    'access_token='+u(access_token),
    ].join('&')

    url = host+method+arguments
    post_result = post_https(url, post_data, post_header)

    post_result
    end