Exemplo n.º 1
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
Exemplo n.º 2
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.º 3
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.º 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
Exemplo n.º 5
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.º 6
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.º 7
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)
Exemplo n.º 8
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
        })