예제 #1
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")
예제 #2
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
예제 #3
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
예제 #4
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
예제 #5
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)
예제 #7
0
파일: user.py 프로젝트: dchen3121/backlog
    def send_slouch_notif(self):
        # using the firebase admin sdk for python
        # specs: https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging#webpushnotification
        # This registration token comes from the client FCM SDKs.

        # See documentation on defining a message payload.
        message = messaging.Message(
            webpush=messaging.WebpushNotification(
                title="Look out, you're slouching!", 
                icon="ICON_URL"),
            to="/topics/all"
        )

        # Send a message to the device corresponding to the provided
        # registration token.
        response = messaging.send(message)
예제 #8
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)
예제 #9
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
예제 #10
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
 def test_invalid_icon(self, data):
     notification = messaging.WebpushNotification(icon=data)
     excinfo = self._check_notification(notification)
     assert str(
         excinfo.value) == 'WebpushNotification.icon must be a string.'
예제 #12
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)
예제 #13
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
        })
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
예제 #15
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