示例#1
0
    def quiz_reminder(self, uid, module, quiz, quiz_ref=None):
        doc_ref = self.db.collection(u'users').document(uid)
        curr = doc_ref.get().to_dict()
        curr = curr[u'token']
        if quiz_ref == None:
            message = messaging.Message(
                notification=messaging.Notification(
                    title='Remider to do task: {}'.format(quiz),
                    body='Here is a reminder to perform your task!',
                ),
                token=curr,
            )
        else:
            message = messaging.Message(
                data={
                    'quiz': quiz_ref,
                },
                notification=messaging.Notification(
                    title='Remider to do quiz: {}'.format(quiz),
                    body='Time for you to refresh your memory with this quiz!',
                ),
                token=curr,
            )

            # Send a message to the device corresponding to the provided
            # registration token.
        response = messaging.send(message)
示例#2
0
    def fcm_notification(self):
        from firebase_admin import messaging
        # Construct Team-specific payload
        if self.team:
            if len(self.team_awards) == 1:
                award = self.team_awards[0]
                # For WINNER/FINALIST, change our verbage
                if award.award_type_enum in [
                        AwardType.WINNER, AwardType.FINALIST
                ]:
                    body = 'is the'
                else:
                    body = 'won the'
                body = '{} {}'.format(body, award.name_str)
            else:
                body = 'won {} awards'.format(len(self.team_awards))
            return messaging.Notification(
                title='Team {} Awards'.format(self.team.team_number),
                body='Team {} {} at the {} {}.'.format(
                    self.team.team_number, body, self.event.year,
                    self.event.normalized_name))

        # Construct Event payload
        return messaging.Notification(
            title='{} Awards'.format(self.event.event_short.upper()),
            body='{} {} awards have been posted.'.format(
                self.event.year, self.event.normalized_name))
示例#3
0
def test_send_all():
    messages = [
        messaging.Message(
            topic='foo-bar', notification=messaging.Notification('Title', 'Body')),
        messaging.Message(
            topic='foo-bar', notification=messaging.Notification('Title', 'Body')),
        messaging.Message(
            token='not-a-token', notification=messaging.Notification('Title', 'Body')),
    ]

    batch_response = messaging.send_all(messages, dry_run=True)

    assert batch_response.success_count == 2
    assert batch_response.failure_count == 1
    assert len(batch_response.responses) == 3

    response = batch_response.responses[0]
    assert response.success is True
    assert response.exception is None
    assert re.match('^projects/.*/messages/.*$', response.message_id)

    response = batch_response.responses[1]
    assert response.success is True
    assert response.exception is None
    assert re.match('^projects/.*/messages/.*$', response.message_id)

    response = batch_response.responses[2]
    assert response.success is False
    assert isinstance(response.exception, exceptions.InvalidArgumentError)
    assert response.message_id is None
示例#4
0
 def send_entity_message(cls, data, entity):
     """
     Gets the message content for Entities
     """
     topic = 'E_'+str(entity.id)
     if data.get('is_workshop', True):
         msg_notification=messaging.Notification(
             title="New Workshop in "+str(entity.name),
             body=data['title']+" on "+str(data['date'].strftime('%d-%m-%Y')),
             image=data.get('image_url',''))
     else:
         msg_notification=messaging.Notification(
             title="New Event in "+str(entity.name),
             body=data['title']+" on "+str(data['date'].strftime('%d-%m-%Y')),
             image=data.get('image_url',''))
     message = messaging.Message(
         notification=msg_notification,
         topic=topic
     )
     try:
         response = messaging.send(message)
         logger.info('[Topic %s] Successfully sent message: %s', topic, response)
     except (exceptions.FirebaseError, TransportError) as e:
         logger.warning('[Topic %s] Could not send notification!', topic)
         logger.error(e)
 def test_notification_message(self):
     check_encoding(
         messaging.Message(topic='topic', notification=messaging.Notification()),
         {'topic': 'topic'})
     check_encoding(
         messaging.Message(topic='topic', notification=messaging.Notification('t', 'b')),
         {'topic': 'topic', 'notification': {'title': 't', 'body': 'b'}})
     check_encoding(
         messaging.Message(topic='topic', notification=messaging.Notification('t')),
         {'topic': 'topic', 'notification': {'title': 't'}})
    def push_notifications(self, request):
        request.current_app = self.name
        context = dict(
           # Include common variables for rendering the admin template.
           self.each_context(request),
        )

        users = UserInformation.objects.all().order_by('first_name')
        context['users'] = users
        
        if request.method == "POST":
            if not firebase_admin._apps:
                cred = credentials.Certificate(os.path.join(settings.BASE_DIR, 'firebase_admin.json'))
                firebase_admin.initialize_app(cred)


            try:
                fcm = UserInformation.objects.get(pk=request.POST['user_id']).fcm

                message = messaging.Message(
                    notification=messaging.Notification(
                        title=request.POST['title'],
                        body=request.POST['message'],
                    ),
                    token=fcm,
                )
                
                response = messaging.send(message)
                print(response)
            except:
                try:
                    for user_id in request.POST.getlist('user_id'):
                        fcm = UserInformation.objects.get(pk=user_id).fcm

                        message = messaging.Message(
                            notification=messaging.Notification(
                            title=request.POST['title'],
                            body=request.POST['message'],
                            ),
                            token=fcm,
                        )

                        response = messaging.send(message)
                except:
                    context["user_not_registered"] = 1

        

        return TemplateResponse(request, "push-notifications.html", context)
示例#7
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
示例#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()
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)
示例#10
0
    def send_message(self, user_token, title, *args, **kwargs):
        if not user_token:
            return None

        body = kwargs.get('body', None)
        message = messaging.Message(notification=messaging.Notification(title, body), token=user_token)
        return messaging.send(message)
示例#11
0
def index(request):
    cred = credentials.Certificate('service_key.json')
    try:
        app = firebase_admin.get_app()
    except ValueError:
        app = firebase_admin.initialize_app(cred, {'databaseURL': 'https://kagandroidapp.firebaseio.com/'})

    if request.method == 'POST':
        form = FcmForm(request.POST)
        if form.is_valid():
            message = messaging.Message(
                notification=messaging.Notification(
                    title=form.cleaned_data['title'],
                    body=form.cleaned_data['msg']
                ),
                android=messaging.AndroidConfig(
                    restricted_package_name='com.simaskuprelis.kag_androidapp.dev'
                ),
                topic='test'
            )
            print(messaging.send(message, app=app))
    else:
        form = FcmForm()

    return render(request, 'index.html', {'form': form})
示例#12
0
def test_send_invalid_token():
    msg = messaging.Message(
        token=_REGISTRATION_TOKEN,
        notification=messaging.Notification('test-title', 'test-body')
    )
    with pytest.raises(messaging.SenderIdMismatchError):
        messaging.send(msg, dry_run=True)
示例#13
0
文件: fcm.py 项目: sn94/uvSkin
    def messaging_from_firestore2(self):
        #consulta lo de cloud firestore
        # Use a service account
        import firebase_admin
        from firebase_admin import credentials

        #cred = credentials.Certificate('uvapp-246400-9e75d4d9608a.json')
        #'uvapp-246400-04d67e9d0c21firebasecount.json'
        #'uvapp-246400-6c35cea9bf32default.json
        cred = credentials.Certificate(
            'uvapp-246400-04d67e9d0c21firebasecount.json')
        app = firebase_admin.initialize_app(cred)

        from firebase_admin import firestore
        db = firestore.client()
        users_ref = db.collection(u'usuarios')
        docs = users_ref.get()

        from firebase_admin import messaging
        for doc in docs:
            #registro_id= doc.id
            registro_user = doc.to_dict()
            token = registro_user['token']
            a_notification = messaging.Notification(title="hola",
                                                    body="quetal")
            message = messaging.Message(data=None,
                                        notification=a_notification,
                                        token=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)
            #self.send_a_notification_sdk_admin( "iuv alto","cuidate",token )
        firebase_admin.delete_app(app)  #borrar instancia anterior
示例#14
0
 def send_topic_notification(self, topic):
     message = messaging.Message(notification=messaging.Notification(
         title=self.title, body=self.body, image=self.image),
                                 topic=topic)
     response = messaging.send(message)
     # Response is a message ID string.
     print('Successfully sent message:', response)
示例#15
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)
示例#16
0
    def call(self, title: str = '', body: str = ''):

        token = "asfdjkladjfkaldjfklajdfkl2j13klj132kljkl"

        messages = []
        message = messaging.Message(notification=messaging.Notification(
            title=title, body=body),
                                    token=token,
                                    data=None,
                                    android=AndroidConfig(priority=10, ttl=45))

        messages.append(message)

        if len(messages) == 0:
            batch_rsp = messaging.send_all(messages)
            i = 0
            failed_ids = []
            for rsp in batch_rsp.responses:
                if rsp.exception:
                    if rsp.exception.http_response.status_code in [404, 400]:
                        failed_ids.append(token)
                    else:
                        logger.warning(f"failed fcm batch send: {token}")

                i += 1
            return failed_ids
示例#17
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")
示例#18
0
def send_notification(title, message, to=[], data={}):
    data.update({
        "body": message,
        "title": title,
        'type':
        'confimar_embarque',  # aqui vai a informacao sobre o tipo da notificacao
        'email': '*****@*****.**',  # aqui vai o email do usuário
        "click_action": "FLUTTER_NOTIFICATION_CLICK",
        'data': json.dumps({'email': '*****@*****.**'})
    })
    registration_tokens = to

    message = messaging.MulticastMessage(
        notification=messaging.Notification(
            title=title,
            body=message,
        ),
        android=messaging.AndroidConfig(
            ttl=datetime.timedelta(seconds=5 * 60),
            priority='high',
            notification=messaging.AndroidNotification(
                icon='stock_ticker_update',
                color='#f45342',
                sound='default',
                # click_action='FLUTTER_NOTIFICATION_CLICK',
            ),
        ),
        data=data,
        tokens=registration_tokens,
    )
    response = messaging.send_multicast(message)
    print('data: {}\n'.format(data))
    print('{0} messages were sent successfully'.format(response.success_count))
 def fcm_notification(self):
     from firebase_admin import messaging
     return messaging.Notification(
         title='{} District Points Updated'.format(
             self.district.abbreviation.upper()),
         body='{} district point calculations have been updated.'.format(
             self.district.display_name))
示例#20
0
def send_alarm(sender, instance, created, **kwargs):
    if created:
        devices = Device.objects.filter(
            owner_id__in=instance.organization.members.all())
        message = messaging.Message(notification=messaging.Notification(
            title=instance.title,
            body=instance.message,
        ))

        error_tokens = []

        for device in devices:
            message.token = device.fcm_token

            try:
                messaging.send(message, app=firebase_app, dry_run=False)
            except ApiCallError as err:
                code = err.code

                # Old error list
                # error_list = ['MissingRegistration', 'MismatchSenderId', 'InvalidRegistration', 'NotRegistered']

                error_list = [
                    'invalid-registration-token',
                    'registration-token-not-registered',
                    'invalid-package-name', 'invalid-recipient',
                    'invalid-argument'
                ]
                if code in error_list:
                    error_tokens.append(device.fcm_token)

        # delete all devices with invalid recipients
        if error_tokens:
            Device.objects.filter(fcm_token__in=error_tokens).delete()
示例#21
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
示例#22
0
 def fcm_notification(self):
     from firebase_admin import messaging
     return messaging.Notification(
         title='{} Alliances Updated'.format(
             self.event.event_short.upper()),
         body='{} alliances have been updated.'.format(
             self.event.normalized_name))
示例#23
0
    def send(self, **kwargs):
        if self:
            success_total = 0
            failure_total = 0
            ttl = kwargs.get("ttl", 3600)

            for lang in settings.LANGUAGES:
                with override(lang[0]):
                    reg_ids = list(
                        Device.objects.filter(
                            user__in=self.users.all(),
                            receive_category__key=self.category_id,
                            active=True,
                            language=lang[0],
                        ).values_list("registration_id", flat=True))

                    data = kwargs.get("data", {})
                    if self.url is not None:
                        data["url"] = self.url
                    data["title"] = self.title
                    data["body"] = str(self.body)

                    message = messaging.Message(
                        notification=messaging.Notification(
                            title=data["title"],
                            body=data["body"],
                        ),
                        data=data,
                        android=messaging.AndroidConfig(
                            ttl=datetime.timedelta(seconds=ttl),
                            priority="normal",
                            notification=messaging.AndroidNotification(
                                color="#E62272",
                                sound="default",
                            ),
                        ),
                    )

                    for reg_id in reg_ids:
                        message.token = reg_id
                        try:
                            messaging.send(message,
                                           dry_run=kwargs.get(
                                               "dry_run", False))
                            success_total += 1
                        except messaging.UnregisteredError:
                            failure_total += 1
                            Device.objects.filter(
                                registration_id=reg_id).delete()
                        except exceptions.InvalidArgumentError:
                            failure_total += 1
                            Device.objects.filter(
                                registration_id=reg_id).update(active=False)
                        except exceptions.FirebaseError:
                            failure_total += 1

            self.sent = timezone.now()
            self.success = success_total
            self.failure = failure_total
            self.save()
示例#24
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)
示例#25
0
def test_send_malformed_token():
    msg = messaging.Message(
        token='not-a-token',
        notification=messaging.Notification('test-title', 'test-body')
    )
    with pytest.raises(exceptions.InvalidArgumentError):
        messaging.send(msg, dry_run=True)
 def test_invalid_body(self, data):
     with pytest.raises(ValueError) as excinfo:
         check_encoding(
             messaging.Message(
                 topic='topic',
                 notification=messaging.Notification(body=data)))
     assert str(excinfo.value) == 'Notification.body must be a string.'
示例#27
0
def prediction(current_frames, original_footage):
    current_frames = current_frames.reshape(1, 64, 224, 224, 5)
    prediction = model.predict(current_frames)

    if prediction[0][0] > 0.75:  # Assuming model predicts as [Nonviolence,Violence]
        global hit
        hit = True
        print("Violence Detected")

        now = datetime.now().strftime("%Y%m%d%H%M%s")
        fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
        video_filename = f'Videos/{topic}_{now}.mp4'
        out = cv2.VideoWriter(video_filename, fourcc, camera_fps,
                              (original_footage[0].shape[1], original_footage[0].shape[0]))
        for frame in original_footage:
            out.write(frame)
        out.release()
        blob = bucket.blob(f"{topic}_{now}.mp4")
        blob.upload_from_filename(filename=video_filename)
        data = {
            "click_action": "FLUTTER_NOTIFICATION_CLICK",
            "camID": "007",
            "latitude": "23.4",
            "longitude": "89.1",
            "file": f"{topic}_{now}"
        }
        message = messaging.Message(
            notification=messaging.Notification(
                body="Violence Detected", title="Test Message"),
            topic=topic,
            data=data
        )
        response = messaging.send(message)
        print('Successfully sent message:', response)
    print(prediction)
def _send_android_notification(token_shops: dict, coupon_description: str):
    if not token_shops:
        return

    body = coupon_description or "Смотри подробнее в приложении!"

    android_params = messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=3600), priority='high')

    failed_tokens = []

    for chunk in chunks(list(token_shops.items()), 500):
        registration_tokens = []

        for token, shops in chunk:
            registration_tokens.append(token)

            notification = messaging.Notification(
                title=f"Новый купон в {', '.join(shops)}🔥", body=body)

            multicast_message = messaging.MulticastMessage(
                notification=notification,
                android=android_params,
                tokens=registration_tokens,
            )

        batch_failed_tokens = _send_firebase_request(registration_tokens,
                                                     multicast_message)
        failed_tokens.extend(batch_failed_tokens)
        batch_failed_tokens = []

    users.delete_tokens(failed_tokens, is_ios=False)
示例#29
0
    def fcm_notification(self):
        winning_alliance = self.match.winning_alliance
        losing_alliance = self.match.losing_alliance

        alliance_one = self.match.alliances[
            winning_alliance] if winning_alliance is not '' else self.match.alliances[
                'red']
        alliance_two = self.match.alliances[
            losing_alliance] if losing_alliance is not '' else self.match.alliances[
                'blue']

        # [3:] to remove 'frc' prefix
        alliance_one_teams = ', '.join(
            [team[3:] for team in alliance_one['teams']])
        alliance_two_teams = ', '.join(
            [team[3:] for team in alliance_two['teams']])

        alliance_one_score = alliance_one['score']
        alliance_two_score = alliance_two['score']
        if alliance_one_score == alliance_two_score:
            action = 'tied with'
        else:
            action = 'beat'

        from firebase_admin import messaging
        return messaging.Notification(
            title='{} {} Results'.format(self.event.event_short.upper(),
                                         self.match.short_name),
            body='{} {} {} scoring {}-{}.'.format(alliance_one_teams, action,
                                                  alliance_two_teams,
                                                  alliance_one_score,
                                                  alliance_two_score))
    def fcm_notification(self):
        body = [
            '{} alliances have been updated.'.format(
                self.event.normalized_name)
        ]
        # Add alliance information for team
        if self.team and self.alliance:
            sub_body = ['Team {}'.format(self.team.team_number)]
            if self.alliance['picks'][0] == self.team.key_name:
                sub_body.append('is Captain of')
            else:
                sub_body.append('is on')
            # Get alliance number
            alliance_number = self.event.alliance_selections.index(
                self.alliance) + 1
            sub_body.append('Alliance {} with'.format(alliance_number))
            # [3:] to remove 'frc' prefix
            team_names = [
                'Team {}'.format(team_key[3:])
                for team_key in self.alliance['picks']
                if team_key != self.team.key_name
            ]
            # A gorgeous, gramatically correct list comprehension
            # Format is like 'Team 1, Team 2, and Team 3' or just 'Team 2 and Team 3'
            sub_body.append(
                ' and '.join([', '.join(team_names[:-1]), team_names[-1]]) +
                '.')
            body.append(' '.join(sub_body))

        from firebase_admin import messaging
        return messaging.Notification(title='{} Alliances Updated'.format(
            self.event.event_short.upper()),
                                      body=' '.join(body))