Beispiel #1
0
def send_push(api_key, data):
    response_list = {Field.SUCCESS: {}, Field.ERRORS: {}}

    for key in api_key:
        try:
            gcm = GCM(key)
            total_of_gcm_ids = len(api_key[key])
            start = 0
            end = 1000

            if total_of_gcm_ids >= Constants.LIMIT_OF_PLAYERS_TO_SEND_PUSH:
                while total_of_gcm_ids > 0:
                    response = gcm.json_request(
                        registration_ids=api_key[key][start:end], data=data)
                    response_list = list_results_from_push_notification_response(
                        response=response, response_list=response_list)
                    start = end
                    end += Constants.LIMIT_OF_PLAYERS_TO_SEND_PUSH
                    total_of_gcm_ids -= Constants.LIMIT_OF_PLAYERS_TO_SEND_PUSH

            else:
                response = gcm.json_request(registration_ids=api_key[key],
                                            data=data)
                response_list = list_results_from_push_notification_response(
                    response=response, response_list=response_list)
        except Exception:
            response_list = push_notification_exception_treatment(
                response_list, api_key[key])
    return response_list
Beispiel #2
0
 def gcm_request(self, notification, max_retries = 10):
     from gcm.gcm import GCM, GCMConnectionException, GCMUnavailableException, GCMAuthenticationException
     from settings import GOOGLE_GCM_API_KEY 
     from coresql.models import UserProfile
     
     logger.info("[GCMClientThread] Handling request for notification: " + str(notification))
     
     gcm_client = GCM(GOOGLE_GCM_API_KEY)
     registration_ids, collapse_key, delay_while_idle, ttl, data = notification
     
     try:
         response = gcm_client.json_request(registration_ids, data = data,
                                        collapse_key = collapse_key, 
                                        delay_while_idle = delay_while_idle,
                                        time_to_live = ttl,
                                        retries = max_retries)
         
         # Handling errors
         if 'errors' in response:
             for error, reg_ids in response['errors'].items():
                 # Check for errors and act accordingly
                 if error in ['NotRegistered', 'InvalidRegistration']:
                     # Remove reg_ids from database
                     for reg_id in reg_ids:
                         """
                         Either the owner has turned off notifications (NotRegistered) or 
                         there is a problem with the registration_id (InvalidRegistration).
                         In both cases, log the error and set the corresponding registration_id to null in the UserProfile
                         """
                         try:
                             user_profile = UserProfile.objects.get(c2dm_id = reg_id)
                             user_profile.c2dm_id = None
                             user_profile.save()
                         except Exception:
                             pass
                         
                         logger.error("[GCM " + error + " ERROR] Encountered at notification request: " 
                                      + str(notification))
                 else:
                     """
                     Any other error that should normally not be encountered because of the internal business logic: 
                     MissingRegistration, MismatchSenderId, MessageTooBig, MissingCollapseKey 
                     """
                     logger.error("[GCM " + error + " ERROR] Encountered at notification request: " 
                                  + str(notification))
             
         if 'canonical' in response:
             for canonical_id, reg_id in response['canonical'].items():
                 # Repace reg_id with canonical_id in your database
                 try:
                     user_profile = UserProfile.objects.get(c2dm_id=reg_id)
                     user_profile.c2dm_id = canonical_id
                     user_profile.save()
                 except Exception:
                     pass
         
         logger.info("[GCM INFO] Finished processing GCM notifications: " + str(notification))
         
     except GCMConnectionException, e:
         logger.critical("[GCM EXCEPTION] Connection error at GCM request (" + str(notification) + "): " + str(e))
Beispiel #3
0
def send_gcm_message(device, app, message_type, data=None):
    """
    Send a Google Cloud Messaging message.
    """
    token_list = [device.token]
    unique_key = device.token

    key = '%d-cycle.key' % int(time())
    if message_type == TYPE_CALL:
        unique_key = data['unique_key']
        message = get_call_push_payload(
            unique_key,
            data['phonenumber'],
            data['caller_id'],
            data['attempt'],
        )
    elif message_type == TYPE_MESSAGE:
        message = get_message_push_payload(data['message'])
    else:
        log_middleware_information(
            '{0} | Trying to sent message of unknown type: {1}',
            OrderedDict([
                ('unique_key', unique_key),
                ('message_type', message_type),
            ]),
            logging.WARNING,
            device=device,
        )

    gcm = GCM(app.push_key)

    try:
        start_time = time()
        response = gcm.json_request(
            registration_ids=token_list,
            data=message,
            collapse_key=key,
            priority='high',
        )

        success = response.get('success')
        canonical = response.get('canonical')
        errors = response.get('errors')

        if success:
            for reg_id, msg_id in success.items():
                log_middleware_information(
                    '{0} | GCM \'{1}\' message sent at time:{2} to {3}',
                    OrderedDict([
                        ('unique_key', unique_key),
                        ('message_type', message_type),
                        ('sent_time',
                         datetime.datetime.fromtimestamp(start_time).strftime(
                             '%H:%M:%S.%f')),
                        ('registration_id', reg_id),
                    ]),
                    logging.INFO,
                    device=device,
                )

        if canonical:
            for reg_id, new_reg_id in canonical.items():
                log_middleware_information(
                    '{0} | Should replace device token {1} with {2} in database',
                    OrderedDict([
                        ('unique_key', unique_key),
                        ('registration_id', reg_id),
                        ('new_registration_id', new_reg_id),
                    ]),
                    logging.WARNING,
                    device=device,
                )

        if errors:
            for err_code, reg_id in errors.items():
                log_middleware_information(
                    '{0} | Should remove {1} because {2}',
                    OrderedDict([
                        ('unique_key', unique_key),
                        ('registration_id', reg_id),
                        ('error_code', err_code),
                    ]),
                    logging.WARNING,
                    device=device,
                )

    except GCMAuthenticationException:
        # Stop and fix your settings.
        log_middleware_information(
            '{0} | Our Google API key was rejected!!!',
            OrderedDict([
                ('unique_key', unique_key),
            ]),
            logging.ERROR,
            device=device,
        )
    except ValueError:
        # Probably your extra options, such as time_to_live,
        # are invalid. Read error message for more info.
        log_middleware_information(
            '{0} | Invalid message/option or invalid GCM response',
            OrderedDict([
                ('unique_key', unique_key),
            ]),
            logging.ERROR,
            device=device,
        )
    except Exception:
        log_middleware_information(
            '{0} | Error sending GCM message',
            OrderedDict([
                ('unique_key', unique_key),
            ]),
            logging.CRITICAL,
            device=device,
        )
Beispiel #4
0
def send_gcm_message(device, app, message_type, data=None):
    """
    Send a Google Cloud Messaging message.
    """
    token_list = [
        device.token,
    ]
    unique_key = device.token

    key = "%d-cycle.key" % int(time())
    if message_type == TYPE_CALL:
        unique_key = data['unique_key']
        message = get_call_push_payload(
            unique_key,
            data['phonenumber'],
            data['caller_id'],
        )
    elif message_type == TYPE_MESSAGE:
        message = get_message_push_payload(data['message'])
    else:
        logger.warning(
            '{0} | Trying to sent message of unknown type: {1}'.format(
                unique_key, message_type))

    gcm = GCM(app.push_key)

    try:
        start_time = time()
        response = gcm.json_request(
            registration_ids=token_list,
            data=message,
            collapse_key=key,
            priority='high',
        )

        success = response.get('success')
        canonical = response.get('canonical')
        errors = response.get('errors')

        if success:
            for reg_id, msg_id in success.items():
                logger.info(
                    '{0} | GCM \'{1}\' message sent at time:{2} to {3} Data:{4}'
                    .format(
                        unique_key,
                        message_type,
                        datetime.datetime.fromtimestamp(start_time).strftime(
                            '%H:%M:%S.%f'),
                        reg_id,
                        data,
                    ))

        if canonical:
            for reg_id, new_reg_id in canonical.items():
                logger.warning(
                    '%s | Should replace device token %s with %s in database' %
                    (unique_key, reg_id, new_reg_id))

        if errors:
            for err_code, reg_id in errors.items():
                logger.warning('%s | Should remove %s because %s' %
                               (unique_key, reg_id, err_code))

    except GCMAuthenticationException:
        # Stop and fix your settings.
        logger.error(
            '{0} | Our Google API key was rejected!!!'.format(unique_key))
    except ValueError:
        # Probably your extra options, such as time_to_live,
        # are invalid. Read error message for more info.
        logger.error(
            '{0} | Invalid message/option or invalid GCM response'.format(
                unique_key))
    except Exception:
        logger.exception('{0} | Error sending GCM message'.format(unique_key))
Beispiel #5
0
    def gcm_request(self, notification, max_retries=10):
        from gcm.gcm import GCM, GCMConnectionException, GCMUnavailableException, GCMAuthenticationException
        from settings import GOOGLE_GCM_API_KEY
        from coresql.models import UserProfile

        logger.info("[GCMClientThread] Handling request for notification: " + str(notification))

        gcm_client = GCM(GOOGLE_GCM_API_KEY)
        registration_ids, collapse_key, delay_while_idle, ttl, data = notification

        try:
            response = gcm_client.json_request(
                registration_ids,
                data=data,
                collapse_key=collapse_key,
                delay_while_idle=delay_while_idle,
                time_to_live=ttl,
                retries=max_retries,
            )

            # Handling errors
            if "errors" in response:
                for error, reg_ids in response["errors"].items():
                    # Check for errors and act accordingly
                    if error in ["NotRegistered", "InvalidRegistration"]:
                        # Remove reg_ids from database
                        for reg_id in reg_ids:
                            """
                            Either the owner has turned off notifications (NotRegistered) or 
                            there is a problem with the registration_id (InvalidRegistration).
                            In both cases, log the error and set the corresponding registration_id to null in the UserProfile
                            """
                            try:
                                user_profile = UserProfile.objects.get(c2dm_id=reg_id)
                                user_profile.c2dm_id = None
                                user_profile.save()
                            except Exception:
                                pass

                            logger.error(
                                "[GCM " + error + " ERROR] Encountered at notification request: " + str(notification)
                            )
                    else:
                        """
                        Any other error that should normally not be encountered because of the internal business logic: 
                        MissingRegistration, MismatchSenderId, MessageTooBig, MissingCollapseKey 
                        """
                        logger.error(
                            "[GCM " + error + " ERROR] Encountered at notification request: " + str(notification)
                        )

            if "canonical" in response:
                for canonical_id, reg_id in response["canonical"].items():
                    # Repace reg_id with canonical_id in your database
                    try:
                        user_profile = UserProfile.objects.get(c2dm_id=reg_id)
                        user_profile.c2dm_id = canonical_id
                        user_profile.save()
                    except Exception:
                        pass

            logger.info("[GCM INFO] Finished processing GCM notifications: " + str(notification))

        except GCMConnectionException, e:
            logger.critical("[GCM EXCEPTION] Connection error at GCM request (" + str(notification) + "): " + str(e))