Beispiel #1
0
    def send_visible_notification(self, token_map, title, message, json_data, dev=False):
        if len(token_map) == 0:
            logging.info("len(token_map) == 0, early return to save api calls")
            return

        # convert tokens if necessary
        fcm_token_map = self.convert_to_fcm_if_necessary(token_map, dev)

        push_service = FCMNotification(api_key=self.server_auth_token)
        data_message = {
           "data": json_data,
           "payload": json_data
        }
        # Send android and iOS messages separately because they have slightly
        # different formats
        # https://github.com/e-mission/e-mission-server/issues/564#issuecomment-360720598
        android_response = push_service.notify_multiple_devices(registration_ids=fcm_token_map["android"],
                                               data_message=data_message)
        ios_response = push_service.notify_multiple_devices(registration_ids=fcm_token_map["ios"],
                                               message_body = message,
                                               message_title = title,
                                               data_message=data_message)
        combo_response = {"ios": ios_response, "android": android_response}
        logging.debug(combo_response)
        return combo_response
Beispiel #2
0
 def push_notification(self, data):
     ret = {'is_success': True, 'error': ''}
     now_user = self.request.user
     to_list = []
     if self.is_super_admin:
         all_users_id = list(OSFUser.objects.all().values_list('pk', flat=True))
         all_tokens = RdmFcmDevice.objects.filter(user_id__in=all_users_id).distinct().values_list(
             'device_token', flat=True)
         to_list = list(all_tokens)
     elif self.is_admin:
         now_institutions_id = list(now_user.affiliated_institutions.all().values_list('pk', flat=True))
         all_institution_users_id = list(OSFUser.objects.filter(affiliated_institutions__in=now_institutions_id).distinct().values_list(
             'pk', flat=True))
         all_institution_tokens = RdmFcmDevice.objects.filter(user_id__in=all_institution_users_id).distinct().values_list(
             'device_token', flat=True)
         to_list = list(all_institution_tokens)
     else:
         ret['is_success'] = False
         return ret
     try:
         api_key = FCM_SETTINGS.get('FCM_SERVER_KEY')
         FCMNotification(api_key=api_key)
         push_service = FCMNotification(api_key=api_key)
         registration_ids = list(set(to_list))  # Remove duplicates
         message_title = data['title']
         message_body = data['body']
         push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title,
                                              message_body=message_body)
     except Exception as e:
         ret['is_success'] = False
         ret['error'] = 'Push notification error: ' + str(e)
     finally:
         return ret
Beispiel #3
0
    def send_visible_notification(self,
                                  token_list,
                                  title,
                                  message,
                                  json_data,
                                  dev=False):
        if len(token_list) == 0:
            logging.info(
                "len(token_list) == 0, early return to save api calls")
            return

        # convert tokens if necessary
        fcm_token_map = self.convert_to_fcm_if_necessary(token_list, dev)

        push_service = FCMNotification(api_key=self.server_auth_token)
        data_message = {"data": json_data, "payload": json_data}
        # Send android and iOS messages separately because they have slightly
        # different formats
        # https://github.com/e-mission/e-mission-server/issues/564#issuecomment-360720598
        android_response = push_service.notify_multiple_devices(
            registration_ids=fcm_token_map["android"],
            data_message=data_message)
        ios_response = push_service.notify_multiple_devices(
            registration_ids=fcm_token_map["ios"],
            message_body=message,
            message_title=title,
            data_message=data_message)
        combo_response = {"ios": ios_response, "android": android_response}
        logging.debug(combo_response)
        return combo_response
Beispiel #4
0
    def _notify(self, message):
        res = super(MailChannel, self)._notify(message)
        if self.env['ir.config_parameter'].sudo().get_param(
                'mail_notify.is_fcm_enabled'):
            push_service = FCMNotification(
                api_key=self.env['ir.config_parameter'].sudo().get_param(
                    'mail_notify.fcm_server_key'))
            base_url = self.env['ir.config_parameter'].sudo().get_param(
                'web.base.url') or ''
            message_values = message.message_format()[0]
            icon = message.author_id and (
                base_url +
                ('/web/image/res.partner/' + str(message.author_id.id) +
                 '/image_small')) or (base_url +
                                      '/mail/static/src/img/smiley/avatar.jpg')
            web_tokens = (message.sudo().mapped(
                'channel_ids.channel_partner_ids.user_ids') -
                          message.sudo().author_id.user_ids
                          ).mapped('token_ids').filtered(
                              lambda t: t.type == 'web').mapped('token')
            action_id = self.env.ref('mail.action_discuss').id
            #badge = ('/web/image/res.company/%s/badge' % str(self.env.user.company_id.id)) if self.env.user.company_id.badge else '/web/static/src/img/favicon.ico'

            if web_tokens:
                push_service.notify_multiple_devices(
                    registration_ids=web_tokens,
                    message_title=message_values['author_id'][1],
                    message_icon=icon,
                    click_action=base_url + '/web?#action=' + str(action_id) +
                    '&active_id=' + str(self.id),
                    #badge = base_url + badge,
                    message_body=html2text(message_values['body']))
        return res
Beispiel #5
0
def notify_webcam():
    try:
        content = json.loads(request.data)

        users = []
        lock = Locks.query.get(content['lockId'])
        username = lock.username
        owner = Users.query.get(username)

        push_service = FCMNotification(
            api_key=
            'AAAASi2VHpQ:APA91bGqzWABHfFOtzeuwc1AvIjGDCtXS90JkEErLxICILPrx81ScnzZv_AhE7um20rzOYTe28Hkhy_cF3Xj5ZqxucVaYRwkDGFIiUO3_RRbvfsr1kwsZDHdzZZJTCiPpu9whij3Puoo'
        )
        message_title = 'ACCESS'
        message_icon = 'notification_icon'
        message_body = 'Someone wishes to access ' + lock.alias
        push_service.notify_multiple_devices(registration_ids=owner.appIds,
                                             message_title=message_title,
                                             message_body=message_body,
                                             message_icon=message_icon,
                                             low_priority=False)

        for user in Acl.query.filter_by(lockId=content['lockId']):
            appIds = Users.query.get(user.username).appIds
            push_service.notify_multiple_devices(registration_ids=appIds,
                                                 message_title=message_title,
                                                 message_body=message_body,
                                                 message_icon=message_icon,
                                                 low_priority=False)

        return 'true'

    except Exception as e:
        return str(e)
Beispiel #6
0
def send_message(self, message_title, message_body, data_message=None):
        from pyfcm import FCMNotification
        push_service = FCMNotification(api_key=settings.NOTICATION_KEY)
        extra_notification_kwargs = {
            'android_channel_id': 'ONTECX-DEFAULT'
        }
        if data_message is not None:
            return push_service.notify_multiple_devices(registration_id=self.registration_id, message_title=message_title, message_body=message_body, data_message=data_message, extra_notification_kwargs=extra_notification_kwargs)
        return push_service.notify_multiple_devices(registration_id=self.registration_id, message_title=message_title, message_body=message_body, data_message=data_message, extra_notification_kwargs=extra_notification_kwargs)
Beispiel #7
0
def push_to_fcm_multy(device_token, gcm_key, title=None, message=None, data=None, sound=None, badge=None):
    fcm_push_service = FCMNotification(api_key=gcm_key)
    fcm_push_service.notify_multiple_devices(
        registration_ids=device_token,
        message_title=title,
        message_body=message,
        data_message=data,
        sound=sound,
        badge=badge
    )
 def handle(self, *args, **kwargs):
     data_message = dict(type="url", message="hello",
                         title="hell", url="url",
                         click_action="FLUTTER_NOTIFICATION_CLICK")
     push_service = FCMNotification(api_key=settings.FCM_API_KEY)
     registration_ids = Device.objects.all().values_list("registration_id",
                                                         flat=True)
     registration_ids = list(set(list(registration_ids)))
     push_service.notify_multiple_devices(
         registration_ids=registration_ids,
         message_title=data_message['type'],
         message_body=data_message["message"], data_message=data_message)
     self.stdout.write('Successfully send ..')
Beispiel #9
0
class FcmPi:

    def __init__(self): 

        # Here holds essential information, 
        # Firebase server key and device token.
        self._server_key = ''
        self._device_token = []

        with open(cf.FCM_SERVER_FILE, "r", encoding="utf-8") as file:
            self._server_key = file.readline()

        with open(cf.FCM_DEVICE_FILE, "r", encoding="utf-8") as device_file: # Read file.

            list = device_file.readlines() # Read api key

            # if there are multiple keys, then something is wrong.
            if len(list) is 0: 
                print('\tNo device token found.')

            else:
                # print('\tServer API key found.')
                for user in list:
                    self._device_token.append(str(user).rstrip('\n')) # Remove \n 
        
        #
        # Server
        self.fcm_service = FCMNotification(api_key=self._server_key)
        loggerd.log('FCM service initiated.', 'fcm')
        print('\tFCM service initiated.')


    # Parameter: String, String, Action(String, mostly URL)
    # Returns: -
    # Author: acoustikue(SukJoon Oh)
    def notifyMultipleDevice(self, m_title, m_body, action='', kwargs=None):

        print('\tSent push to: ' + self._device_token[0][0:15])
        print('\t... and more.')

        #for token in self._device_token:
        #    print('\t' + token[0:19] + '...')
        
        # send push!
        self.fcm_service.notify_multiple_devices(registration_ids=self._device_token, \
                                                 message_title=m_title, message_body=m_body, click_action=action \
                                                     , extra_notification_kwargs=kwargs)

    pass
Beispiel #10
0
def send_fcm_notification(title="", body="", data=None, users=None):
    """
    sends fcm notification to a single or multiple user device
    :param title: title of the notification message
    :param body: body of the notification
    :param data: any data to be sent
    :param users: list of user ids
    :return: True/False
    """
    if users:
        push_service = FCMNotification(api_key=settings.FCM_API_KEY)
        try:
            if data:
                if isinstance(users, list):
                    registration_ids = [
                        devices.registration_id
                        for devices in UserDevice.objects.filter(
                            used_id__in=users)
                    ]
                    push_service.multiple_devices_data_message(
                        registration_ids=registration_ids, data_message=data)
                else:
                    registration_id = UserDevice.objects.get(
                        user_id=users).registration_id
                    push_service.single_device_data_message(
                        registration_id=registration_id, data_message=data)
            else:
                if isinstance(users, list):
                    registration_ids = [
                        devices.registration_id
                        for devices in UserDevice.objects.filter(
                            user_id__in=users)
                    ]
                    push_service.notify_multiple_devices(
                        registration_ids=registration_ids,
                        message_title=title,
                        message_body=body)
                else:
                    registration_id = UserDevice.objects.get(
                        user_id=users).registration_id
                    push_service.notify_single_device(
                        registration_id=registration_id,
                        message_title=title,
                        message_body=body)
            return True
        except:
            return False
    else:
        return False
Beispiel #11
0
 def notify(self):
     push = FCMNotification(api_key="")
     self.db.query("select * from tokens")
     results = self.db.store_result()
     results = results.fetch_row(maxrows=0)
     l = []
     for x in results:
         l.append(x[0])
     title = 'Crime Alert!'
     body = 'Crime!'
     msg = {'location': 'Bookstore', 'case_id': '170214-0692'}
     push.notify_multiple_devices(registration_ids=l,
                                  message_title=title,
                                  message_body=body,
                                  data_message=msg)
Beispiel #12
0
def send_sale_alarm(station, sale_type, sale_name, sale_price, sale_link):
    user_dic = {}
    user_dic = get_user_toke(station, sale_type)

    for key, value in user_dic.items():
        print(key, value)

    for key, value in user_dic.items():
        if value == 1:
            push_service = FCMNotification(
                api_key=
                "AAAADgTMcII:APA91bFMVVBZB7bOM8BqocEGTJToANS9sB4Da0ODqG4RTfndoUapWBye8ASi9d3-rHUCkq4BvabFLgSqBfdyqrxtWCqZj3lYSYXpsFB-Szvo4gEgh9cExF24Puvr3I9rQ7r-H-pWMMQ0"
            )
            push_tokens = [str(key)]
            print(str(key))
            han_station = find_station_location(station)
            han_type = translate_type(sale_type)
            message_title = str(han_station) + " " + str(han_type) + " 매물 등록"
            message_body = "매물명: " + str(sale_name) + "/ 가격: " + str(
                sale_price)
            result = push_service.notify_multiple_devices(
                registration_ids=push_tokens,
                message_title=message_title,
                message_body=message_body)

            print(result)
Beispiel #13
0
    def handle(self, *args, **options):
        push_service = FCMNotification(api_key=settings.PDK_FIREBASE_API_KEY)

        event_definition = DataGeneratorDefinition.definition_for_identifier(
            'pdk-app-event')

        tokens = {}

        for point in DataPoint.objects.filter(
                generator_definition=event_definition,
                secondary_identifier='pdk-firebase-token').order_by('created'):
            properties = point.fetch_properties()

            tokens[point.source] = properties['event_details']['token']

        token_list = []

        for source, token in tokens.iteritems():  # pylint: disable=unused-variable
            if (token in token_list) is False:
                token_list.append(token)

        message = {'operation': 'nudge', 'source': 'passive-data-kit'}

        result = push_service.notify_multiple_devices(
            registration_ids=token_list, data_message=message)

        if settings.DEBUG:
            print 'Firebase nudge result: ' + str(result)
            print '(Update settings.DEBUG to suppress...)'
 def post(self,request):
     if not request.data._mutable:
         request.data._mutable = True
         request.data['user']=User.objects.filter(id=request.user.id)[0].id
         request.data['team']=TeamInfo.objects.filter(team_number=request.data['team'])[0].id
         request.data._mutable = False
         serializer = MessagingSerializer(data=request.data)
         print(request.data)
         push_service = FCMNotification(api_key="AIzaSyD8v3e4a3v-rcasU3Mh0KKkPaflm1dW1J4")
         if serializer.is_valid():
             print(serializer.validated_data)
             serializer.save(user=request.user)
             if not serializer.data['message_conf']:
                 devices = Notifications.objects.all()#.exclude(user=request.user) UNCOMMMENT THIS IN FUTURE
                 registration_ids=[]
                 for i in devices:
                     registration_ids.append(i.device_id)
                 result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=serializer.data['message_heading'], message_body=serializer.data['message_body'])
                 print(result)
             return Response(serializer.data, status=201)
         return Response(serializer.errors, status=400)
     else:
         request.data['user']=request.user
         serializer = MessagingSerializer(data=request.data)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data, status=201)
         return Response(serializer.errors, status=400)
Beispiel #15
0
 def data_push(self, device, registration_id, data_message):
     push_service = FCMNotification(api_key=config('SERVER_KEY'))
     if device == "single":
         result = push_service.notify_single_device(registration_id=registration_id, data_message=data_message)
     else:
         result = push_service.notify_multiple_devices(registration_ids=registration_id, data_message=data_message)
     print(result)
Beispiel #16
0
def notify():
    # Send to single device.
    from pyfcm import FCMNotification

    push_service = FCMNotification(api_key="<api-key>")

    # Your api-key can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging

    registration_id = "<device registration_id>"
    message_title = "Uber update"
    message_body = "Hi john, your customized news for today is ready"
    result = push_service.notify_single_device(registration_id=registration_id,
                                               message_title=message_title,
                                               message_body=message_body)

    # Send to multiple devices by passing a list of ids.
    registration_ids = ["<device registration_id 1>",
                        "<device registration_id 2>", ...]
    message_title = "Uber update"
    message_body = "Hope you're having fun this weekend, don't forget to check today's news"
    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids, message_title=message_title,
        message_body=message_body)

    print(result)
Beispiel #17
0
def sendNotification(username, post):
    flist = Follows.query.filter_by(follows=username)
    nameret = user_details.query.filter_by(username=username).first()
    name = nameret.fullname
    registration_ids = []
    usernames = []
    for i in flist:
        dataret = user_token.query.filter_by(username=i.username).first()
        registration_ids.append(dataret.token)
        usernames.append(dataret.username)
    push_service = FCMNotification(
        api_key=
        "AAAAFXEDMyw:APA91bHARuwO7X7Y5I_lLwkbEiQ3bCzt3TVS6awj6iqFolpd_YXMKKhevsoMsdx-cCWPkaXMR7iFuJB0X3TrVXqUcOgqSIfTO898PgWEsWZQrdZbDt8RILtgicYOS836jypqnMdAbsG4J170Fvj0tOdtB_USzhqj-g"
    )
    message_title = "New Post from " + name
    message_body = post.desc
    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids,
        message_title=message_title,
        message_body=message_body)
    print message_title
    print message_body
    print str(registration_ids)
    print str(usernames)
    print str(result)
Beispiel #18
0
    def send_push_notification(self, user_tokens, subject: Subject):

        fcm_api_key = os.getenv("FCM_API_KEY")
        # print(fcm_api_key)

        push_service = FCMNotification(api_key=fcm_api_key)

        # OR initialize with proxies

        push_service = FCMNotification(api_key=fcm_api_key)

        # Your api-key can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging

        # registration_id = "cA53EyujqEHAr2VzhWi47M:APA91bGtXuVeilvlK7z3UrBTmRnBx7TRQphAm3_cjun6admjs_Apl2K34dNNC3Cgky35gxiCZ0akl9P3TFbzSUbPTTJK1aZhCwphjvh3194ksref_JKYdNNClrYq6EyCF3mz2f2kM1ja"
        # message_title = "rental alert"
        # message_body = "Hi john, your customized news for today is ready"
        # print("send notification")
        # result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)

        # Send to multiple devices by passing a list of ids.
        registration_ids = user_tokens

        temp = base64.b64decode(subject.name)
        name = temp.decode("UTF-8")

        message_title = f"{name}"
        message_body = f"{subject.location}/{subject.region}/{subject.location}/{subject.price}"
        data_message = {'subject_id': f'{subject.subject_id}'}

        result = push_service.notify_multiple_devices(
            registration_ids=registration_ids,
            message_title=message_title,
            message_body=message_body,
            data_message=data_message)
        print(f"push result: {result}")
Beispiel #19
0
class FirebasePopupNotifications(IObserver):
    def __init__(self, firebase_server_key: str):
        self.service = FCMNotification(api_key=firebase_server_key)

    def update(self, update_info: UpdateInfo):
        session = DBInstance.get_instance().new_session()
        channel = GameBasedChannelsManager.get_game_based_channel(
            session, update_info.steam_id)
        subs = UserManager.get_subscribes(channel)
        session.close()
        self.__notify_users(channel, subs, update_info)

    def __notify_users(self, channel: GameBasedChannel, users: Generator[User],
                       update_info: UpdateInfo):
        ids: List[str] = []
        for user in users:
            ids += user.firebase_tokens

        response = self.service.notify_multiple_devices(
            registration_ids=ids,
            message_title=f"NEW UPDATE IN {channel.name}",
            message_body=update_info.short_description)
        for message in response:
            if 'error' in message:
                logger.error(f"FCM ERROR {message}")
class Message():
    def __init__(self, group_to_notify, message_title, message_body):
        self.push_service = FCMNotification(
            api_key=
            "AAAAYIooHik:APA91bF6utyDUSgqYX0MgZKhRM3-76kWvBYNXK6NY3HNKtM45shnt8JHbsx0x2XtpE2yXmEtH7MA6lR0M5e9BJuyJ5sDG1c8cjEwCpLZzZv93jyFUOQhofC1oOoMm6iWvfjRSuBU5_3r"
        )
        self.message_title = message_title
        self.message_body = message_body
        self.notify_ids = self.fetch_group_members(group_to_notify)

    def fetch_group_members(self, group_id):
        members_ref = db.reference("/groups/" + group_id + "/members")
        users_ref = db.reference("/users")
        notify_ids = [
            users_ref.child(x).child("notify_id").get()
            for x in members_ref.get().keys()
        ]
        print(notify_ids)
        return notify_ids

    def send(self):
        return self.push_service.notify_multiple_devices(
            registration_ids=self.notify_ids,
            message_title=self.message_title,
            message_body=self.message_body)
Beispiel #21
0
class PushMessage:
    def __init__(self, token_list, title, body=None, badge=None):
        self.token_list = token_list
        self.title = title
        self.body = body
        self.badge = badge

        registry = getUtility(IRegistry)
        self.push_service = FCMNotification(
            api_key=registry['infoporto.push_api_key'])
        self.push_locations = registry['infoporto.push_location'] or '/push/'

    def send(self):
        logger.info("Sending push to %s" % self.token_list)
        result = self.push_service.notify_multiple_devices(
            registration_ids=self.token_list,
            message_title=self.title,
            message_body=self.body)
        logger.debug(result)

    def queue(self):
        print self.push_locations
        container = api.content.get(path=self.push_locations)

        for token in self.token_list:
            obj = api.content.create(type='PushMessage',
                                     title=self.title,
                                     message=self.body,
                                     recipient=token,
                                     state='OUTGOING',
                                     container=container)

            logger.info("Push %s for %s added to queue" % (obj.id, token))
Beispiel #22
0
def sendgroupnotification():
    push_service = FCMNotification(
        api_key=
        "AAAAYv7rBNM:APA91bEwGTAwNGMqqFnh_3YSrcbCFvcwXvxlJhdEumZQQ6RU7_PnBlbBZILJwWKEyXLOaKCgLUDXwMiPk8lx1ONWyzrcR1KI5fxLysyAgrgWsLPhPrFjsLYsEiV-rsD39OcMcwd_omvU_zIFI-ynM0j0_RKj0OgRqQ"
    )

    masterids = request.form.getlist('masterid')
    manager = dbhelper.DBManager()
    tokens = []
    for masterid in masterids:
        tokens.append(str(manager.getToken(masterid)))

    message_title = request.form.get("title")
    message_body = request.form.get("message")

    newNotif = dbhelper.Notification()
    newNotif.title = message_title
    newNotif.message = message_body
    newNotif.sendTimestamp = datetime.datetime.now()
    manager.addGroupNotification(masterids, newNotif)

    result = push_service.notify_multiple_devices(registration_ids=tokens,
                                                  message_title=message_title,
                                                  message_body=message_body)
    print(result)
    return "Notifcation sent successfully"
Beispiel #23
0
def push_procedure_to_devices(owner, procedure_id):
    # api_key from https://console.firebase.google.com/project/sanamobile-1f7b1/settings/general/
    push_service = FCMNotification(api_key="FILL API KEY HERE")

    secret_key = os.urandom(32).encode('hex')
    PushEvent.objects.create(procedure_id=procedure_id, secret_key=secret_key)

    # create a data message
    data_message = {
        "type":
        "newProcedure",
        "procedureId":
        procedure_id,
        "secretKey":
        secret_key,
        "fetchUrl":
        "/api/procedures/{}/fetch?secret={}".format(procedure_id, secret_key),
    }

    registration_ids = Device.objects.all().values_list('registration_id',
                                                        flat=True)
    registration_ids = [i.encode('ascii', 'ignore') for i in registration_ids]

    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids, data_message=data_message)
Beispiel #24
0
def fcm_send_bulk_message(registration_ids,
                          title=None,
                          body=None,
                          icon=None,
                          data=None,
                          sound=None,
                          badge=None,
                          low_priority=None,
                          condition=None,
                          time_to_live=None,
                          click_action=None,
                          collapse_key=None,
                          **kwargs):
    api_key = SETTINGS.get("FCM_SERVER_KEY")
    push_service = FCMNotification(api_key=api_key)

    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids,
        message_title=title,
        message_body=body,
        message_icon=icon,
        data_message=data,
        sound=sound,
        badge=badge,
        collapse_key=collapse_key,
        low_priority=low_priority,
        condition=condition,
        time_to_live=time_to_live,
        click_action=click_action,
        **kwargs)

    # do not raise errors, pyfcm will raise exceptions if response status will
    # be anything but 200

    return result
Beispiel #25
0
def send_notification_to_all():
    api_key = ''
    if api_key != '':
        print('inside push notification')
        ids = User.objects.filter(
            is_active=True, is_superuser=False).values_list('device_token',
                                                            flat=True)
        ids = list(ids)

        push_service = FCMNotification(api_key=api_key)
        registration_ids = ids
        message_title = "KishMalik Notification"
        message_body = 'Please check a new article added in the list'
        result = push_service.notify_multiple_devices(
            registration_ids=registration_ids,
            message_title=message_title,
            message_body=message_body)

        users = User.objects.filter(is_active=True, is_superuser=False)
        for u in users:
            un = UserNotification(
                user=u,
                notification=notification_msg,
                req_type='6',
            )
            un.save()
        return True
    return False
Beispiel #26
0
def buy():
    f = open("eur.txt", "r")
    eur = float(f.read()) - 0.5
    f.close()

    print(str(eur) + "€ vorhanden!")

    f = open("eur.txt", "w")
    f.write("0")
    f.close()

    eth = eur / ethPrice
    print(str(eth) + " ETH gekauft!")

    push_service = FCMNotification(
        api_key=
        "AAAAOL_f7Vw:APA91bHx4r3FM3rH2RxU2JtjoMRMm8At-c9XGrUnxpp6BCHtQLup1uvjAzIifOBAMMqCDOi_Z0O6wgqYGMtVJdt4EUdVzBXiUmpP_kTJRWB_9TmJBTp2II3tELBvSBhQvxMZxxLYP_Xu"
    )
    registration_ids = [
        "dSvcsDop4ek:APA91bFcfxJak8NLbyxjpXavu3RLbf28jNLRRcAcTTN7_dzg-MS8rzN3uRsPvMgpmPNvpJCaRIFMOliUDX169uf3cH2V7isYYMa0F6Hn5VZRunVhz_ZJBUot5m9V2HotGtbBxtAULUvM"
    ]
    message_title = "ETH gekauft"
    message_body = str(eth) + " ETH vorhanden"
    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids,
        message_title=message_title,
        message_body=message_body)

    f = open("eth.txt", "w")
    f.write(str(eth))
    f.close()
Beispiel #27
0
def send_push_notification(
):  # send a fcm push notification to all android devices
    from pyfcm import FCMNotification

    API_KEY = 'fcm api key here'
    push_service = FCMNotification(api_key=API_KEY)

    # parse list of fcmRegKeys
    with touchopen('/var/www/devices.json', 'r') as f:
        fcntl.lockf(f, fcntl.LOCK_EX)

        obj = json.load(f)

        registration_ids = []
        for i in obj["devices"]:
            registration_ids.append(i["fcmRegKey"])

    # Send to multiple devices by passing a list of ids.
    app.logger.info("regId size:%d", len(registration_ids))

    message_title = "MySmartHome"
    message_body = "Check your home"
    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids,
        message_title=message_title,
        message_body=message_body)

    print result
Beispiel #28
0
def sendNotification(string):

    push_service = FCMNotification(api_key="enter-key-here")

    # OR initialize with proxies

    #proxy_dict = {
    #          "http"  : "http://127.0.0.1",
    #          "https" : "http://127.0.0.1",
    #        }
    #push_service = FCMNotification(api_key="<api-key>", proxy_dict=proxy_dict)

    # Your api-key can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging

    registration_ids = ["enter-ids-here-separated-with-commas"]
    message_title = "Nowe zdjecie"
    message_body = string
    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids,
        message_title=message_title,
        message_body=message_body)

    # Send to multiple devices by passing a list of ids.
    #	registration_ids = ["<device registration_id 1>", "<device registration_id 2>", ...]
    #	message_title = "Uber update"
    #	message_body = "Hope you're having fun this weekend, don't forget to check today's news"
    #	result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)

    print result
Beispiel #29
0
    def send_silent_notification(self, token_list, json_data, dev=False):
        if len(token_list) == 0:
            logging.info(
                "len(token_list) == 0, early return to save api calls")
            return

        ios_raw_data = copy.copy(json_data)
        # multiplying by 10^6 gives us the maximum resolution possible while still
        # being not a float. Have to see if that is too big.
        # Hopefully we will never send a push notification a millisecond to a single phone
        ios_raw_data.update({"notId": int(time.time() * 10**6)})
        ios_raw_data.update({"payload": ios_raw_data["notId"]})

        push_service = FCMNotification(api_key=server_auth_token)

        FirebasePush.print_dev_flag_warning()
        # convert tokens if necessary
        fcm_token_list = self.convert_to_fcm_if_necessary(token_list)

        response = push_service.notify_multiple_devices(
            registration_ids=fcm_token_list,
            data_message=ios_raw_data,
            content_available=True)
        logging.debug(response)
        return response
Beispiel #30
0
    def send_visible_notification(self,
                                  token_list,
                                  title,
                                  message,
                                  json_data,
                                  dev=False):
        if len(token_list) == 0:
            logging.info(
                "len(token_list) == 0, early return to save api calls")
            return

        FirebasePush.print_dev_flag_warning()

        # convert tokens if necessary
        fcm_token_list = self.convert_to_fcm_if_necessary(token_list)

        push_service = FCMNotification(api_key=server_auth_token)
        data_message = {"data": json_data, "payload": json_data}
        response = push_service.notify_multiple_devices(
            registration_ids=fcm_token_list,
            message_body=message,
            message_title=title,
            data_message=data_message)
        logging.debug(response)
        return response
Beispiel #31
0
def getNotifications():

	push_service = FCMNotification(api_key="AIzaSyB1byDiSollNF32f7auagCdzRXWqcs8aAs")
	
	if(len(pdservice.getNotificationData())==0):
		return "No notifications available"
	else:
		j = pdservice.getNotificationData()
		message_title ="Shopping notification"
		message_body="You should buy these products by tomorrow : " + "\n"
		products_name=""
		device_registration_ids=[]
		message=""
		
		#print len(j)
		
	 	for registration_id,value in j.items():
	 		device_registration_ids.append(registration_id)
	 		for i in range(0,len(value)):
	 			products_name = products_name + str(value[i]).title() + "\n"
	 		message = message_body + products_name  + "\n" 
	 		result = push_service.notify_multiple_devices(registration_ids=device_registration_ids, message_title=message_title, message_body=message)
	 		print result
	 		products_name=""
	 		message=""
	 		device_registration_ids=[]
	 	return "sucess"
Beispiel #32
0
def push_urls(crawler_id, crawler_name, changed_line, url_link ):
    #make push message for ios
    title_ios = str("구독중인 "+ crawler_name + " 이/가 변경되었습니다!")
    message_ios = str(changed_line)

    #make push message for android
    message_data_android = {'title': str(crawler_name + " Changed!"),
                    'body': str(changed_line),
                    'clickurl': str(url_link)
                    }

    #shoot the crawler id to API server and receive the subscribe user as json type
    payload = {'crawler_id': crawler_id}
    received_json = requests.post(api_request_url, data=payload)

    #parse the json user data
    token_receive_data = received_json.json()
    for k in token_receive_data['data']:
        tokens.append(k['push_token'])


    for i in api_list:
        push_service = FCMNotification(api_key=i)
        result = None

        try:
            if i == api_list[0]:    #which means push to android
                result = push_service.notify_multiple_devices(registration_ids=tokens, data_message=message_data_android)
            elif i == api_list[1]:  #which means push to ios
                result = push_service.notify_multiple_devices(message_title=title_ios, message_body=message_ios,registration_ids=tokens, data_message={})

        except Exception as e:
            print(e)
            print(str(result))

    tokens.clear()
    return;
Beispiel #33
0
    def send_silent_notification(self, token_map, json_data, dev=False):
        if len(token_map) == 0:
            logging.info("len(token_map) == 0, early return to save api calls")
            return

        ios_raw_data = copy.copy(json_data)
        # multiplying by 10^6 gives us the maximum resolution possible while still
        # being not a float. Have to see if that is too big.
        # Hopefully we will never send a push notification a millisecond to a single phone
        ios_raw_data.update({"notId": int(time.time() * 10**6)})
        ios_raw_data.update({"payload": ios_raw_data["notId"]})

        push_service = FCMNotification(api_key=self.server_auth_token)

        # convert tokens if necessary
        fcm_token_map = self.convert_to_fcm_if_necessary(token_map, dev)

        response = push_service.notify_multiple_devices(registration_ids=fcm_token_list,
                                                   data_message=ios_raw_data,
                                                   content_available=True)
        logging.debug(response)
        return response
#!/usr/bin/python

# pip install pyfcm
# ref: https://github.com/olucurious/PyFCM
from pyfcm import FCMNotification
from os import environ
from pprint import PrettyPrinter

# requirement:
# export FCM_API_KEY and FCM_TOKENS in .profile

api_key = environ["FCM_API_KEY"]
device_tokens = environ['FCM_TOKENS'].split(";")

print "using api_key=", api_key, "device_tokens=", device_tokens

fcm = FCMNotification(api_key = api_key)
pretty_printer = PrettyPrinter(indent=2)

message_title = "FCM Message Title"
message_body = "FCM Test Message"
data_message = {
	"message": "FCM Test Message",
	"link": "https://jackcsk.me"
}
result = fcm.notify_multiple_devices(registration_ids = device_tokens, message_title = message_title, message_body = message_body, data_message = data_message)
#result = fcm.multiple_devices_data_message(registration_ids = device_tokens, data_message = data_message)

print "FCM Response:"
pretty_printer.pprint(result)
Beispiel #35
0
    if notification_count < 2:

        # Send to single device.

        push_service = FCMNotification(api_key="AIzaSyBl6il28Gs0OeQGdzF4FsjRuaZoT6C8r38")

        regs = database.notification.find()
        id = database.judgement.find()
        registration_ids = []

        for reg in regs:
            registration_ids.append(reg['device_id'])
        message_title = header
        message_body = case_number
        result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=json.loads(string))
        print(string)
        print(result)
        notification_count = notification_count + 1
    else:
        exit()

"""
    # Send to multiple device.


    last_case = database.judgement.find().sort('_id',pymongo.DESCENDING).limit(1)
    for a in last_case:
        ida = a['_id']
        category = a['category']
    string = '{"id":"' + str(ida) + '","category":"' + str(category) + '"}'
Beispiel #36
0
def fcm_send_bulk_message(
        registration_ids,
        title=None,
        body=None,
        icon=None,
        data=None,
        sound=None,
        badge=None,
        low_priority=False,
        condition=None,
        time_to_live=None,
        click_action=None,
        collapse_key=None,
        delay_while_idle=False,
        restricted_package_name=None,
        dry_run=False,
        color=None,
        tag=None,
        body_loc_key=None,
        body_loc_args=None,
        title_loc_key=None,
        title_loc_args=None,
        content_available=None,
        extra_kwargs={},
        api_key=None,
        json_encoder=None,
        **kwargs):
    """
    Copied from https://github.com/olucurious/PyFCM/blob/master/pyfcm/fcm.py:

    Send push notification to a single device
    Args:
        registration_ids (list): FCM device registration IDs.
        body (str): Message string to display in the notification tray
        data (dict): Data message payload to send alone or with the notification
            message
        sound (str): The sound file name to play. Specify "Default" for device
            default sound.
    Keyword Args:
        collapse_key (str, optional): Identifier for a group of messages
            that can be collapsed so that only the last message gets sent
            when delivery can be resumed. Defaults to ``None``.
        delay_while_idle (bool, optional): If ``True`` indicates that the
            message should not be sent until the device becomes active.
        time_to_live (int, optional): How long (in seconds) the message
            should be kept in FCM storage if the device is offline. The
            maximum time to live supported is 4 weeks. Defaults to ``None``
            which uses the FCM default of 4 weeks.
        low_priority (boolean, optional): Whether to send notification with
            the low priority flag. Defaults to ``False``.
        restricted_package_name (str, optional): Package name of the
            application where the registration IDs must match in order to
            receive the message. Defaults to ``None``.
        dry_run (bool, optional): If ``True`` no message will be sent but
            request will be tested.

    Returns:
        :tuple:`multicast_id(long), success(int), failure(int),
            canonical_ids(int), results(list)`:
        Response from FCM server.
    Raises:
        AuthenticationError: If :attr:`api_key` is not set or provided or there
            is an error authenticating the sender.
        FCMServerError: Internal server error or timeout error on Firebase cloud
            messaging server
        InvalidDataError: Invalid data provided
        InternalPackageError: JSON parsing error, mostly from changes in the
            response of FCM, create a new github issue to resolve it.
    """

    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_multiple_devices(
        registration_ids=registration_ids,
        message_title=title,
        message_body=body,
        message_icon=icon,
        data_message=data,
        sound=sound,
        badge=badge,
        collapse_key=collapse_key,
        low_priority=low_priority,
        condition=condition,
        time_to_live=time_to_live,
        click_action=click_action,
        delay_while_idle=delay_while_idle,
        restricted_package_name=restricted_package_name,
        dry_run=dry_run,
        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,
        extra_kwargs=extra_kwargs,
        **kwargs
    )

    # do not raise errors, pyfcm will raise exceptions if response status will
    # be anything but 200

    return result