Skip to content

Instantly share code, notes, and snippets.

@namit
Last active August 29, 2015 13:59
Show Gist options
  • Save namit/10911934 to your computer and use it in GitHub Desktop.
Save namit/10911934 to your computer and use it in GitHub Desktop.
Creating and Editing Endpoints in Amazon Simple Notification Servicce (SNS) + Apple Apple Push Notification service (APNS) + Ruby
sns = AWS::SNS.new(:access_key_id => AWSPUB,:secret_access_key => AWSPRI)
app_arn = server.is_sandbox? ? SNS_SANDBOX_APP_ARN : SNS_PRODUCTION_APP_ARN
timestamp = Time.new.strftime("%Y-%m-%d %H:%M:%S")
custom_user_data = "{\"user_id\":#{user.id},\"type\":\"#{token_type}\",\"update_ts\":\"#{timestamp}\"}"
if edit_endpoint # Edit existing endpoint
apn_token = AppleToken.find(:id => token_id) # AppleToken is the DB object in Sequel
if apn_token.nil? || apn_token.user_id != user.id
# Token ID not found for this user
# Return with error
end
apn_token.type = token_type
apn_token.update_ts = timestamp
# (1) Disable endpoint
if token_type == 'none'
apn_token.token = ''
# Ideally you want to catch SNS exceptions
sns.client.set_endpoint_attributes(endpoint_arn: apn_token.endpoint_arn, attributes: {'Enabled' => 'false', 'CustomUserData' => custom_user_data})
# (2) Edit existing endpoint
else
apn_token.token = apntoken
sns.client.set_endpoint_attributes(endpoint_arn: apn_token.endpoint_arn, attributes: {'Enabled' => 'true', 'CustomUserData' => custom_user_data, 'Token' => apntoken})
end
if apn_token.save
# Return with success
else
# Return with DB error
end
else
# (3) Create endpoint and get endpoint_arn
unless token_type == 'none'
endpoint = sns.client.create_platform_endpoint(platform_application_arn: app_arn, token: apntoken, custom_user_data: custom_user_data)
unless endpoint[:endpoint_arn].nil?
apn_token = AppleToken.new(
:user_id => user.id,
:type => token_type,
:token => apntoken,
:endpoint_arn => endpoint[:endpoint_arn],
:update_ts => timestamp
)
if apn_token.save
# Return with success and perhaps apn_token.id
else
# Return with DB error
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment