Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aws boto sns - get endpoint_arn by device token

Currently, If we want to add a device to an SNS application using:

ep = SNSConnection.create_platform_endpoint(app_arn,device_token,user_data)

There is an option that the device was already added in the past. To verify if the device is already added, we're using:

def is_device_registered(device_token):
        list_of_endpoints = SNSConnection.list_endpoints_by_platform_application(AC.INPLAY_CHAT_APPLICATION_SNS_ARN)
        all_app_endpoints = list_of_endpoints['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
        for ep in all_app_endpoints:
            ep_device_token = ep['Attributes']['Token']
            if device_token == ep_device_token:
                endpoint_arn =  ep['EndpointArn']
                print 'Found an endpoint for device_token: %s, entry:%s' % (device_token,endpoint_arn)
                return endpoint_arn
        return None

which is very inefficient and can not be scaled.

is there a boto sns function that get the device_token and returns the endpoint_arn if exists? (None if not).

like image 927
Amit Talmor Avatar asked Mar 06 '14 14:03

Amit Talmor


2 Answers

Amazon gives you the arn on the Error Message. You can parse it from there. Not optimal, but saves some db lookup.

error: SNS ERROR - Could not subcribe user to SNSInvalidParameter: Invalid parameter: Token Reason: Endpoint arn:aws:sns:us-east-[rest of the ARN Key] already exists with the same Token, but different attributes. Here is some coffe with regex ready to go

if err?
  log.error "SNS ERROR - Could not subcribe user to SNS" + err
  #Try to get arn from error

  result = err.message.match(/Endpoint(.*)already/)
  if result?.length
    #Assign and remove leading and trailing white spaces.
    result = result[1].replace /^\s+|\s+$/g, ""
    log.debug "found existing arn-> #{result} "
like image 97
fino Avatar answered Oct 17 '22 22:10

fino


Same answer as @fino but code for Django. Hope this help.

import re

try:
    sns_connection = sns.connect_to_region(...)
    response = sns_connection.create_platform_endpoint(...)
    arn = response['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
    return arn

except Exception, err:
    print err
    #try to get arn from error
    result_re = re.compile(r'Endpoint(.*)already', re.IGNORECASE)
    result = result_re.search(err.message)
    if result:
        arn = result.group(0).replace('Endpoint ','').replace(' already','')
        print arn
        return arn
    return ''
like image 45
John Pang Avatar answered Oct 17 '22 21:10

John Pang