Last active
December 2, 2015 13:53
-
-
Save jeanbaptistebeck/cb15b0cab33bbe63349d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'base64' | |
class Provider < ActiveRecord::Base | |
belongs_to :user | |
def prepare_access_token(oauth_token, oauth_token_secret) | |
token_hash = { oauth_token: oauth_token, oauth_token_secret: oauth_token_secret } | |
access_token = OAuth::AccessToken.from_hash(TWITTER_APP, token_hash) | |
access_token | |
end | |
def publish_status(status:, image: nil) | |
access_token = generate_access_token | |
params_url = "status=#{CGI.escape status}" | |
if image.present? | |
media_id = upload_photo(image) | |
return nil unless media_id.present? | |
params_url += "&media_ids=#{media_id}" | |
end | |
response = access_token.post("https://api.twitter.com/1.1/statuses/update.json?#{params_url}") | |
data = JSON.parse(response.body) | |
data['id'] | |
end | |
def upload_photo(image) | |
access_token = generate_access_token | |
download_media("#{Rails.root}/tmp/#{image.model.photo_tweet_identifier}", image.url) | |
response = access_token.post('https://upload.twitter.com/1.1/media/upload.json', 'media_data' => Base64.encode64(File.open("#{Rails.root}/tmp/#{image.model.photo_tweet_identifier}").read), 'Content-Type' => 'multipart/form-data') | |
data = JSON.parse(response.body) | |
data['media_id'] | |
end | |
private | |
def download_media(path, url) | |
open(path, 'wb') do |file| | |
file << open(url).read | |
end | |
end | |
def generate_access_token | |
Rails.env.production? ? prepare_access_token(token, secret) : FAKE_PROVIDER | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment