2020-02-11 08:57:38 +00:00
|
|
|
class Twitter::CallbacksController < Twitter::BaseController
|
2021-02-16 14:05:10 +00:00
|
|
|
include TwitterConcern
|
|
|
|
|
2020-02-11 08:57:38 +00:00
|
|
|
def show
|
2020-03-28 06:21:42 +00:00
|
|
|
return redirect_to twitter_app_redirect_url if permitted_params[:denied]
|
2020-03-05 20:17:37 +00:00
|
|
|
|
2020-05-14 17:21:07 +00:00
|
|
|
@response = ensure_access_token
|
|
|
|
return redirect_to twitter_app_redirect_url if @response.status != '200'
|
|
|
|
|
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
inbox = create_inbox
|
2020-02-11 08:57:38 +00:00
|
|
|
::Redis::Alfred.delete(permitted_params[:oauth_token])
|
|
|
|
::Twitter::WebhookSubscribeService.new(inbox_id: inbox.id).perform
|
2020-03-28 06:21:42 +00:00
|
|
|
redirect_to app_twitter_inbox_agents_url(account_id: account.id, inbox_id: inbox.id)
|
2020-02-11 08:57:38 +00:00
|
|
|
end
|
2020-05-14 17:21:07 +00:00
|
|
|
rescue StandardError => e
|
2022-03-28 12:44:30 +00:00
|
|
|
Rails.logger.error e
|
2020-05-14 17:21:07 +00:00
|
|
|
redirect_to twitter_app_redirect_url
|
2020-02-11 08:57:38 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def parsed_body
|
|
|
|
@parsed_body ||= Rack::Utils.parse_nested_query(@response.raw_response.body)
|
|
|
|
end
|
|
|
|
|
|
|
|
def account_id
|
|
|
|
::Redis::Alfred.get(permitted_params[:oauth_token])
|
|
|
|
end
|
|
|
|
|
|
|
|
def account
|
2020-09-08 05:54:08 +00:00
|
|
|
@account ||= Account.find(account_id)
|
2020-02-11 08:57:38 +00:00
|
|
|
end
|
|
|
|
|
2020-03-28 06:21:42 +00:00
|
|
|
def twitter_app_redirect_url
|
|
|
|
app_new_twitter_inbox_url(account_id: account.id)
|
|
|
|
end
|
|
|
|
|
2020-05-14 17:21:07 +00:00
|
|
|
def ensure_access_token
|
|
|
|
twitter_client.access_token(
|
|
|
|
oauth_token: permitted_params[:oauth_token],
|
|
|
|
oauth_verifier: permitted_params[:oauth_verifier]
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_inbox
|
2022-09-13 12:10:06 +00:00
|
|
|
twitter_profile = account.twitter_profiles.create!(
|
2020-05-14 17:21:07 +00:00
|
|
|
twitter_access_token: parsed_body['oauth_token'],
|
|
|
|
twitter_access_token_secret: parsed_body['oauth_token_secret'],
|
|
|
|
profile_id: parsed_body['user_id']
|
|
|
|
)
|
2022-09-13 12:10:06 +00:00
|
|
|
account.inboxes.create!(
|
2020-05-14 17:21:07 +00:00
|
|
|
name: parsed_body['screen_name'],
|
|
|
|
channel: twitter_profile
|
|
|
|
)
|
2020-02-11 08:57:38 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def permitted_params
|
2020-03-05 20:17:37 +00:00
|
|
|
params.permit(:oauth_token, :oauth_verifier, :denied)
|
2020-02-11 08:57:38 +00:00
|
|
|
end
|
|
|
|
end
|