예제 #1
0
def send_notif_multiple(registration_tokens=[],
                        data={},
                        title="Notification Order",
                        body="hey you, you have some order "):
    if len(registration_tokens) == 0:
        return

    message = messaging.MulticastMessage(
        # for id user divice
        tokens=registration_tokens,
        # for data payload
        data=data,

        # notification body
        notification=messaging.Notification(title=title, body=body),

        # android notification
        android=messaging.AndroidConfig(
            ttl=datetime.timedelta(seconds=3600),
            notification=messaging.AndroidNotification(title=title,
                                                       body=body,
                                                       color='#f45342')),

        # apns
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42), ), ),
    )
    response = messaging.send_multicast(message, app=firebase)
    # See the BatchResponse reference documentation
    # for the contents of response.
    return '{0} messages were sent successfully'.format(response.success_count)
 def test_aps(self):
     msg = messaging.Message(
         topic='topic',
         apns=messaging.APNSConfig(payload=messaging.APNSPayload(
             aps=messaging.Aps(alert='alert text',
                               badge=42,
                               sound='s',
                               content_available=True,
                               category='c',
                               thread_id='t'), )))
     expected = {
         'topic': 'topic',
         'apns': {
             'payload': {
                 'aps': {
                     'alert': 'alert text',
                     'badge': 42,
                     'sound': 's',
                     'content-available': 1,
                     'category': 'c',
                     'thread-id': 't',
                 },
             }
         },
     }
     check_encoding(msg, expected)
def test_send():
    msg = messaging.Message(
        topic='foo-bar',
        notification=messaging.Notification(
            'test-title', 'test-body',
            'https://images.unsplash.com/photo-1494438639946'
            '-1ebd1d20bf85?fit=crop&w=900&q=60'),
        android=messaging.AndroidConfig(
            restricted_package_name='com.google.firebase.demos',
            notification=messaging.AndroidNotification(
                title='android-title',
                body='android-body',
                image='https://images.unsplash.com/'
                'photo-1494438639946-1ebd1d20bf85?fit=crop&w=900&q=60',
                event_timestamp=datetime.now(),
                priority='high',
                vibrate_timings_millis=[100, 200, 300, 400],
                visibility='public',
                sticky=True,
                local_only=False,
                default_vibrate_timings=False,
                default_sound=True,
                default_light_settings=False,
                light_settings=messaging.LightSettings(
                    color='#aabbcc',
                    light_off_duration_millis=200,
                    light_on_duration_millis=300),
                notification_count=1)),
        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)
예제 #4
0
    def test_message(self):
        # [START send_to_token]
        # This registration token comes from the client FCM SDKs.
        registration_token = 'd4KUpt5mSJ6ngrNytzwYsp:APA91bGru82_I4TshgwfWhTlq-B-hmqD31nWLr_-3VA_NeUrG3JneaQtuK7et7R_lQS4BGly8nkH7CWC3RIeU3fob46VnO_kq1giPV_EZIi-MOPXDkHpULtYEp2A8fcm12MOvJyNTU3s'

        # See documentation on defining a message payload.
        message = messaging.Message(
            notification=messaging.Notification(
                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.',
            ),
            android=messaging.AndroidConfig(
                ttl=datetime.timedelta(seconds=3600),
                priority='normal',
                notification=messaging.AndroidNotification(
                    icon='stock_ticker_update', color='#f45342'),
            ),
            apns=messaging.APNSConfig(payload=messaging.APNSPayload(
                aps=messaging.Aps(badge=42), ), ),
            token=registration_token,
        )

        # Send a message to the device corresponding to the provided
        # registration token.
        response = messaging.send(message)
        # Response is a message ID string.
        print('Successfully sent message:', response)
 def test_invalid_aps(self, data):
     with pytest.raises(ValueError) as excinfo:
         check_encoding(messaging.Message(
             topic='topic',
             apns=messaging.APNSConfig(payload=messaging.APNSPayload(aps=data))))
     expected = 'APNSPayload.aps must be an instance of Aps class.'
     assert str(excinfo.value) == expected
 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)
예제 #7
0
def send(data: dict, device: str, controller: str, push_temp: float = None):
    app.logger.info(
        f'sending data {"with push" if push_temp else "without push"} to device: {device}'
    )

    message = messaging.Message(
        data={'payload': json.dumps(data)},
        token=device,
    )
    if push_temp and not should_throttle_push(device, controller):
        # don't send another push to this device about this controller for num seconds.
        set_push_throttle(device, controller, seconds=30)
        # add push notification to message
        message.notification = messaging.Notification(
            title='MeatHeat',
            body=f'{push_temp}° is outside of the range!',
        )
        message.apns = messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=1, sound='default'), ), )

    try:
        message_id = messaging.send(message)
        app.logger.info(f'successfully sent {message_id} to device: {device}')
    except Exception as e:
        # TODO: should remove device token from redis if the exception is related to it being invalid.
        app.logger.error(
            f'error sending push to device: {device} with error: {e}')
예제 #8
0
async def send_fcm(to_user, action):
    if not firebase_admin._apps:
        cred = credentials.Certificate(
            '/var/www/static/fullfii-firebase-adminsdk-cn02h-2e2b2efd56.json')
        firebase_admin.initialize_app(cred)

    registration_token = to_user.device_token
    if not registration_token:
        return

    fcm_reducer_result = await fcm_reducer(to_user, action)
    if fcm_reducer_result is None:
        return

    try:
        badge_apns = messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=fcm_reducer_result['badge']
                              ))) if fcm_reducer_result['badge'] > 0 else None

        message = messaging.Message(
            notification=messaging.Notification(
                title=fcm_reducer_result['title'],
                body=fcm_reducer_result['body'],
            ),
            apns=badge_apns,
            token=registration_token,
        )

        try:
            response = messaging.send(message)
            print('Successfully sent message:', response)
        except:
            traceback.print_exc()
    except:
        traceback.print_exc()
예제 #9
0
    def send_notification_to_user(self, title, message, uid, data=None):
        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 * FROM devices WHERE uid='{}';".format(uid))

        devices = cursor.fetchall()

        conn.commit()
        conn.close()

        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)
예제 #10
0
def send_push_message(self, token, message, subject, extra=None):
    default_app = self.default_app

    # All data key:values must be strings
    notify_data = {
        'title': str(subject),
        'body': str(message),
        'sound': 'waytone'
    }

    try:
        message = messaging.Message(
            data=notify_data,
            token=token,
            notification=messaging.Notification(
                title=subject,
                body=message,
            ),
            android=messaging.AndroidConfig(
                ttl=datetime.timedelta(seconds=3600),
                priority='high',
                notification=messaging.AndroidNotification(sound='waytone', ),
            ),
            apns=messaging.APNSConfig(payload=messaging.APNSPayload(
                aps=messaging.Aps(sound='waytone.caf'), ), ),
        )
        # Send a message to the device corresponding to the provided
        # registration token.
        response = messaging.send(message, app=self.default_app)
        logger.info('Push Message sent to %s', token)

    except Exception as e:
        print 'Error while sending push message: %s', e.message
        logger.error('Error while sending push message: %s', e.message)
 def _check_aps(self, aps):
     with pytest.raises(ValueError) as excinfo:
         check_encoding(
             messaging.Message(topic='topic',
                               apns=messaging.APNSConfig(
                                   payload=messaging.APNSPayload(aps=aps))))
     return excinfo
    def _build_apns_config(self, title_loc_key: str = ''):
        """
        Data for the Apple Push Notification Service
        see https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging
        :param title_loc_key:
        :return:
        """

        return messaging.APNSConfig(
            # headers={
            #    'apns-priority': '10'
            # },
            payload=messaging.APNSPayload(
                aps=messaging.Aps(
                    alert=messaging.ApsAlert(
                        # This is a localized key that iOS will search in
                        # the safe iOS app to show as a default title
                        title="New Activity",
                        body="New Activity with your Safe",
                        #    title_loc_key=title_loc_key,
                    ),
                    # Means the content of the notification will be
                    # modified by the safe app.
                    # Depending on the 'type' custom field,
                    # 'alert.title' and 'alert.body' above will be
                    # different
                    mutable_content=True,
                    badge=1,
                    sound='default',
                ), ), )
예제 #13
0
def send_notif_device(registration_token="",
                      data={},
                      title="Notification Order",
                      body="hey you, you have some order"):
    if registration_token == "":
        return
    message = messaging.Message(
        data=data,
        token=registration_token,

        # notification body
        notification=messaging.Notification(title=title, body=body),

        # android notification
        android=messaging.AndroidConfig(
            ttl=datetime.timedelta(seconds=3600),
            notification=messaging.AndroidNotification(color='#f45342',
                                                       title=title,
                                                       body=body)),

        # apns
        apns=messaging.APNSConfig(payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42), ), ),
    )

    response = messaging.send(message, app=firebase)

    return response
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)
예제 #15
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)
예제 #16
0
def send_all(registration_token,title, body, data):
    # registration_token = 'YOUR_REGISTRATION_TOKEN'
    # [START send_all]
    # Create a list containing up to 500 messages.
    #  notification=messaging.Notification(title, body,'https://drlinks.yte360.com/static/images/icon-thuoc.png'),

    messages = [
        messaging.Message(
            notification=messaging.Notification(title, body,'https://drlinks.yte360.com/static/images/ic_launcher.png'),
            token=registration_token,
            data=data,
            android=messaging.AndroidConfig(
                ttl=datetime.timedelta(seconds=3600),
                priority='normal',
                notification=messaging.AndroidNotification(
                    title=title,
                    body=body,
                    sound='bell.mp3',
                    icon='https://drlinks.yte360.com/static/images/ic_launcher.png',
                    # color='#f45342'
                ),
            ),
            apns=messaging.APNSConfig(
                headers={'apns-priority': '10'},
                payload=messaging.APNSPayload(
                    aps=messaging.Aps(
                        alert=messaging.ApsAlert(
                            title=title,
                            body=body,
                        ),
                        badge=42,
                        sound='bell.mp3'
                    ),
                ),
            )
            

        ),

        
        # ...
        # messaging.Message(
        #     notification=messaging.Notification(title, body),
        #     topic='readers-club',
        # ),
    ]

    response = messaging.send_all(messages)
    # See the BatchResponse reference documentation
    # for the contents of response.
    print('{0} messages were sent successfully'.format(response.success_count))
예제 #17
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)
예제 #18
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
예제 #19
0
def _build_data_message(client_token: str, event: Event) -> Optional[messaging.Message]:
    data = _build_data_prop(event=event)

    if data is not None:
        android_config = messaging.AndroidConfig(priority="high")
        apns = messaging.APNSConfig(
            headers={"apns-push-type": "background", "apns-priority": "5"},
            payload=messaging.APNSPayload(aps=messaging.Aps(content_available=True),),
        )

        return messaging.Message(
            data=data, token=client_token, android=android_config, apns=apns
        )

    return None
예제 #20
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)
예제 #21
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
예제 #22
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)
예제 #23
0
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
예제 #24
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
             )))
예제 #25
0
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
 def test_apns_payload(self):
     msg = messaging.Message(
         topic='topic',
         apns=messaging.APNSConfig(payload=messaging.APNSPayload(
             aps=messaging.Aps(alert='alert text'), k1='v1', k2=True)))
     expected = {
         'topic': 'topic',
         'apns': {
             'payload': {
                 'aps': {
                     'alert': 'alert text',
                 },
                 'k1': 'v1',
                 'k2': True,
             },
         },
     }
     check_encoding(msg, expected)
예제 #27
0
    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))
예제 #28
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
예제 #29
0
 async def all_platforms_message(self):
     # [START multi_platforms_message]
     message = messaging.Message(
         notification=messaging.Notification(
             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.',
         ),
         android=messaging.AndroidConfig(
             ttl=datetime.timedelta(seconds=3600),
             priority='normal',
             notification=messaging.AndroidNotification(
                 icon='stock_ticker_update', color='#f45342'),
         ),
         apns=messaging.APNSConfig(payload=messaging.APNSPayload(
             aps=messaging.Aps(badge=42), ), ),
         topic='industry-tech',
     )
     # [END multi_platforms_message]
     return message
예제 #30
0
def apns_message(registration_token, title, body, data):
    # [START apns_message]
    message = messaging.Message(
        token=registration_token,
        data=data,
        apns=messaging.APNSConfig(
            payload=messaging.APNSPayload(
                aps=messaging.Aps(
                    alert=messaging.ApsAlert(
                        title=title,
                        body=body,
                    ),
                    badge=1,
                ),
            ),
        )
    )
    # [END apns_message]
    response = messaging.send(message)
    print("send notify IOS====",response)