Created
May 19, 2015 14:43
-
-
Save zosiu/1b24690ba42cc032dea6 to your computer and use it in GitHub Desktop.
Instagram Real Time Update w/ Rails
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 'active_job/retry' | |
class InstagramJob < ActiveJob::Base | |
include ActiveJob::Retry | |
variable_retry delays: [60, 2 * 60, 5 * 60, 15 * 60, 60 * 60] | |
queue_as :instagram_rtu | |
def perform(instagram_user_uid, instagram_media_uid) | |
user = User.find_by! instagram_uid: instagram_user_uid | |
media = user.instagram_media instagram_media_uid | |
# ... do your thing here | |
end | |
end |
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
class InstagramRealTimeUpdatesController < ActionController::Base | |
def callback | |
case request.method_symbol | |
when :get | |
render text: Instagram.meet_challenge(params, ENV['INSTAGRAM_VERIFY_TOKEN']) | |
when :post | |
Instagram.process_subscription(request.body.read) do |handler| | |
handler.on_user_changed do |user_id, data| | |
media_id = (data['data'] || {})['media_id'] | |
InstagramJob.perform_later user_id, media_id | |
end | |
end | |
head :ok | |
when :options | |
headers['Access-Control-Allow-Methods'] = | |
allowed_methods.map { |sym| sym.to_s.upcase }.join(', ') | |
head :ok | |
end | |
end | |
protected | |
def verify_request_type | |
head :method_not_allowed unless allowed_methods.include?(request.method_symbol) | |
end | |
def allowed_methods | |
[:get, :post] | |
end | |
end |
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
Rails.application.routes.draw do | |
match 'instagram_real_time_update', | |
to: 'instagram_real_time_updates#callback', | |
via: [:get, :post] | |
end |
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
class User < ActiveRecord::Base | |
def instagram_media(media_id) | |
instagram.media_item media_id | |
end | |
private | |
def instagram | |
@instagram ||= Instagram.client access_token: instagram_auth_token | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://instagram.com/developer/realtime/