def _check_alert(self, alert):
     with pytest.raises(ValueError) as excinfo:
         check_encoding(
             messaging.Message(
                 topic='topic',
                 apns=messaging.APNSConfig(payload=messaging.APNSPayload(
                     aps=messaging.Aps(alert=alert)))))
     return excinfo
 def test_invalid_custom_data_dict(self, data):
     if isinstance(data, dict):
         return
     aps = messaging.Aps(custom_data=data)
     with pytest.raises(ValueError) as excinfo:
         self._encode_aps(aps)
     expected = 'Aps.custom_data must be a dict.'
     assert str(excinfo.value) == expected
示例#3
0
def notify_user(user, title, body):
    # See documentation on defining a message payload.
    message = messaging.Message(
        notification=messaging.Notification(
            title=title,
            body=body,
        ),
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(sound="default"))),
        token=user.fir_push_notif_token,
    )

    _send(message, user)
def test_send():
    msg = messaging.Message(
        topic='foo-bar',
        notification=messaging.Notification('test-title', 'test-body'),
        android=messaging.AndroidConfig(
            restricted_package_name='com.google.firebase.demos',
            notification=messaging.AndroidNotification(title='android-title',
                                                       body='android-body')),
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(alert=messaging.ApsAlert(title='apns-title',
                                                       body='apns-body')))))
    msg_id = messaging.send(msg, dry_run=True)
    assert re.match('^projects/.*/messages/.*$', msg_id)
示例#5
0
 def SendNotification(self, Topic, Title, Body):
     print("sending notif")
     NotifAmount = 1
     message = messaging.Message(
         apns=messaging.APNSConfig(payload=messaging.APNSPayload(
             aps=messaging.Aps(alert=messaging.ApsAlert(
                 title=Title,
                 body=Body,
             ),
                               sound="default",
                               badge=NotifAmount + 1), ), ),
         topic=Topic,
     )
     messaging.send(message)
示例#6
0
def build_single_message(token, msg):
    registration_token = token
    message = messaging.Message(
        data={'type': 'notification'},
        notification=messaging.Notification('', msg),
        android=messaging.AndroidConfig(
            priority='high',
            notification=messaging.AndroidNotification(
                click_action='FLUTTER_NOTIFICATION_CLICK'),
        ),
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42), ), ),
        token=registration_token,
    )
    return message
示例#7
0
    def send_notification_to_users(self,
                                   title,
                                   message,
                                   uids,
                                   setting,
                                   data=None):
        settings = [
            'users.notify_new_friend_req', 'users.notify_new_friend_acc',
            'notify_new_feed_item', 'notify_new_like', 'notify_new_comment'
        ]

        title = pymysql.escape_string(bleach.clean(title))
        message = pymysql.escape_string(bleach.clean(message))

        #Connect to MySQL
        conn = pymysql.connect(self.host,
                               self.username,
                               self.password,
                               self.database,
                               cursorclass=pymysql.cursors.DictCursor,
                               charset='utf8mb4')
        cursor = conn.cursor()

        cursor.execute("""SELECT device_id, devices.uid AS uid FROM users

LEFT OUTER JOIN devices ON devices.uid = users.uid

WHERE devices.uid IN ({}) AND {} = 1;""".format(
            ",".join(["'{}'".format(uid) for uid in uids]), settings[setting]))

        conn.commit()
        conn.close()

        devices = cursor.fetchall()

        device_tokens = [device["device_id"] for device in devices]
        push_notification = messaging.MulticastMessage(
            device_tokens,
            notification=messaging.Notification(title=title, body=message),
            data=data,
            apns=messaging.APNSConfig(
                payload=messaging.APNSPayload(messaging.Aps(sound="default"))),
            android=messaging.AndroidConfig(
                notification=messaging.AndroidNotification(
                    sound="default", click_action="OPEN_FROM_NOTIFICATION")))

        response = messaging.send_multicast(push_notification)
示例#8
0
def send_message_notif(fir_push_notif_token,
                       badge_number,
                       title=None,
                       body=None):
    """send message notif and update badge icon"""
    message = messaging.Message(
        token=fir_push_notif_token,
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=badge_number))))

    if title is not None and body is not None:
        message.notification = messaging.Notification(
            title=title,
            body=body,
        )

    _send(message, user)
def silent_notification():
    post_response = request.get_json()
    deviceToken = post_response.get('token')
    key = post_response.get('key')
    message = messaging.Message(
        data={"key": key},
        token=deviceToken,
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(content_available=True))))

    try:
        response = messaging.send(message)
    except:
        abort(400, {'message': 'could not send silent notification'})
    return jsonify(
        {'message':
         'silent notification successfully sent from customer'}), 200
示例#10
0
 def construct_multicast_message(self):
     self.data['click_action'] = 'FLUTTER_NOTIFICATION_CLICK'
     message = messaging.MulticastMessage(
         notification=messaging.Notification(
             title=self.message['title'],
             body=self.message['body'],
         ),
         android=messaging.AndroidConfig(
             ttl=datetime.timedelta(seconds=3600),
             priority='normal',
         ),
         apns=messaging.APNSConfig(payload=messaging.APNSPayload(
             aps=messaging.Aps(badge=42), ), ),
         data=self.data,
         tokens=self.tokens,
     )
     return message
def apns_message():
    # [START apns_message]
    message = messaging.Message(
        apns=messaging.APNSConfig(
            headers={'apns-priority': '10'},
            payload=messaging.APNSPayload(aps=messaging.Aps(
                alert=messaging.ApsAlert(
                    title='$GOOG up 1.43% on the day',
                    body=
                    '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
                ),
                badge=42,
            ), ),
        ),
        topic='industry-tech',
    )
    # [END apns_message]
    return message
示例#12
0
 def make_message(self, body=None, notification=None):
     topic_or_token = self.topic if self.topic else self.token
     body = {} if not body else body
     notification = {} if not notification else notification
     return messaging.Message(
         data=body,
         notification=Notification(**notification),
         token=topic_or_token,
         apns=messaging.APNSConfig(
             headers={
                 'apns-push-type': 'background',
                 'apns-priority': '5'
             },
             payload=messaging.APNSPayload(
                 aps=messaging.Aps(content_available=True)
                 # badge=Session().query(Notification).filter((Notification.to_user_id == self.target_user_id)
                 #                                            & (Notification.read == False)).count() + 1
             )))
    def platform_config(self, platform_type):
        """ Return a platform-specific configuration object for a platform_type, given the platform payload.

        Args:
            platform_type (PlatformType): Type for the platform config.

        Returns:
            object: Either a AndroidConfig, ApnsConfig, or WebpushConfig depending on the platform_type.
        """
        from consts.fcm.platform_type import PlatformType
        # Validate that platform_type is supported
        PlatformType.validate(platform_type)

        from firebase_admin import messaging
        if platform_type == PlatformType.ANDROID:
            priority = PlatformPriority.platform_priority(platform_type, self.priority) \
                if self.priority is not None else None

            return messaging.AndroidConfig(
                collapse_key=self.collapse_key,
                priority=priority
            )
        else:
            headers = {}

            if self.collapse_key:
                headers[PlatformType.collapse_key_key(platform_type)] = self.collapse_key

            if self.priority is not None:
                priority = PlatformPriority.platform_priority(platform_type, self.priority)
                headers[PlatformType.priority_key(platform_type)] = priority

            # Null out headers if they're empty
            headers = headers if headers else None

            if platform_type == PlatformType.APNS:
                # Create an empty `payload` as a workaround for an FCM bug
                # https://github.com/the-blue-alliance/the-blue-alliance/pull/2557#discussion_r310365295
                payload = messaging.APNSPayload(aps=messaging.Aps(content_available=True)) if headers else None
                return messaging.APNSConfig(headers=headers, payload=payload)
            elif platform_type == PlatformType.WEBPUSH:
                return messaging.WebpushConfig(headers=headers)
            else:
                raise TypeError("Unsupported PlatformPayload platform_type: {}".format(platform_type))
示例#14
0
def send_to_app(token, title, url):
    registration_token = token
    try:
        user = User.objects.get(token=token)
        if user.user_os == "ios":
            message = messaging.Message(
                # notification=messaging.Notification(title=title, body="페이지 변경 감지!"),
                apns=messaging.APNSConfig(
                    payload=messaging.APNSPayload(
                        aps=messaging.Aps(
                            alert=messaging.ApsAlert(title=title, body="페이지 변경 감지!",),
                            badge=1,
                        ),
                    ),
                ),
                token=registration_token,
            )

        else:
            message = messaging.Message(
                android=messaging.AndroidConfig(
                    notification=messaging.AndroidNotification(
                        title=title,
                        body="페이지 변경 감지!",
                        default_sound=True,
                        visibility="public",
                        priority="high",
                    )
                ),
                token=registration_token,
            )
    except:
        return False

    try:
        response = messaging.send(message)
        print("Successfully sent message:", response)
        return True
    except Exception as e:
        print("Fail sent message", e)
        # delete_user(token)
    return False
 def test_aps_alert(self):
     msg = messaging.Message(
         topic='topic',
         apns=messaging.APNSConfig(
             payload=messaging.APNSPayload(
                 aps=messaging.Aps(
                     alert=messaging.ApsAlert(
                         title='t',
                         body='b',
                         title_loc_key='tlk',
                         title_loc_args=['t1', 't2'],
                         loc_key='lk',
                         loc_args=['l1', 'l2'],
                         action_loc_key='alk',
                         launch_image='li'
                     )
                 ),
             )
         )
     )
     expected = {
         'topic': 'topic',
         'apns': {
             'payload': {
                 'aps': {
                     'alert': {
                         'title': 't',
                         'body': 'b',
                         'title-loc-key': 'tlk',
                         'title-loc-args': ['t1', 't2'],
                         'loc-key': 'lk',
                         'loc-args': ['l1', 'l2'],
                         'action-loc-key': 'alk',
                         'launch-image': 'li',
                     },
                 },
             }
         },
     }
     check_encoding(msg, expected)
示例#16
0
    def _fcm_message(self):
        platform_config = self.notification.platform_config

        from consts.fcm.platform_type import PlatformType
        android_config = self.notification.android_config if self.notification.android_config \
            else platform_config and platform_config.platform_config(platform_type=PlatformType.ANDROID)
        apns_config = self.notification.apns_config if self.notification.apns_config \
            else platform_config and platform_config.platform_config(platform_type=PlatformType.APNS)
        webpush_config = self.notification.webpush_config if self.notification.webpush_config \
            else platform_config and platform_config.platform_config(platform_type=PlatformType.WEBPUSH)
        # `platform_config and platform_config` is to short circuit execution if platform_config is None

        # Additional APNS-specific configuration - make sure we have some payload
        if not apns_config:
            apns_config = messaging.APNSConfig()
        if not apns_config.payload:
            apns_config.payload = messaging.APNSPayload(aps=messaging.Aps())

        if self.notification.fcm_notification:
            # Set sound
            apns_config.payload.aps.sound = 'default'
        else:
            # Set content_available
            apns_config.payload.aps.content_available = True

        # Add `notification_type` to data payload
        data_payload = self.notification.data_payload if self.notification.data_payload else {}
        # Remove `None` from data payload, since FCM won't accept them
        data_payload = {k: v for k, v in data_payload.items() if v is not None}
        from consts.notification_type import NotificationType
        data_payload['notification_type'] = NotificationType.type_names[
            self.notification.__class__._type()]

        return messaging.MulticastMessage(
            tokens=self.tokens,
            data=data_payload,
            notification=self.notification.fcm_notification,
            android=android_config,
            webpush=webpush_config,
            apns=apns_config)
示例#17
0
def build_multiple_message(token, msg):
    registration_token = token
    message = messaging.Message(
        data={'type': 'notification'},
        notification=messaging.Notification('', msg),
        android=messaging.AndroidConfig(
            priority='high',
            notification=messaging.AndroidNotification(
                click_action='FLUTTER_NOTIFICATION_CLICK'),
        ),
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42), ), ),
        token=registration_token,
    )
    return message


# Send a message to the device corresponding to the provided
# registration token.
#response = messaging.send(build_single_message())
# Response is a message ID string.
#print('Successfully sent message:', response)
示例#18
0
 def send_notifications(self, registration_tokens, title, body):
     message = messaging.MulticastMessage(
         notification=messaging.Notification(
             title=title,
             body=body,
         ),
         android=messaging.AndroidConfig(
             priority='normal',
             notification=messaging.AndroidNotification(
                 icon='stock_ticker_update', color='#f45342'),
         ),
         apns=messaging.APNSConfig(payload=messaging.APNSPayload(
             aps=messaging.Aps(badge=42), ), ),
         tokens=registration_tokens)
     response = messaging.send_multicast(message)
     if response.failure_count > 0:
         responses = response.responses
         failed_tokens = []
         for idx, resp in enumerate(responses):
             if not resp.success:
                 # The order of responses corresponds to the order of the registration tokens.
                 failed_tokens.append(registration_tokens[idx])
         print('List of tokens that caused failures: {0}'.format(
             failed_tokens))
示例#19
0
def send_fcm(title, body, reciever):
    initialize_firebase_admin_sdk()
    firebase_admin.get_app()
    notification = messaging.Notification(title=title, body=body)
    print(reciever)
    tokens = FCMDeviceToken.objects.filter(user=reciever)
    # token = settings.FIREBASE_TEST_TOKEN  # local_settings.py
    if tokens is not None:
        for token in tokens:
            apns = messaging.APNSConfig(payload=messaging.APNSPayload(
                aps=messaging.Aps(badge=1)))
            message = messaging.Message(
                notification=notification,
                apns=apns,
                token=token.device_token,
            )
            try:
                messaging.send(message)
                logger.info('fcm ok')
                print('fcm ok')
            except:
                print('error')
                logger.error('fcm sending error')
                pass
 def test_aps_custom_data(self):
     msg = messaging.Message(
         topic='topic',
         apns=messaging.APNSConfig(
             payload=messaging.APNSPayload(aps=messaging.Aps(
                 alert='alert text',
                 custom_data={
                     'k1': 'v1',
                     'k2': 1
                 },
             ), )))
     expected = {
         'topic': 'topic',
         'apns': {
             'payload': {
                 'aps': {
                     'alert': 'alert text',
                     'k1': 'v1',
                     'k2': 1,
                 },
             }
         },
     }
     check_encoding(msg, expected)