1# Copyright (c) 2010-2012 Mitch Garnaat http://garnaat.org/
2# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.  All Rights Reserved
3#
4# Permission is hereby granted, free of charge, to any person obtaining a
5# copy of this software and associated documentation files (the
6# "Software"), to deal in the Software without restriction, including
7# without limitation the rights to use, copy, modify, merge, publish, dis-
8# tribute, sublicense, and/or sell copies of the Software, and to permit
9# persons to whom the Software is furnished to do so, subject to the fol-
10# lowing conditions:
11#
12# The above copyright notice and this permission notice shall be included
13# in all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
17# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
18# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21# IN THE SOFTWARE.
22
23import uuid
24import hashlib
25
26from boto.connection import AWSQueryConnection
27from boto.regioninfo import RegionInfo
28from boto.compat import json
29import boto
30
31
32class SNSConnection(AWSQueryConnection):
33    """
34    Amazon Simple Notification Service
35    Amazon Simple Notification Service (Amazon SNS) is a web service
36    that enables you to build distributed web-enabled applications.
37    Applications can use Amazon SNS to easily push real-time
38    notification messages to interested subscribers over multiple
39    delivery protocols. For more information about this product see
40    `http://aws.amazon.com/sns`_. For detailed information about
41    Amazon SNS features and their associated API calls, see the
42    `Amazon SNS Developer Guide`_.
43
44    We also provide SDKs that enable you to access Amazon SNS from
45    your preferred programming language. The SDKs contain
46    functionality that automatically takes care of tasks such as:
47    cryptographically signing your service requests, retrying
48    requests, and handling error responses. For a list of available
49    SDKs, go to `Tools for Amazon Web Services`_.
50    """
51    DefaultRegionName = boto.config.get('Boto', 'sns_region_name', 'us-east-1')
52    DefaultRegionEndpoint = boto.config.get('Boto', 'sns_region_endpoint',
53                                            'sns.us-east-1.amazonaws.com')
54    APIVersion = boto.config.get('Boto', 'sns_version', '2010-03-31')
55
56
57    def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
58                 is_secure=True, port=None, proxy=None, proxy_port=None,
59                 proxy_user=None, proxy_pass=None, debug=0,
60                 https_connection_factory=None, region=None, path='/',
61                 security_token=None, validate_certs=True,
62                 profile_name=None):
63        if not region:
64            region = RegionInfo(self, self.DefaultRegionName,
65                                self.DefaultRegionEndpoint,
66                                connection_cls=SNSConnection)
67        self.region = region
68        super(SNSConnection, self).__init__(aws_access_key_id,
69                                    aws_secret_access_key,
70                                    is_secure, port, proxy, proxy_port,
71                                    proxy_user, proxy_pass,
72                                    self.region.endpoint, debug,
73                                    https_connection_factory, path,
74                                    security_token=security_token,
75                                    validate_certs=validate_certs,
76                                    profile_name=profile_name)
77
78    def _build_dict_as_list_params(self, params, dictionary, name):
79      """
80            Serialize a parameter 'name' which value is a 'dictionary' into a list of parameters.
81
82            See: http://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html
83            For example::
84
85                dictionary = {'PlatformPrincipal': 'foo', 'PlatformCredential': 'bar'}
86                name = 'Attributes'
87
88            would result in params dict being populated with:
89                Attributes.entry.1.key    = PlatformPrincipal
90                Attributes.entry.1.value  = foo
91                Attributes.entry.2.key    = PlatformCredential
92                Attributes.entry.2.value  = bar
93
94      :param params: the resulting parameters will be added to this dict
95      :param dictionary: dict - value of the serialized parameter
96      :param name: name of the serialized parameter
97      """
98      items = sorted(dictionary.items(), key=lambda x:x[0])
99      for kv, index in zip(items, list(range(1, len(items)+1))):
100        key, value = kv
101        prefix = '%s.entry.%s' % (name, index)
102        params['%s.key' % prefix] = key
103        params['%s.value' % prefix] = value
104
105    def _required_auth_capability(self):
106        return ['hmac-v4']
107
108    def get_all_topics(self, next_token=None):
109        """
110        :type next_token: string
111        :param next_token: Token returned by the previous call to
112                           this method.
113
114        """
115        params = {}
116        if next_token:
117            params['NextToken'] = next_token
118        return self._make_request('ListTopics', params)
119
120    def get_topic_attributes(self, topic):
121        """
122        Get attributes of a Topic
123
124        :type topic: string
125        :param topic: The ARN of the topic.
126
127        """
128        params = {'TopicArn': topic}
129        return self._make_request('GetTopicAttributes', params)
130
131    def set_topic_attributes(self, topic, attr_name, attr_value):
132        """
133        Get attributes of a Topic
134
135        :type topic: string
136        :param topic: The ARN of the topic.
137
138        :type attr_name: string
139        :param attr_name: The name of the attribute you want to set.
140                          Only a subset of the topic's attributes are mutable.
141                          Valid values: Policy | DisplayName
142
143        :type attr_value: string
144        :param attr_value: The new value for the attribute.
145
146        """
147        params = {'TopicArn': topic,
148                  'AttributeName': attr_name,
149                  'AttributeValue': attr_value}
150        return self._make_request('SetTopicAttributes', params)
151
152    def add_permission(self, topic, label, account_ids, actions):
153        """
154        Adds a statement to a topic's access control policy, granting
155        access for the specified AWS accounts to the specified actions.
156
157        :type topic: string
158        :param topic: The ARN of the topic.
159
160        :type label: string
161        :param label: A unique identifier for the new policy statement.
162
163        :type account_ids: list of strings
164        :param account_ids: The AWS account ids of the users who will be
165                            give access to the specified actions.
166
167        :type actions: list of strings
168        :param actions: The actions you want to allow for each of the
169                        specified principal(s).
170
171        """
172        params = {'TopicArn': topic,
173                  'Label': label}
174        self.build_list_params(params, account_ids, 'AWSAccountId.member')
175        self.build_list_params(params, actions, 'ActionName.member')
176        return self._make_request('AddPermission', params)
177
178    def remove_permission(self, topic, label):
179        """
180        Removes a statement from a topic's access control policy.
181
182        :type topic: string
183        :param topic: The ARN of the topic.
184
185        :type label: string
186        :param label: A unique identifier for the policy statement
187                      to be removed.
188
189        """
190        params = {'TopicArn': topic,
191                  'Label': label}
192        return self._make_request('RemovePermission', params)
193
194    def create_topic(self, topic):
195        """
196        Create a new Topic.
197
198        :type topic: string
199        :param topic: The name of the new topic.
200
201        """
202        params = {'Name': topic}
203        return self._make_request('CreateTopic', params)
204
205    def delete_topic(self, topic):
206        """
207        Delete an existing topic
208
209        :type topic: string
210        :param topic: The ARN of the topic
211
212        """
213        params = {'TopicArn': topic}
214        return self._make_request('DeleteTopic', params, '/', 'GET')
215
216    def publish(self, topic=None, message=None, subject=None, target_arn=None,
217                message_structure=None, message_attributes=None):
218        """
219        Get properties of a Topic
220
221        :type topic: string
222        :param topic: The ARN of the new topic.
223
224        :type message: string
225        :param message: The message you want to send to the topic.
226                        Messages must be UTF-8 encoded strings and
227                        be at most 4KB in size.
228
229        :type message_structure: string
230        :param message_structure: Optional parameter. If left as ``None``,
231                                  plain text will be sent. If set to ``json``,
232                                  your message should be a JSON string that
233                                  matches the structure described at
234                                  http://docs.aws.amazon.com/sns/latest/dg/PublishTopic.html#sns-message-formatting-by-protocol
235
236        :type message_attributes: dict
237        :param message_attributes: Message attributes to set. Should be
238            of the form:
239
240            .. code-block:: python
241
242                {
243                    "name1": {
244                        "data_type": "Number",
245                        "string_value": "42"
246                    },
247                    "name2": {
248                        "data_type": "String",
249                        "string_value": "Bob"
250                    }
251                }
252
253        :type subject: string
254        :param subject: Optional parameter to be used as the "Subject"
255                        line of the email notifications.
256
257        :type target_arn: string
258        :param target_arn: Optional parameter for either TopicArn or
259                           EndpointArn, but not both.
260
261        """
262        if message is None:
263            # To be backwards compatible when message did not have
264            # a default value and topic and message were required
265            # args.
266            raise TypeError("'message' is a required parameter")
267        params = {'Message': message}
268        if subject is not None:
269            params['Subject'] = subject
270        if topic is not None:
271            params['TopicArn'] = topic
272        if target_arn is not None:
273            params['TargetArn'] = target_arn
274        if message_structure is not None:
275            params['MessageStructure'] = message_structure
276        if message_attributes is not None:
277            keys = sorted(message_attributes.keys())
278            for i, name in enumerate(keys, start=1):
279                attribute = message_attributes[name]
280                params['MessageAttributes.entry.{0}.Name'.format(i)] = name
281                if 'data_type' in attribute:
282                    params['MessageAttributes.entry.{0}.Value.DataType'.format(i)] = \
283                        attribute['data_type']
284                if 'string_value' in attribute:
285                    params['MessageAttributes.entry.{0}.Value.StringValue'.format(i)] = \
286                        attribute['string_value']
287                if 'binary_value' in attribute:
288                    params['MessageAttributes.entry.{0}.Value.BinaryValue'.format(i)] = \
289                        attribute['binary_value']
290        return self._make_request('Publish', params, '/', 'POST')
291
292    def subscribe(self, topic, protocol, endpoint):
293        """
294        Subscribe to a Topic.
295
296        :type topic: string
297        :param topic: The ARN of the new topic.
298
299        :type protocol: string
300        :param protocol: The protocol used to communicate with
301                         the subscriber.  Current choices are:
302                         email|email-json|http|https|sqs|sms|application
303
304        :type endpoint: string
305        :param endpoint: The location of the endpoint for
306                         the subscriber.
307                         * For email, this would be a valid email address
308                         * For email-json, this would be a valid email address
309                         * For http, this would be a URL beginning with http
310                         * For https, this would be a URL beginning with https
311                         * For sqs, this would be the ARN of an SQS Queue
312                         * For sms, this would be a phone number of an
313                           SMS-enabled device
314                         * For application, the endpoint is the EndpointArn
315                           of a mobile app and device.
316        """
317        params = {'TopicArn': topic,
318                  'Protocol': protocol,
319                  'Endpoint': endpoint}
320        return self._make_request('Subscribe', params)
321
322    def subscribe_sqs_queue(self, topic, queue):
323        """
324        Subscribe an SQS queue to a topic.
325
326        This is convenience method that handles most of the complexity involved
327        in using an SQS queue as an endpoint for an SNS topic.  To achieve this
328        the following operations are performed:
329
330        * The correct ARN is constructed for the SQS queue and that ARN is
331          then subscribed to the topic.
332        * A JSON policy document is contructed that grants permission to
333          the SNS topic to send messages to the SQS queue.
334        * This JSON policy is then associated with the SQS queue using
335          the queue's set_attribute method.  If the queue already has
336          a policy associated with it, this process will add a Statement to
337          that policy.  If no policy exists, a new policy will be created.
338
339        :type topic: string
340        :param topic: The ARN of the new topic.
341
342        :type queue: A boto Queue object
343        :param queue: The queue you wish to subscribe to the SNS Topic.
344        """
345        t = queue.id.split('/')
346        q_arn = queue.arn
347        sid = hashlib.md5((topic + q_arn).encode('utf-8')).hexdigest()
348        sid_exists = False
349        resp = self.subscribe(topic, 'sqs', q_arn)
350        attr = queue.get_attributes('Policy')
351        if 'Policy' in attr:
352            policy = json.loads(attr['Policy'])
353        else:
354            policy = {}
355        if 'Version' not in policy:
356            policy['Version'] = '2008-10-17'
357        if 'Statement' not in policy:
358            policy['Statement'] = []
359        # See if a Statement with the Sid exists already.
360        for s in policy['Statement']:
361            if s['Sid'] == sid:
362                sid_exists = True
363        if not sid_exists:
364            statement = {'Action': 'SQS:SendMessage',
365                         'Effect': 'Allow',
366                         'Principal': {'AWS': '*'},
367                         'Resource': q_arn,
368                         'Sid': sid,
369                         'Condition': {'StringLike': {'aws:SourceArn': topic}}}
370            policy['Statement'].append(statement)
371        queue.set_attribute('Policy', json.dumps(policy))
372        return resp
373
374    def confirm_subscription(self, topic, token,
375                             authenticate_on_unsubscribe=False):
376        """
377        Get properties of a Topic
378
379        :type topic: string
380        :param topic: The ARN of the new topic.
381
382        :type token: string
383        :param token: Short-lived token sent to and endpoint during
384                      the Subscribe operation.
385
386        :type authenticate_on_unsubscribe: bool
387        :param authenticate_on_unsubscribe: Optional parameter indicating
388                                            that you wish to disable
389                                            unauthenticated unsubscription
390                                            of the subscription.
391
392        """
393        params = {'TopicArn': topic, 'Token': token}
394        if authenticate_on_unsubscribe:
395            params['AuthenticateOnUnsubscribe'] = 'true'
396        return self._make_request('ConfirmSubscription', params)
397
398    def unsubscribe(self, subscription):
399        """
400        Allows endpoint owner to delete subscription.
401        Confirmation message will be delivered.
402
403        :type subscription: string
404        :param subscription: The ARN of the subscription to be deleted.
405
406        """
407        params = {'SubscriptionArn': subscription}
408        return self._make_request('Unsubscribe', params)
409
410    def get_all_subscriptions(self, next_token=None):
411        """
412        Get list of all subscriptions.
413
414        :type next_token: string
415        :param next_token: Token returned by the previous call to
416                           this method.
417
418        """
419        params = {}
420        if next_token:
421            params['NextToken'] = next_token
422        return self._make_request('ListSubscriptions', params)
423
424    def get_all_subscriptions_by_topic(self, topic, next_token=None):
425        """
426        Get list of all subscriptions to a specific topic.
427
428        :type topic: string
429        :param topic: The ARN of the topic for which you wish to
430                      find subscriptions.
431
432        :type next_token: string
433        :param next_token: Token returned by the previous call to
434                           this method.
435
436        """
437        params = {'TopicArn': topic}
438        if next_token:
439            params['NextToken'] = next_token
440        return self._make_request('ListSubscriptionsByTopic', params)
441
442    def create_platform_application(self, name=None, platform=None,
443                                    attributes=None):
444        """
445        The `CreatePlatformApplication` action creates a platform
446        application object for one of the supported push notification
447        services, such as APNS and GCM, to which devices and mobile
448        apps may register. You must specify PlatformPrincipal and
449        PlatformCredential attributes when using the
450        `CreatePlatformApplication` action. The PlatformPrincipal is
451        received from the notification service. For APNS/APNS_SANDBOX,
452        PlatformPrincipal is "SSL certificate". For GCM,
453        PlatformPrincipal is not applicable. For ADM,
454        PlatformPrincipal is "client id". The PlatformCredential is
455        also received from the notification service. For
456        APNS/APNS_SANDBOX, PlatformCredential is "private key". For
457        GCM, PlatformCredential is "API key". For ADM,
458        PlatformCredential is "client secret". The
459        PlatformApplicationArn that is returned when using
460        `CreatePlatformApplication` is then used as an attribute for
461        the `CreatePlatformEndpoint` action. For more information, see
462        `Using Amazon SNS Mobile Push Notifications`_.
463
464        :type name: string
465        :param name: Application names must be made up of only uppercase and
466            lowercase ASCII letters, numbers, underscores, hyphens, and
467            periods, and must be between 1 and 256 characters long.
468
469        :type platform: string
470        :param platform: The following platforms are supported: ADM (Amazon
471            Device Messaging), APNS (Apple Push Notification Service),
472            APNS_SANDBOX, and GCM (Google Cloud Messaging).
473
474        :type attributes: map
475        :param attributes: For a list of attributes, see
476            `SetPlatformApplicationAttributes`_
477
478        """
479        params = {}
480        if name is not None:
481            params['Name'] = name
482        if platform is not None:
483            params['Platform'] = platform
484        if attributes is not None:
485            self._build_dict_as_list_params(params, attributes, 'Attributes')
486        return self._make_request(action='CreatePlatformApplication',
487                                  params=params)
488
489    def set_platform_application_attributes(self,
490                                            platform_application_arn=None,
491                                            attributes=None):
492        """
493        The `SetPlatformApplicationAttributes` action sets the
494        attributes of the platform application object for the
495        supported push notification services, such as APNS and GCM.
496        For more information, see `Using Amazon SNS Mobile Push
497        Notifications`_.
498
499        :type platform_application_arn: string
500        :param platform_application_arn: PlatformApplicationArn for
501            SetPlatformApplicationAttributes action.
502
503        :type attributes: map
504        :param attributes:
505        A map of the platform application attributes. Attributes in this map
506            include the following:
507
508
509        + `PlatformCredential` -- The credential received from the notification
510              service. For APNS/APNS_SANDBOX, PlatformCredential is "private
511              key". For GCM, PlatformCredential is "API key". For ADM,
512              PlatformCredential is "client secret".
513        + `PlatformPrincipal` -- The principal received from the notification
514              service. For APNS/APNS_SANDBOX, PlatformPrincipal is "SSL
515              certificate". For GCM, PlatformPrincipal is not applicable. For
516              ADM, PlatformPrincipal is "client id".
517        + `EventEndpointCreated` -- Topic ARN to which EndpointCreated event
518              notifications should be sent.
519        + `EventEndpointDeleted` -- Topic ARN to which EndpointDeleted event
520              notifications should be sent.
521        + `EventEndpointUpdated` -- Topic ARN to which EndpointUpdate event
522              notifications should be sent.
523        + `EventDeliveryFailure` -- Topic ARN to which DeliveryFailure event
524              notifications should be sent upon Direct Publish delivery failure
525              (permanent) to one of the application's endpoints.
526
527        """
528        params = {}
529        if platform_application_arn is not None:
530            params['PlatformApplicationArn'] = platform_application_arn
531        if attributes is not None:
532            self._build_dict_as_list_params(params, attributes, 'Attributes')
533        return self._make_request(action='SetPlatformApplicationAttributes',
534                                  params=params)
535
536    def get_platform_application_attributes(self,
537                                            platform_application_arn=None):
538        """
539        The `GetPlatformApplicationAttributes` action retrieves the
540        attributes of the platform application object for the
541        supported push notification services, such as APNS and GCM.
542        For more information, see `Using Amazon SNS Mobile Push
543        Notifications`_.
544
545        :type platform_application_arn: string
546        :param platform_application_arn: PlatformApplicationArn for
547            GetPlatformApplicationAttributesInput.
548
549        """
550        params = {}
551        if platform_application_arn is not None:
552            params['PlatformApplicationArn'] = platform_application_arn
553        return self._make_request(action='GetPlatformApplicationAttributes',
554                                  params=params)
555
556    def list_platform_applications(self, next_token=None):
557        """
558        The `ListPlatformApplications` action lists the platform
559        application objects for the supported push notification
560        services, such as APNS and GCM. The results for
561        `ListPlatformApplications` are paginated and return a limited
562        list of applications, up to 100. If additional records are
563        available after the first page results, then a NextToken
564        string will be returned. To receive the next page, you call
565        `ListPlatformApplications` using the NextToken string received
566        from the previous call. When there are no more records to
567        return, NextToken will be null. For more information, see
568        `Using Amazon SNS Mobile Push Notifications`_.
569
570        :type next_token: string
571        :param next_token: NextToken string is used when calling
572            ListPlatformApplications action to retrieve additional records that
573            are available after the first page results.
574
575        """
576        params = {}
577        if next_token is not None:
578            params['NextToken'] = next_token
579        return self._make_request(action='ListPlatformApplications',
580                                  params=params)
581
582    def list_endpoints_by_platform_application(self,
583                                               platform_application_arn=None,
584                                               next_token=None):
585        """
586        The `ListEndpointsByPlatformApplication` action lists the
587        endpoints and endpoint attributes for devices in a supported
588        push notification service, such as GCM and APNS. The results
589        for `ListEndpointsByPlatformApplication` are paginated and
590        return a limited list of endpoints, up to 100. If additional
591        records are available after the first page results, then a
592        NextToken string will be returned. To receive the next page,
593        you call `ListEndpointsByPlatformApplication` again using the
594        NextToken string received from the previous call. When there
595        are no more records to return, NextToken will be null. For
596        more information, see `Using Amazon SNS Mobile Push
597        Notifications`_.
598
599        :type platform_application_arn: string
600        :param platform_application_arn: PlatformApplicationArn for
601            ListEndpointsByPlatformApplicationInput action.
602
603        :type next_token: string
604        :param next_token: NextToken string is used when calling
605            ListEndpointsByPlatformApplication action to retrieve additional
606            records that are available after the first page results.
607
608        """
609        params = {}
610        if platform_application_arn is not None:
611            params['PlatformApplicationArn'] = platform_application_arn
612        if next_token is not None:
613            params['NextToken'] = next_token
614        return self._make_request(action='ListEndpointsByPlatformApplication',
615                                  params=params)
616
617    def delete_platform_application(self, platform_application_arn=None):
618        """
619        The `DeletePlatformApplication` action deletes a platform
620        application object for one of the supported push notification
621        services, such as APNS and GCM. For more information, see
622        `Using Amazon SNS Mobile Push Notifications`_.
623
624        :type platform_application_arn: string
625        :param platform_application_arn: PlatformApplicationArn of platform
626            application object to delete.
627
628        """
629        params = {}
630        if platform_application_arn is not None:
631            params['PlatformApplicationArn'] = platform_application_arn
632        return self._make_request(action='DeletePlatformApplication',
633                                  params=params)
634
635    def create_platform_endpoint(self, platform_application_arn=None,
636                                 token=None, custom_user_data=None,
637                                 attributes=None):
638        """
639        The `CreatePlatformEndpoint` creates an endpoint for a device
640        and mobile app on one of the supported push notification
641        services, such as GCM and APNS. `CreatePlatformEndpoint`
642        requires the PlatformApplicationArn that is returned from
643        `CreatePlatformApplication`. The EndpointArn that is returned
644        when using `CreatePlatformEndpoint` can then be used by the
645        `Publish` action to send a message to a mobile app or by the
646        `Subscribe` action for subscription to a topic. For more
647        information, see `Using Amazon SNS Mobile Push
648        Notifications`_.
649
650        :type platform_application_arn: string
651        :param platform_application_arn: PlatformApplicationArn returned from
652            CreatePlatformApplication is used to create a an endpoint.
653
654        :type token: string
655        :param token: Unique identifier created by the notification service for
656            an app on a device. The specific name for Token will vary,
657            depending on which notification service is being used. For example,
658            when using APNS as the notification service, you need the device
659            token. Alternatively, when using GCM or ADM, the device token
660            equivalent is called the registration ID.
661
662        :type custom_user_data: string
663        :param custom_user_data: Arbitrary user data to associate with the
664            endpoint. SNS does not use this data. The data must be in UTF-8
665            format and less than 2KB.
666
667        :type attributes: map
668        :param attributes: For a list of attributes, see
669            `SetEndpointAttributes`_.
670
671        """
672        params = {}
673        if platform_application_arn is not None:
674            params['PlatformApplicationArn'] = platform_application_arn
675        if token is not None:
676            params['Token'] = token
677        if custom_user_data is not None:
678            params['CustomUserData'] = custom_user_data
679        if attributes is not None:
680            self._build_dict_as_list_params(params, attributes, 'Attributes')
681        return self._make_request(action='CreatePlatformEndpoint',
682                                  params=params)
683
684    def delete_endpoint(self, endpoint_arn=None):
685        """
686        The `DeleteEndpoint` action, which is idempotent, deletes the
687        endpoint from SNS. For more information, see `Using Amazon SNS
688        Mobile Push Notifications`_.
689
690        :type endpoint_arn: string
691        :param endpoint_arn: EndpointArn of endpoint to delete.
692
693        """
694        params = {}
695        if endpoint_arn is not None:
696            params['EndpointArn'] = endpoint_arn
697        return self._make_request(action='DeleteEndpoint', params=params)
698
699    def set_endpoint_attributes(self, endpoint_arn=None, attributes=None):
700        """
701        The `SetEndpointAttributes` action sets the attributes for an
702        endpoint for a device on one of the supported push
703        notification services, such as GCM and APNS. For more
704        information, see `Using Amazon SNS Mobile Push
705        Notifications`_.
706
707        :type endpoint_arn: string
708        :param endpoint_arn: EndpointArn used for SetEndpointAttributes action.
709
710        :type attributes: map
711        :param attributes:
712        A map of the endpoint attributes. Attributes in this map include the
713            following:
714
715
716        + `CustomUserData` -- arbitrary user data to associate with the
717              endpoint. SNS does not use this data. The data must be in UTF-8
718              format and less than 2KB.
719        + `Enabled` -- flag that enables/disables delivery to the endpoint.
720              Message Processor will set this to false when a notification
721              service indicates to SNS that the endpoint is invalid. Users can
722              set it back to true, typically after updating Token.
723        + `Token` -- device token, also referred to as a registration id, for
724              an app and mobile device. This is returned from the notification
725              service when an app and mobile device are registered with the
726              notification service.
727
728        """
729        params = {}
730        if endpoint_arn is not None:
731            params['EndpointArn'] = endpoint_arn
732        if attributes is not None:
733            self._build_dict_as_list_params(params, attributes, 'Attributes')
734        return self._make_request(action='SetEndpointAttributes',
735                                  params=params)
736
737    def get_endpoint_attributes(self, endpoint_arn=None):
738        """
739        The `GetEndpointAttributes` retrieves the endpoint attributes
740        for a device on one of the supported push notification
741        services, such as GCM and APNS. For more information, see
742        `Using Amazon SNS Mobile Push Notifications`_.
743
744        :type endpoint_arn: string
745        :param endpoint_arn: EndpointArn for GetEndpointAttributes input.
746
747        """
748        params = {}
749        if endpoint_arn is not None:
750            params['EndpointArn'] = endpoint_arn
751        return self._make_request(action='GetEndpointAttributes',
752                                  params=params)
753
754    def _make_request(self, action, params, path='/', verb='GET'):
755        params['ContentType'] = 'JSON'
756        response = self.make_request(action=action, verb=verb,
757                                     path=path, params=params)
758        body = response.read().decode('utf-8')
759        boto.log.debug(body)
760        if response.status == 200:
761            return json.loads(body)
762        else:
763            boto.log.error('%s %s' % (response.status, response.reason))
764            boto.log.error('%s' % body)
765            raise self.ResponseError(response.status, response.reason, body)
766