Python pyfcm.FCMNotification() Examples

The following are 10 code examples of pyfcm.FCMNotification(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyfcm , or try the search function .
Example #1
Source File: android_app.py    From heltour with MIT License 6 votes vote down vote up
def _get_push_service():
    return FCMNotification(api_key=_get_fcm_key()) 
Example #2
Source File: fcm.py    From autopush with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, conf, router_conf, metrics):
        """Create a new FCM router and connect to FCM"""
        self.conf = conf
        self.router_conf = router_conf
        self.metrics = metrics
        self.min_ttl = router_conf.get("ttl", 60)
        self.dryRun = router_conf.get("dryrun", False)
        self.collapseKey = router_conf.get("collapseKey", "webpush")
        self.clients = {}
        try:
            for (sid, creds) in router_conf["creds"].items():
                self.clients[sid] = pyfcm.FCMNotification(
                    api_key=creds["auth"])
        except Exception as e:
            self.log.error("Could not instantiate FCM {ex}", ex=e)
            raise IOError("FCM Bridge not initiated in main")
        self._base_tags = ["platform:fcm"]
        self.log.debug("Starting FCM router...") 
Example #3
Source File: test_fcm.py    From PyFCM with MIT License 5 votes vote down vote up
def push_service():
    api_key = os.getenv("FCM_TEST_API_KEY", None)
    assert api_key, "Please set the environment variables for testing according to CONTRIBUTING.rst"

    return FCMNotification(api_key=api_key) 
Example #4
Source File: test_fcm.py    From PyFCM with MIT License 5 votes vote down vote up
def test_push_service_without_credentials():
    try:
        FCMNotification()
        assert False, "Should raise AuthenticationError without credentials"
    except errors.AuthenticationError:
        pass 
Example #5
Source File: fcm.py    From iris with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, config):
        self.config = config
        self.api_key = self.config.get('api_key')
        # FCM guarantees best-effort delivery with TTL 0
        self.ttl = self.config.get('ttl', 0)
        self.timeout = self.config.get('timeout', 10)
        self.default_notification = self.config.get('notification_title')
        self.proxy = None
        if 'proxy' in self.config:
            host = self.config['proxy']['host']
            port = self.config['proxy']['port']
            self.proxy = {'http': 'http://%s:%s' % (host, port),
                          'https': 'https://%s:%s' % (host, port)}
        self.client = FCMNotification(api_key=self.api_key, proxy_dict=self.proxy) 
Example #6
Source File: refresh-devices.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        # Initiate connection
        push_service = FCMNotification(api_key=settings.FCM_SERVER_KEY)

        # Refresh all
        for device in Device.objects.all():
            print(device.user.name + ' - ', end='', flush=True)
            if fill_device_firebase(push_service, device):
                print('OK')
            else:
                device.delete()
                print('FAIL') 
Example #7
Source File: notify-event-starting.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        # Initiate connection
        push_service = FCMNotification(api_key=settings.FCM_SERVER_KEY)

        # Maintain a count
        count = 0

        # Iterate all upcoming events
        for event in Event.objects.filter(
                start_time__range=(timezone.now(), timezone.now() + timedelta(minutes=30)),
                starting_notified=False):

            # Stop the spam!
            event.starting_notified = True
            event.notify = False
            event.save()

            # Event About to Start
            print('EATS -', event.name)

            # Construct object
            data_message = {
                "type": "event",
                "id": str(event.id),
                "title": event.name,
                "verb": "Event is about to start",
                "large_icon": event.bodies.first().image_url,
                "image_url": event.image_url
            }

            # Notify all followers
            for profile in event.followers.all():
                # Send FCM push notification
                for device in profile.devices.all():
                    count += send_notification_fcm(push_service, device, data_message)

        print('Sent', count, 'rich notifications')
        self.stdout.write(self.style.SUCCESS('Event starting chore completed successfully')) 
Example #8
Source File: tasks.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def push_notify(pk):
    """Push notify a notification."""
    setUp()
    notification = Notification.objects.filter(id=pk).first()

    # Check invalid subscriptions
    if not notification or notification.emailed or not notification.actor:
        return

    # Get the user's profile
    profile = notification.recipient.profile

    # Check bad users
    if not profile:
        return

    # Stop the spam!
    notification.emailed = True
    notification.save()

    # Get rich notification
    data_message = get_rich_notification(notification)

    # Get the API endpoint
    if not hasattr(settings, 'FCM_SERVER_KEY'):
        return

    push_service = FCMNotification(api_key=settings.FCM_SERVER_KEY)

    # Send FCM push notification
    for device in profile.devices.all():
        send_notification_fcm(push_service, device, data_message)

    # For each web push subscription
    for subscription in profile.web_push_subscriptions.all():
        send_notification_webpush(subscription, data_message) 
Example #9
Source File: push-notify.py    From instiapp-api with GNU Affero General Public License v3.0 4 votes vote down vote up
def handle(self, *args, **options):  # noqa: C901
        """Send Push notifications."""

        webpush_sent = 0
        webpush_total = 0
        fcm_sent = 0

        push_service = FCMNotification(api_key=settings.FCM_SERVER_KEY)

        # Iterate all unsent notifications
        for notification in Notification.objects.filter(emailed=False)[:1000]:

            # Check invalid subscriptions
            if not notification or not notification.actor:
                continue

            # Get the user's profile
            profile = notification.recipient.profile

            # Check bad users
            if not profile:
                continue

            # Stop the spam!
            notification.emailed = True
            notification.save()

            # Get rich notification
            data_message = get_rich_notification(notification)

            # Retro method for transition
            if profile.fcm_id and profile.fcm_id != '':
                send_fcm_notification_message(push_service, profile.fcm_id, data_message)

            # Send FCM push notification
            for device in profile.devices.all():
                fcm_sent += send_notification_fcm(push_service, device, data_message)

            # For each web push subscription
            for subscription in profile.web_push_subscriptions.all():
                webpush_total += 1
                webpush_sent += send_notification_webpush(subscription, data_message)

        print(
            "WebPush:", webpush_sent,
            "WebPush FAIL:", webpush_total - webpush_sent,
            "FCM:", fcm_sent
        )
        self.stdout.write(self.style.SUCCESS('Push notification chore completed successfully')) 
Example #10
Source File: fcm.py    From fcm-django with MIT License 4 votes vote down vote up
def fcm_send_topic_message(
        api_key=None,
        json_encoder=None,
        topic_name=None,
        message_body=None,
        message_title=None,
        message_icon=None,
        sound=None,
        condition=None,
        collapse_key=None,
        delay_while_idle=False,
        time_to_live=None,
        restricted_package_name=None,
        low_priority=False,
        dry_run=False,
        data_message=None,
        click_action=None,
        badge=None,
        color=None,
        tag=None,
        body_loc_key=None,
        body_loc_args=None,
        title_loc_key=None,
        title_loc_args=None,
        content_available=None,
        timeout=5,
        extra_notification_kwargs=None,
        extra_kwargs={}):

    if api_key is None:
        api_key = SETTINGS.get("FCM_SERVER_KEY")
    push_service = FCMNotification(api_key=api_key, json_encoder=json_encoder)
    result = push_service.notify_topic_subscribers(
        topic_name=topic_name,
        message_body=message_body,
        message_title=message_title,
        message_icon=message_icon,
        sound=sound,
        condition=condition,
        collapse_key=collapse_key,
        delay_while_idle=delay_while_idle,
        time_to_live=time_to_live,
        restricted_package_name=restricted_package_name,
        low_priority=low_priority,
        dry_run=dry_run,
        data_message=data_message,
        click_action=click_action,
        badge=badge,
        color=color,
        tag=tag,
        body_loc_key=body_loc_key,
        body_loc_args=body_loc_args,
        title_loc_key=title_loc_key,
        title_loc_args=title_loc_args,
        content_available=content_available,
        timeout=timeout,
        extra_kwargs=extra_kwargs,
        extra_notification_kwargs=extra_notification_kwargs,
    )

    return result