Exemplo n.º 1
0
def submit_notification(email, content):
    user_data = UserData.query.filter_by(email=email).first()
    notif = messaging.Notification(
        content['title'],
        content['body'],
        image=
        'https://images-na.ssl-images-amazon.com/images/I/41NMl%2Bp3MlL._SY355_.jpg'
    )
    app_url = os.environ.get('APP_URL')
    flyer_id = content['flyer_id']

    link = f'{app_url}/messages?flyerId={flyer_id}'

    fcm_options = messaging.WebpushFCMOptions(link=link)

    web_push = messaging.WebpushConfig(fcm_options=fcm_options)

    # See documentation on defining a message payload.
    message = messaging.Message(data=content,
                                token=user_data.push_token,
                                notification=notif,
                                webpush=web_push)

    # 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)
Exemplo n.º 2
0
def sendNotification(title, body, data, token):
    print(token)
    """
    @desc: Send notification
    @param: data (dictionary)
        1) title (string)
        2) body (string)
        3) data (dict with any format)
        4) token (string)
    @return:
        Dictionary: {'status' : SUCCESS|FAIL, 'msg' : (string), 'status_code' : (int), data : (dict)}
    """
  
    try:
        notification = messaging.Notification(title=title, body=body)
        web_notification = messaging.WebpushNotification(icon=constants.NOTIFICATION_ICON)
        web_push_config = messaging.WebpushConfig(notification=web_notification)
        message = messaging.Message(
            notification=notification,
            data=data,
            token=token,
            webpush=web_push_config
        )
        message_id = firebase_admin.messaging.send(message)
        print(message_id)
        return helper.getPositiveResponse("Message send successfully",message_id)
    except Exception as e:
        return helper.getNegativeResponse("Message send failed")
Exemplo n.º 3
0
    def send_fcm(self, token, msg, url):
        title = 'POAP.fun alert'
        poap_badge = 'https://poap.fun/favicons/favicon-96x96.png'
        notification = messaging.Notification(title=title,
                                              body=msg,
                                              image=poap_badge)

        webpush = messaging.WebpushConfig(
            notification=messaging.WebpushNotification(
                title=title,
                body=msg,
                icon=poap_badge,
                badge=poap_badge,
                image=poap_badge,
            ),
            fcm_options=messaging.WebpushFCMOptions(link=url))

        message = messaging.Message(
            notification=notification,
            webpush=webpush,
            token=token,
        )

        response = messaging.send(message)

        return response
 def _check_notification(self, notification):
     with pytest.raises(ValueError) as excinfo:
         check_encoding(
             messaging.Message(topic='topic',
                               webpush=messaging.WebpushConfig(
                                   notification=notification)))
     return excinfo
 def test_invalid_webpush_notification(self, data):
     with pytest.raises(ValueError) as excinfo:
         check_encoding(
             messaging.Message(
                 topic='topic',
                 webpush=messaging.WebpushConfig(notification=data)))
     expected = 'WebpushConfig.notification must be an instance of WebpushNotification class.'
     assert str(excinfo.value) == expected
Exemplo n.º 6
0
def send_notification(token, title, body, link=None):
    message = messaging.Message(
        notification=messaging.Notification(title=title,
                                            body=body,
                                            image="/logo192.png"),
        webpush=messaging.WebpushConfig(
            fcm_options=messaging.WebpushFCMOptions(link=link)),
        token=token,
    )

    return messaging.send(message, app=app)
Exemplo n.º 7
0
    def _development_message(self):
        body = self._notification_body()
        webpush_notification = messaging.WebpushNotification(
            title=NOTIFICATION_TITLE, body=body, icon='/static/icon.png')
        webpush_config = messaging.WebpushConfig(
            notification=webpush_notification, )

        message = messaging.Message(topic=MESSAGE_TOPIC,
                                    webpush=webpush_config)

        return message
Exemplo n.º 8
0
def notify(user, data, db):
    userdata = db.query.filter_by(user=user).first()
    if not userdata:
        return None
    if not userdata.notification_id:
        return None
    idx: str = userdata.notification_id

    data_fs: dict = {"data": json.dumps(data)}
    config = messaging.WebpushConfig(headers={"Urgency": "high"})
    message = messaging.Message(data=data_fs, token=idx, webpush=config)
    return messaging.send(message)
Exemplo n.º 9
0
    def _production_message(self):
        body = self._notification_body()
        webpush_notification = messaging.WebpushNotification(
            title=NOTIFICATION_TITLE, body=body, icon='/static/icon.png')
        webpush_fcm_options = messaging.WebpushFCMOptions(link=BASE_URL)
        webpush_config = messaging.WebpushConfig(
            notification=webpush_notification, fcm_options=webpush_fcm_options)

        message = messaging.Message(topic=MESSAGE_TOPIC,
                                    webpush=webpush_config)

        return message
Exemplo n.º 10
0
def webpush_message():
    # [START webpush_message]
    message = messaging.Message(
        webpush=messaging.WebpushConfig(
            notification=messaging.WebpushNotification(
                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.',
                icon='https://my-server/icon.png',
            ),
        ),
        topic='industry-tech',
    )
    # [END webpush_message]
    return message
 def test_webpush_notification(self):
     msg = messaging.Message(topic='topic',
                             webpush=messaging.WebpushConfig(
                                 notification=messaging.WebpushNotification(
                                     title='t', body='b', icon='i')))
     expected = {
         'topic': 'topic',
         'webpush': {
             'notification': {
                 'title': 't',
                 'body': 'b',
                 'icon': 'i',
             },
         },
     }
     check_encoding(msg, expected)
Exemplo n.º 12
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))
Exemplo n.º 13
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.
        """
        # 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:
                return messaging.APNSConfig(headers=headers)
            elif platform_type == PlatformType.WEBPUSH:
                return messaging.WebpushConfig(headers=headers)
            else:
                raise TypeError(
                    "Unsupported PlatformPayload platform_type: {}".format(
                        platform_type))
Exemplo n.º 14
0
def main(datas):
    cred = credentials.Certificate('service-account.json')
    default_app = firebase_admin.initialize_app(cred)
    
    # This registration token comes from the client FCM SDKs.
    #registration_token = 'ANDROID_CLIENT_TOKEN'
    topic = 'capstone'
    message_body = datas[2] + '   Person : ' + datas[0] + ', Accuracy : ' + datas[1] + '%'
    message_title = 'Notification!'
    
    # See documentation on defining a message payload.
    message = messaging.Message(
        android=messaging.AndroidConfig(
            ttl=datetime.timedelta(seconds=3600),
            priority='normal',
            notification=messaging.AndroidNotification(
                title=message_title,
                body=message_body,
                icon='',
                color='#f45342',
                sound='default'
            ),
        ),
        data={
            'score': '850',
            'time': '2:45',
        },
        webpush=messaging.WebpushConfig(
            notification=messaging.WebpushNotification(
                title=message_title,
                body=message_body,
                icon='',
            ),
        ),
        topic=topic,
        #token=registration_token
    )
    
    # Send a message to the device corresponding to the provided
    # registration token.
    response = messaging.send(message)
 def test_webpush_config(self):
     msg = messaging.Message(
         topic='topic',
         webpush=messaging.WebpushConfig(
             headers={'h1': 'v1', 'h2': 'v2'},
             data={'k1': 'v1', 'k2': 'v2'}
         )
     )
     expected = {
         'topic': 'topic',
         'webpush': {
             'headers': {
                 'h1': 'v1',
                 'h2': 'v2',
             },
             'data': {
                 'k1': 'v1',
                 'k2': 'v2',
             },
         },
     }
     check_encoding(msg, expected)
Exemplo n.º 16
0
def webpush_message(registration_token, title, body, data):
    try:

        print("webpush_message.data====",data)
        # [START webpush_message]
        message = messaging.Message(
            notification=messaging.Notification(title, body,'https://drlinks.yte360.com/static/images/ic_launcher.png'),
            token=registration_token,
            data=data,
            webpush=messaging.WebpushConfig(
                notification=messaging.WebpushNotification(
                    title=str(title),
                    body=str(body),
                    icon='https://drlinks.yte360.com/static/images/favicon/favicon-96x96.png',
                ),
            )
        )
        response = messaging.send(message)
        print("send webpush_message====",response)
    except Exception as error:
        print(error)
        pass
Exemplo n.º 17
0
def notify_about_post_async(post_id):
    post = Post.objects.get(id=post_id)

    notification = messaging.Notification(
        title=post.title,
        body=post.description,
    )
    webpush = messaging.WebpushConfig(fcm_options=messaging.WebpushFCMOptions(
        link=post.link))

    for sub in Subscription.objects.all():
        try:
            message = messaging.Message(notification=notification,
                                        token=sub.notification_token,
                                        webpush=webpush)
            messaging.send(message)

            print('Subscription %s notified about %s\
                   successfully!' % (sub.id, post.id))

        except Exception as e:
            sentry_sdk.capture_exception(e)
            raise e
Exemplo n.º 18
0
        notification=messaging.AndroidNotification(
            title='알림인데',
            body='백그라운드 자비 좀',
            icon='',
            color='#f45342',
            sound='default'
        ),
    ),
    data={
        'score': '850',
        'time': '2:45',
    },
    webpush=messaging.WebpushConfig(
        notification=messaging.WebpushNotification(
            title='웹 알림',
            body='여긴 어떨까',
            icon='',
        ),
    ),
    topic=topic
    #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 fcm_push(notification_id, tokens=None):
    """
    FCM message push, either to all users subscribed to the
    topic(category slug), or to a specific user targeted by the specified token.
    :param notification_id: Notification id.
    :param tokens: Specific tokens of clients to push the notification to.
    :return: None
    """

    try:
        notification = Notification.objects.get(id=notification_id)
        app_config = notification.category.app_config

    except Notification.DoesNotExist:
        return False

    base_notification = messaging.Notification(
        title=notification.category.name,
        body=notification.template,
    )
    android_conf = messaging.AndroidConfig(
        notification=messaging.AndroidNotification(
            click_action=notification.android_onclick_activity))

    if app_config is not None and app_config.assets is not None:
        icon_url = os.path.join(
            settings.STATIC_URL,
            app_config.base_urls.static,
            'assets',
            app_config.assets.logo,
        )
    else:
        icon_url = os.path.join(
            settings.STATIC_URL, 'notifications',
            settings.DISCOVERY.get_app_configuration(
                'notifications').base_urls.static, 'bell_icon.svg')

    webpush_conf = messaging.WebpushConfig(
        notification=messaging.WebpushNotification(
            icon=icon_url,
            actions=[
                messaging.WebpushNotificationAction(
                    action=notification.web_onclick_url,
                    title=f'Open {notification.web_onclick_url}')
            ]))

    # If tokens are provided, make a multicast message
    # else it is assumed that it is a topic based broadcast
    if tokens:
        message = messaging.MulticastMessage(notification=base_notification,
                                             android=android_conf,
                                             webpush=webpush_conf,
                                             tokens=tokens)
    else:
        message = messaging.Message(notification=base_notification,
                                    android=android_conf,
                                    webpush=webpush_conf,
                                    topic=notification.category.slug)

    try:
        # use dry_run = True for testing purpose
        if tokens:
            _ = messaging.send_multicast(message, dry_run=False)
        else:
            _ = messaging.send(message, dry_run=False)
    except messaging.ApiCallError as e:
        return False
    except ValueError as e:
        return False

    return True
Exemplo n.º 20
0
    def construct_body(title: str, topic: str, category: str = None,
                       data: dict = None, body_text: str = '',
                       alert_sound: str = 'default', critical: bool = False,
                       web_badge: str = '', web_icon: str = '',
                       vibration_pattern: Sequence[int] = None,
                       priority: str = 'normal'):
        if data is None:
            data = {}
        if vibration_pattern is None:
            vibration_pattern = DEFAULT_VIBRATION_PATTERN

        android_notification_additional_config = {}
        aps_additional_config = {}

        if category is not None:
            android_notification_additional_config['click_action'] = category
            aps_additional_config['category'] = category

        # https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html#//apple_ref/doc/uid/TP40008194-CH17-SW5
        fcm_body = {
            'data': data,
            'android': messaging.AndroidConfig(
                priority=ANDROID_PRIORITIES[priority],  # normal and high
                ttl=300,
                notification=messaging.AndroidNotification(
                    title=title,
                    body=body_text,
                    **android_notification_additional_config,
                ),
            ),
            'webpush': messaging.WebpushConfig(
                headers={
                    'TTL': '300',
                    'Urgency': priority,  # can be very-low, low, normal, or high
                    'Topic': topic,
                },
                # Send everything in a dict instead so that we can handle the notifications ourselves.
                data=dict(
                    notification=json.dumps(dict(
                        title=title,
                        body=body_text,
                        # URL for badge icon
                        badge=web_badge,
                        icon=web_icon,  # URL for icon
                        # should the user be renotified if an old notification is replaced by a new one
                        # renotify=True,
                        # Should the notification remain active until the user clicks or dismisses it rather than closing automatically
                        require_interaction=False,
                        silent=False,  # should the notification be comletely silent regardless of device settings
                        # vibration pattern
                        vibrate=vibration_pattern,
                    )),
                    **data
                ),
                # fcm_options=messaging.WebpushFcmOptions(
                #     link='',  # link to open when the user clicks on the notification
                # ),
            ),
            'apns': messaging.APNSConfig(
                headers={
                    # The date at which the notification is no longer valid. This value
                    # is a Unix epoch expressed in seconds (UTC). If the value is
                    # nonzero, APNs stores the notification and tries to deliver it at
                    # least once, repeating the attempt as needed until the specified
                    # date. If the value is 0, APNs attempts to deliver the
                    # notification only once and does not store the notification.
                    'apns-expiration': str(int(datetime.timestamp(
                        datetime.utcnow() + FIVE_MINUTES))),

                    # This should be the default, but we will specify it here manually.
                    # 10 should be immediate, while 5 does it based off of power
                    # considerations.
                    'apns-priority': IOS_PRIORITIES[priority],

                    # Generally the app's bundle ID.
                    # 'apns-topic': settings.FCM_NOTIFICATIONS['bundle_id'],

                    # 64 bytes at most and is used to collapse notifications if the
                    # notifications are the same.
                    'apns-collpase-id': topic,
                },
                payload=messaging.APNSPayload(
                    aps=messaging.Aps(
                        alert=messaging.ApsAlert(
                            title=title,  # short string that descirbes purpose
                            # subtitle='',
                            body=body_text,  # body text of message
                        ),
                        # badge=0,  # badge counter
                        sound=messaging.CriticalSound(
                            alert_sound, critical=critical, volume=1),  # sound to play
                        content_available=True,  # use 1 to indicate that the system has new data to handle

                        # used for grouping along with a Notification Content app extension
                        mutable_content=True,
                        custom_data=data,
                        **aps_additional_config,
                    ),
                    **data
                ),
            ),
        }

        return fcm_body
Exemplo n.º 21
0
def create_job_page(request):
    current_customer = request.user.customer

    if not current_customer.stripe_payment_method_id:
        return redirect(reverse('customer:payment_method'))

    has_current_job = Job.objects.filter(customer=current_customer,
                                         status__in=[
                                             Job.PROCESSING_STATUS,
                                             Job.PICKING_STATUS,
                                             Job.DELIVERING_STATUS
                                         ]).exists()

    if has_current_job:
        messages.warning(request, "You currently have a processing job.")
        return redirect(reverse('customer:current_jobs'))

    creating_job = Job.objects.filter(customer=current_customer,
                                      status=Job.CREATING_STATUS).last()
    step1_form = forms.JobCreateStep1Form(instance=creating_job)
    step2_form = forms.JobCreateStep2Form(instance=creating_job)
    step3_form = forms.JobCreateStep3Form(instance=creating_job)

    if request.method == "POST":
        if request.POST.get('step') == '1':
            step1_form = forms.JobCreateStep1Form(request.POST,
                                                  request.FILES,
                                                  instance=creating_job)
            if step1_form.is_valid():
                creating_job = step1_form.save(commit=False)
                creating_job.customer = current_customer
                creating_job.save()
                return redirect(reverse('customer:create_job'))

        elif request.POST.get('step') == '2':
            step2_form = forms.JobCreateStep2Form(request.POST,
                                                  instance=creating_job)
            if step2_form.is_valid():
                creating_job = step2_form.save()
                return redirect(reverse('customer:create_job'))

        elif request.POST.get('step') == '3':
            step3_form = forms.JobCreateStep3Form(request.POST,
                                                  instance=creating_job)
            if step3_form.is_valid():
                creating_job = step3_form.save()

                try:
                    r = requests.get(
                        "https://maps.googleapis.com/maps/api/distancematrix/json?origins={}&destinations={}&mode=transit&key={}"
                        .format(
                            creating_job.pickup_address,
                            creating_job.delivery_address,
                            settings.GOOGLE_MAP_API_KEY,
                        ))

                    print(r.json()['rows'])

                    distance = r.json(
                    )['rows'][0]['elements'][0]['distance']['value']
                    duration = r.json(
                    )['rows'][0]['elements'][0]['duration']['value']
                    creating_job.distance = round(distance / 1000, 2)
                    creating_job.duration = int(duration / 60)
                    creating_job.price = creating_job.distance * 1  # $1 per km
                    creating_job.save()

                except Exception as e:
                    print(e)
                    messages.error(
                        request,
                        "Unfortunately, we do not support shipping at this distance"
                    )

                return redirect(reverse('customer:create_job'))

        elif request.POST.get('step') == '4':
            if creating_job.price:
                try:
                    payment_intent = stripe.PaymentIntent.create(
                        amount=int(creating_job.price * 100),
                        currency='usd',
                        customer=current_customer.stripe_customer_id,
                        payment_method=current_customer.
                        stripe_payment_method_id,
                        off_session=True,
                        confirm=True,
                    )

                    Transaction.objects.create(
                        stripe_payment_intent_id=payment_intent['id'],
                        job=creating_job,
                        amount=creating_job.price,
                    )

                    creating_job.status = Job.PROCESSING_STATUS
                    creating_job.save()

                    # Send Push Notification to all Couriers
                    couriers = Courier.objects.all()
                    registration_tokens = [
                        i.fcm_token for i in couriers if i.fcm_token
                    ]

                    message = messaging.MulticastMessage(
                        notification=messaging.Notification(
                            title=creating_job.name,
                            body=creating_job.description,
                        ),
                        webpush=messaging.WebpushConfig(
                            notification=messaging.WebpushNotification(
                                icon=creating_job.photo.url, ),
                            fcm_options=messaging.WebpushFCMOptions(
                                link=settings.NOTIFICATION_URL +
                                reverse('courier:available_jobs'), ),
                        ),
                        tokens=registration_tokens)
                    response = messaging.send_multicast(message)
                    print('{0} messages were sent successfully'.format(
                        response.success_count))

                    return redirect(reverse('customer:home'))

                except stripe.error.CardError as e:
                    err = e.error
                    # Error code will be authentication_required if authentication is needed
                    print("Code is: %s" % err.code)
                    payment_intent_id = err.payment_intent['id']
                    payment_intent = stripe.PaymentIntent.retrieve(
                        payment_intent_id)

    # Determine the current step
    if not creating_job:
        current_step = 1
    elif creating_job.delivery_name:
        current_step = 4
    elif creating_job.pickup_name:
        current_step = 3
    else:
        current_step = 2

    return render(
        request, 'customer/create_job.html', {
            "job": creating_job,
            "step": current_step,
            "step1_form": step1_form,
            "step2_form": step2_form,
            "step3_form": step3_form,
            "GOOGLE_MAP_API_KEY": settings.GOOGLE_MAP_API_KEY
        })
Exemplo n.º 22
0
def test_firebase_call():
    print('1')
    if not firebase_admin._apps:
        cred = credentials.Certificate(cred_cert)
        default_app = firebase_admin.initialize_app(cred)

    print('2')
    body = 'Remind time 00:00'
    n = messaging.Notification(title='test_firebase_call',
                               body=body,
                               image=None)
    priority = 'normal'
    myicon = 'https://rusel.by/static/rok/img/test-192.png'
    mybadge = 'https://rusel.by/static/rok/img/test-72.png'
    click_action = 'https://rusel.by/todo/99999/'
    an = messaging.AndroidNotification(title = 'test_firebase_call', body = body, icon = myicon, color = None, sound = None, tag = None, click_action = click_action, body_loc_key = None, \
                                       body_loc_args = None, title_loc_key = None, title_loc_args = None, channel_id = None, image = None, ticker = None, sticky = None, \
                                       event_timestamp = None, local_only = None, priority = None, vibrate_timings_millis = None, default_vibrate_timings = None, \
                                       default_sound = None, light_settings = None, default_light_settings = None, visibility = None, notification_count = None)
    añ = messaging.AndroidConfig(collapse_key=None,
                                 priority=priority,
                                 ttl=None,
                                 restricted_package_name=None,
                                 data=None,
                                 notification=an,
                                 fcm_options=None)
    actions = []
    a1 = messaging.WebpushNotificationAction(
        'postpone',
        'Postpone',
        icon='https://rusel.by/static/todo/icon/remind-today.png')
    a2 = messaging.WebpushNotificationAction(
        'done', 'Done', icon='https://rusel.by/static/rok/icon/delete.png')
    actions.append(a1)
    actions.append(a2)

    print('3')
    #wn = messaging.WebpushNotification(title = task.name, body = body, icon = icon, actions = actions, badge = None, data = None, direction = None, image = None, language = None, renotify = True, require_interaction = True, silent = False, tag = None, timestamp_millis = None, vibrate = None, custom_data = None)
    wn = messaging.WebpushNotification(
        title='test_firebase_call',
        body=body,
        icon=myicon,
        badge=mybadge,
        actions=actions,
        tag='99999',
        custom_data={"click_action": click_action})
    wo = messaging.WebpushFCMOptions(click_action)
    wc = messaging.WebpushConfig(headers=None,
                                 data=None,
                                 notification=wn,
                                 fcm_options=None)

    tokens = []
    tokens.append(
        'dq6oUJNrQ2IYcm3mVtzfw8:APA91bE_3q9CdIAMWw6Blh0uGmLve5dv_AeHY4kJec6tGM34Vw3wMN6WIEZveI60Yl0neNeeSzmD1zwcvuC0A49Ht7t90mHxD47jE8duyQX0090qRflS7hVo0lm-qJ_wLJsJ59_nJFtQ'
    )

    print('4')
    mm = messaging.MulticastMessage(tokens=tokens,
                                    data=None,
                                    notification=n,
                                    android=None,
                                    webpush=wc,
                                    apns=None,
                                    fcm_options=None)
    print('5')
    r = messaging.send_multicast(mm, dry_run=False, app=None)
    print('6')
    ret_resp = '[' + str(len(r.responses)) + ']: '
    npp = 0
    for z in r.responses:
        if (len(ret_resp) > 0):
            ret_resp += ', '
        if z.success:
            ret_resp += '1'
        else:
            ret_resp += '0 ' + z.exception.code
            if (z.exception.code == 'NOT_FOUND'):
                ss[npp].delete()
        npp += 1

        if z.message_id:
            ret_resp += ':' + z.message_id
Exemplo n.º 23
0
def remind_one_task(log, task):
    if not firebase_admin._apps:
        cred = credentials.Certificate(cred_cert)
        firebase_admin.initialize_app(cred)

    body = task['term'] + ' - ' + task['group']
    n = messaging.Notification(title=task['name'], body=body, image=None)
    if (task['important']):
        priority = 'high'
    else:
        priority = 'normal'
    myicon = HOST + '/static/rusel.png'
    mybadge = ''
    click_action = HOST + '/todo/' + str(task['id']) + '/'
    an = messaging.AndroidNotification(title=task['name'], body=body, icon=myicon, color=None, sound=None, tag=None, click_action=click_action, body_loc_key=None, \
                                       body_loc_args=None, title_loc_key=None, title_loc_args=None, channel_id=None, image=None, ticker=None, sticky=None, \
                                       event_timestamp=None, local_only=None, priority=None, vibrate_timings_millis=None, default_vibrate_timings=None, \
                                       default_sound=None, light_settings=None, default_light_settings=None, visibility=None, notification_count=None)
    messaging.AndroidConfig(collapse_key=None, priority=priority, ttl=None, restricted_package_name=None, data=None, notification=an, fcm_options=None)
    actions = []
    a1 = messaging.WebpushNotificationAction('postpone', 'Postpone 1 hour', icon=HOST+'/static/icons/postpone.png')
    a2 = messaging.WebpushNotificationAction('done', 'Done', icon=HOST+'/static/icons/completed.png')
    actions.append(a1)
    actions.append(a2)

    wn = messaging.WebpushNotification(title=task['name'], body=body, icon=myicon, badge=mybadge, actions=actions, tag=str(task['id']), custom_data={"click_action": click_action})
    messaging.WebpushFCMOptions(click_action)
    wc = messaging.WebpushConfig(headers=None, data=None, notification=wn, fcm_options=None)
    
    resp = requests.get(TASK_API_TOKENS.format(task['user_id']), headers=headers, verify=verify)
    data = resp.json()
    if ('result' not in data) or (len(data['result']) == 0):
        log('[TODO] No tokens for user_id = ' + str(task['user_id']))
        return
    tokens = data['result']
    
    mm = messaging.MulticastMessage(tokens=tokens, data=None, notification=n, android=None, webpush=wc, apns=None, fcm_options=None)
    r = messaging.send_multicast(mm, dry_run=False, app=None)
    ret_resp = '[' + str(len(r.responses)) + ']'
    log('[TODO] Remind task ID: {}, ok: {}, err: {}, resp: {}, name: "{}"'.format(task['id'], r.success_count, r.failure_count, ret_resp, task['name']))
    npp = 1
    for z in r.responses:
        if z.success:
            status = 'Success'
            error_desc = ''
        else:
            status = 'Fail'
            error_desc = ', ' + z.exception.code
        msg = ''
        if z.message_id:
            msg += ', message_id = "' + z.message_id + '"'
        log('       {}. {}{}{}'.format(npp, status, error_desc, msg))
        log('       token "' + tokens[npp-1] + '"')
        if (not z.success) and (z.exception.code == 'NOT_FOUND'):
            resp = requests.get(TASK_API_DEL_TOKEN.format(task['user_id'], tokens[npp-1]), headers=headers, verify=verify)
            data = resp.json()
            if ('result' not in data) and data['result']:
                log('       [!] Token deleted.')
        npp += 1

    requests.get(TASK_API_REMINDED.format(task['id']), headers=headers, verify=verify)
 def test_invalid_data(self, data):
     with pytest.raises(ValueError):
         check_encoding(
             messaging.Message(topic='topic',
                               webpush=messaging.WebpushConfig(data=data)))