Esempio n. 1
0
    def send(self, device_key, data):
        if not self.connection:
            self.establish_connection()

        payload = apns.Payload(alert=data.pop('alert', None),
                               sound=data.pop('sound', None),
                               badge=data.pop('badge', None),
                               category=data.pop('category', None),
                               content_available=bool(
                                   data.pop('content-available', False)),
                               custom=data or {})

        event = self._send_notification(device_key, payload)

        status = event.wait_for_response(1.5)

        if status in (self.STATUS_CODE_INVALID_TOKEN,
                      self.STATUS_CODE_INVALID_TOKEN_SIZE):
            push_result = self.PUSH_RESULT_NOT_REGISTERED
        elif status == self.STATUS_CODE_NO_ERROR:
            push_result = self.PUSH_RESULT_SENT
        else:
            push_result = self.PUSH_RESULT_EXCEPTION

        return push_result, 0
Esempio n. 2
0
 def post_fetch((cmds, resps)):
     """Post fetch callback."""
     try:
         for msg in resps[0][1]['list']:
             logger.debug("Preparing msg to send: %s", msg)
             from1 = msg['from'][0]
             from_name = from1.get('name') or from1.get(
                 'email', '<unknown>')
             notification = "%s - %s" % (from_name, msg['subject'])
             payload = apns.Payload(notification,
                                    sound='default',
                                    badge=1)
             if self._pushtoken:
                 logger.info("Sending push notification: %s", payload)
                 try:
                     self._apns.gateway_server.send_notification(
                         self._pushtoken, payload)
                 except Exception as e:
                     logger.error("Error sending push notification: %s",
                                  e)
                     raise
             else:
                 logger.info(
                     "-- push notification would be sent: %s --",
                     payload)
     except Exception as e:
         logger.error("Error: %s", e)
         raise
Esempio n. 3
0
    def _route(self, notification, router_data):
        """Blocking APNS call to route the notification"""
        token = router_data["token"]
        custom = {
            "Chid": notification.channel_id,
            "Ver": notification.version,
        }
        if notification.data:
            custom["Msg"] = notification.data
            custom["Con"] = notification.headers["content-encoding"]
            custom["Enc"] = notification.headers["encryption"]

            if "crypto-key" in notification.headers:
                custom["Cryptokey"] = notification.headers["crypto-key"]
            elif "encryption-key" in notification.headers:
                custom["Enckey"] = notification.headers["encryption-key"]

        payload = apns.Payload(alert=router_data.get("title",
                                                     self.default_title),
                               content_available=1,
                               custom=custom)
        now = int(time.time())
        self.messages[now] = {"token": token, "payload": payload}
        # TODO: Add listener for error handling.
        self.apns.gateway_server.register_response_listener(self._error)
        self.apns.gateway_server.send_notification(token, payload, now)

        # cleanup sent messages
        if self.messages:
            for time_sent in self.messages.keys():
                if time_sent < now - self.config.get("expry", 10):
                    del self.messages[time_sent]
        return RouterResponse(status_code=200, response_body="Message sent")
Esempio n. 4
0
def push(msg):
    pem = 'apns-prod.pem'
    token = msg['udid']
    data = msg['data']
    payload = apns.Payload(data['alert'], data['badge'], data['sid'],
                           data['sj'])
    # payload = {
    #     'aps': {
    #         'alert': "This is Message!",
    #         'sound': 'hello.caf',
    #         'badge': 123456,
    #     },
    #     'cam': 1,
    #     'sid': 'F28E006B438F90F5FD11BDADF64BDB13',
    #     'sj':'This is the title!',
    # }
    return apns.APN(token, payload, pem)
Esempio n. 5
0
    def post(self):  # pylint: disable=no-self-use
        res = self.handle_input(api_args.IOS)
        if isinstance(res, flask.Response):
            return res

        logging.info('Pushing APNs notifications to %s devices',
                     len(flask.request.devices))
        kwargs = api_utils.apns_payload_data(flask.request.sender_name,
                                             flask.request.message_type,
                                             flask.request.message_id)
        payload = apns.Payload(**kwargs)

        for device in flask.request.devices:
            # Note: For every device it creates a new connection to send
            #       notification. This is inefficient and should be fixed.
            apns_socket = api_utils.create_apns_socket(current_app)
            apns_socket.gateway_server.send_notification(
                device.device_key, payload)

        # Note: For unknown reasons send multiple notifications stopped working
        #       on App Engine both for new and legacy enhanced notification
        #       format: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html  # pylint: disable=line-too-long

        # import random
        # import time
        # frame = apns.Frame()
        # expiry = time.time() + 3600
        # priority = 10
        # for device in flask.request.devices:
        #     identifier = random.getrandbits(32)
        #     frame.add_item(
        #         device.device_key, payload, identifier, expiry, priority)
        # apns_socket = api_utils.create_apns_socket(current_app)
        # apns_socket.gateway_server.send_notification_multiple(frame)

        msg = 'Notification to APNs is pushed'
        logging.info(msg)
        return msg
Esempio n. 6
0
 def prepare_notification(self, notification_type, device, owner, message,
                          os):
     alert = None
     content_available = False
     badge = None
     sound = None
     if notification_type == PEER_TRANSACTION:
         sender_id = str(message['sender_id'])
         recipient_id = str(message['recipient_id'])
         status = int(message['status'])
         is_sender = \
           (str(owner) == sender_id) and (device == message['sender_device_id'])
         is_recipient = str(owner) == recipient_id
         if is_sender:
             sender_statuses = [
                 transaction_status.REJECTED,
                 transaction_status.FINISHED,
             ]
             if status not in sender_statuses:
                 return None
         elif is_recipient:
             recipient_statuses = [
                 transaction_status.INITIALIZED,
                 transaction_status.ACCEPTED,
                 transaction_status.REJECTED,
                 transaction_status.FAILED,
             ]
             if status not in recipient_statuses:
                 return None
         else:
             return None
         if sender_id == recipient_id:
             to_self = True
         else:
             to_self = False
         if message['files_count'] == 1:
             files = 'file'
         else:
             files = 'files'
         if is_recipient:
             badge = self._user_device_receivable_transactions_count(
                 owner, device)
             if status is transaction_status.INITIALIZED:
                 sound = 'default'
                 if to_self:
                     if message['recipient_device_id'] == device:
                         alert = 'Open Infinit for the transfer to begin'
                     elif message['recipient_device_id'] == '':
                         alert = 'Accept transfer from another device'
                 else:
                     alert = 'Accept transfer from %s' % message[
                         'sender_fullname']
         elif is_sender:
             if status is transaction_status.REJECTED:
                 if not to_self:
                     alert = 'Canceled by %s' % message['recipient_fullname']
             elif status is transaction_status.FINISHED:
                 if to_self:
                     alert = 'Transfer received'
                 else:
                     alert = 'Transfer received by %s' % message[
                         'recipient_fullname']
         if alert is None and badge is None:
             return None
         if os == 'iOS':
             return apns.Payload(alert=alert,
                                 badge=badge,
                                 sound=sound,
                                 content_available=content_available)
         elif os == 'Android':
             return {'title': 'Infinit', 'message': alert}
         else:
             return None
     elif notification_type == NEW_SWAGGER:
         if 'contact_email' not in message:
             return None
         alert = 'Your contact %s (%s) joined Infinit' % \
                 (message['contact_fullname'], message['contact_email'])
         if os == 'iOS':
             return apns.Payload(alert=alert,
                                 badge=badge,
                                 sound=sound,
                                 content_available=content_available)
         else:
             return {'title': 'Infinit', 'message': alert}
     else:
         return None