def enviar_notificacao(sender, instance, **kwargs): # Instância da classe FCMNotification com parâmetro da API push_service = FCMNotification(api_key="AIzaSyDXv8_47S0_g64d5sHvwZWpH98gyJDUhtc") # Método que passa os parâmetros de configuração do alerta do push # Recebe o que vem da categoria e passa para a função de envio, obs: Tiramos o uso do IF push_service.notify_topic_subscribers(topic_name='%s' % instance.categoria.desc, sound=True, color=None, message_body=instance.titulo, #condition=topic_condition )
def fcm_send_data(user_id, data=None): """Funcion para enviar mensaje a traves de topicos en Firebase.""" # Notificaciones push para dispositivos moviles # manejamos 2 funciones para cada plataforma en especifico. api_key = FcmConfig.FCM_SETTINGS.get("FCM_SERVER_KEY") # topico para android topic = "user-" + str(user_id) # topico para IOS topic_ios = "ios-user-" + str(user_id) title_ios = data["title"] body_ios = data["body"] # configuracion de apikey push = FCMNotification(api_key=api_key) # funcion para enviar a android, con data_message result = push.notify_topic_subscribers(topic_name=topic, data_message=data) # funcion para enviar a IOS, con notification message result_ios = push.notify_topic_subscribers(topic_name=topic_ios, message_title=title_ios, message_body=body_ios, data_message=data, badge=data["badge"]) # do not raise errors, pyfcm will raise exceptions if response # status will # be anything but 200 # import pdb; pdb.set_trace() # print(user_id) # print(data) # print(body_ios) # print(result) # print(result_ios) return result
def post(app_name): push_service = FCMNotification(api_key=PUSHCONF['API_KEY']) parser = reqparse.RequestParser() parser.add_argument('topic', type=str, location='json', required=True, help='queue topic cannot be blank') parser.add_argument('message', type=str, location='json', required=True, help='message cannot be blank') parser.add_argument('access_token', type=str, location='json', required=True) args = parser.parse_args(strict=True) push_service.notify_topic_subscribers(topic_name='event_' + args['topic'], message_body=args['message']) return {'ack': 'true'}, 200
def push_notif(id, message_title, message_body): api_keys = 'AAAAaxCakgY:APA91bG4JlqQn6YhGAoPck1_moeHW4PxUWiPxnjEmxqfbVLTCVk7Wfn6fOq7AR7b_zPBF0oR9ln-d1maLH5ZoqbFea0eEl0O10RHUYyljyztqkwJEq46kZwVgKgt377PwVH00pjR87i4' push_service = FCMNotification(api_key=api_keys) push_service.notify_topic_subscribers(topic_name=str(id), message_title=message_title, message_body=message_body)
def notify(title, message): key = "KEY" push_service = FCMNotification(api_key=key) if len(message) > 51: message = message[:50] + '...' push_service.notify_topic_subscribers(topic_name="news", message_body=message, message_title=title)
def send_notification_noticias(sender, instance, created, **kwargs): push_service = FCMNotification(api_key=api_key) if created: message = str(instance.title) title = "Nueva noticia" else: message = str(instance.title) title = "Actualización de noticia" data_message = { "type": "noticia", "noticia": str(instance.pk) } push_service.notify_topic_subscribers(message_title=title,topic_name="news",data_message=data_message, message_body=message,time_to_live=0)
def send_notification_premio(sender, instance, created, **kwargs): push_service = FCMNotification(api_key=api_key) premio = instance.name if created: message = str(premio) title = "Resultados" else: message = str(premio) title = "Actualización de Resultados" data_message = { "type": "premio", "premio": str(instance.pk) } push_service.notify_topic_subscribers(message_title=title,topic_name="results", message_body=message,data_message=data_message,time_to_live=0)
def send_push(request): if request.method == 'POST': received_data = request.body received_push_dict = ast.literal_eval(received_data) push_topic = received_push_dict['topic'] push_msg = received_push_dict['message'] push_num = received_push_dict['number'] try: push_service = FCMNotification(api_key='AAAAtoaWwyQ:APA91bFTmtGT2-ku-nnwUgiNgD51IhphQEdemKsAnmfcwVgzwU3OAyxy6UJ8IX7OCZcxWCShPM03_F-IYdfDy6rHs1vbjT04kbngXf7KvGMKUE-cdAFNv4PLEjw2NZMiDE1UU9rxmwcU') message_title = "KUB Story" message_body = push_msg result = push_service.notify_topic_subscribers(topic_name=str(push_topic), message_body=message_body, message_title=message_title) sent_push = Push(push_author=push_topic, push_title=push_msg, push_number=push_num) sent_push.save() return HttpResponse(json.dumps({'response':'success'})) except Exception as e: print(str(e)) return HttpResponse(json.dumps({'response':'fail'})) else: return HttpResponse('Request is not in POST form')
class FCM: """ Firebase Cloud Messaging Client Module. Leverages pyfcm library for API requests """ def __init__(self): self.push_service = None def init_push_service(self, api_key): self.push_service = FCMNotification(api_key=api_key) def send_notification(self, topic, message, data, click_action): self.push_service.notify_topic_subscribers(topic_name=topic, message_body=message, data_message=data, click_action=click_action)
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
class MonitorMessageSender: def __init__(self): ''' Constructor ''' self.__push_service = FCMNotification(api_key=API_KEY) def send_account_balance(self, btc, usd, currencies=[], market="Bittrex"): coins = [] for coin in currencies: if not isinstance(coin, Currency): raise Exception( 'illegal variable currencies, use array of Currency') coins.append(coin.to_json()) message_data = { 'btc': btc, 'usd': usd, "update_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'currencies': coins, "market": market } print(message_data) result = self.__push_service.notify_topic_subscribers( topic_name=TOPIC_NEWS, message_title=TITLE_ACCOUNT_BALANCE, tag=TYPE_ACCOUNT_BALANCE, data_message=message_data) print(result)
def send_device_android_notification_worker(user_uuid, device_uuid, user_sensor_name, device_name, user_sensor_uuid, status, time_reached): # header = { # "Content-Type": "application/x-www-form-urlencoded" # } # # payload = { # 'user_uuid' : 'user_uuid' # 'device_uuid': device_uuid, # 'device_name': device_name, # 'user_sensor_uuid': user_sensor_name, # 'user_sensor_name' : user_sensor_uuid, # 'status': status, # 'timestamp': timestamp # } # response = requests.post(url=SEND_ANDROID_NOTIFICATION_ENDPOINT,data=payload, headers=header) push_service = FCMNotification(api_key=FCM_API_KEY) payload = { "data": { "user_uuid": user_uuid, "device_uuid": device_uuid, "device_name": device_name, "user_sensor_uuid": user_sensor_uuid, "user_sensor_name": user_sensor_name, "status": status, "timestamp": float(datetime.now().timestamp()) } } result = push_service.notify_topic_subscribers(topic_name=user_uuid, data_message=payload)
class FCMSender: def __init__(self, server_key): self.push_service = FCMNotification(api_key=server_key) def send(self, title, message, registration_id=None): message_title = title message_body = message if registration_id is None: result = self.push_service.notify_topic_subscribers(topic_name='all', message_title=message_title, message_body=message_body) else: result = self.push_service.notify_single_device(registration_id=registration_id, message_body=message_body, message_title=message_title) print(result) return result @staticmethod def get_clients_to_push(): rows = database.Database().execute(query_formats.get_registration_id_format) clients_to_push = list() for row in rows: clients_to_push.append(row['registration_key']) return clients_to_push
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_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 ) return result
def send_topic(self, jsondata, topic): try: push_service = FCMNotification(api_key=FCM.FCM_API_KEY) result = push_service.notify_topic_subscribers( data_message=jsondata, topic_name=topic) print(result) except Exception as e: print("fcm_topic error: {}".format(e))
class Firebase: def __init__(self, app): self.app = app api_key = self._get_api_key() if api_key is not None: self.push_service = FCMNotification(api_key=api_key) self.last_send_time = None self.notifications = True def toggle_notifications_based_on_distance(self, lon, lat): distance_meters = calculate_distance(lon, lat, *self._get_pi_location()) if distance_meters is None: return -1 self.notifications = (distance_meters > MIN_DISTANCE_FOR_NOTIFICATIONS) print("Notifications turned {}!".format( "on" if self.notifications else "off")) return distance_meters def send_movement_push_notification(self): delta = time.time() - (self.last_send_time or 0) if delta > PUSH_NOTIFICATION_INTERVAL: self.last_send_time = time.time() self._send_push_notification( "movement", "Detected movement in front of your house!", "Movement detected!") def _send_push_notification(self, topic, message, title): if self.push_service is not None: self.push_service.notify_topic_subscribers(topic, message_body=message, message_title=title) else: print("Skipped sending push notification, API key not provided!") def _get_api_key(self): return self.app.config["FIREBASE_API_KEY"] def _get_pi_location(self): lon = self.app.config["PI_LONGITUDE"] lat = self.app.config["PI_LATITUDE"] return lon, lat
def send_message(): msg = request.form['msg'] #data_message = {"body":msg} push_service = FCMNotification( api_key= "AAAAPyvvG34:APA91bEZ0x963WnD7YJvsIIrEst-GndqnYP02nE2Utca5gK3a_XjpCVLe4dmHh_pwHjPbYhxK-kqZvzZhOMTvvOAtxvO2ZPyHnHxBp2uVCeEZvNI4DgdFUpe1Nl-wS_KGWvueOuHL8NI" ) result = push_service.notify_topic_subscribers(topic_name="all", data_message={"body": msg}) return msg
class NestFCMManager: ADMIN_TOPIC = "admin" NONADMIN_TOPIC = "non-admin" def __init__(self): with open(os.path.join(os.environ["MYH_HOME"], "data", "fcm.json")) as fcm_file: fcm_dict = json.load(fcm_file) api_key = fcm_dict["api_key"] self.push_service = FCMNotification(api_key=api_key) def sendMessage(self, message_title, message_body, topic_name): self.push_service.notify_topic_subscribers(topic_name=topic_name, message_body=message_body, message_title=message_title) def sendMessageAdmin(self, message_title, message_body): self.sendMessage(message_title, message_body, self.ADMIN_TOPIC) def sendMessageNonAdmin(self, message_title, message_body): self.sendMessage(message_title, message_body, self.NONADMIN_TOPIC)
def sendAlert(message, type): from pyfcm import FCMNotification import os global lastHumidityTime global lastTemperatureTime push_service = FCMNotification(api_key=os.environ['FCM_KEY']) if type is "humidity" and lastHumidityTime + 300000 < int( round(time.time() * 1000)): print("Sending humidity Alert") lastHumidityTime = int(round(time.time() * 1000)) push_service.notify_topic_subscribers(topic_name="alerts", message_body=message) if type is "temperature" and lastTemperatureTime + 300000 < int( round(time.time() * 1000)): print("Sending temperature Alert") lastTemperatureTime = int(round(time.time() * 1000)) push_service.notify_topic_subscribers(topic_name="alerts", message_body=message)
def push_notification(request): if request.method == 'POST': topic = request.POST.get('topic') title = request.POST.get('title') message = request.POST.get('message') push_service = FCMNotification(api_key=settings.FCM_API_KEY) result = push_service.notify_topic_subscribers( topic_name=topic, message_title=title, message_body=message, ) return redirect(request.META.get('HTTP_REFERER'))
class FCMSender: def __init__(self, server_key): self.push_service = FCMNotification(api_key=server_key) def send(self, topic_id, topic_name): message_title = topic_name message_body = '새로운 메시지가 있습니다' result = self.push_service.notify_topic_subscribers( topic_name=topic_id, message_title=message_title, message_body=message_body) return result
def send_push_notification_fcm(message): """ Using Firebase Cloud Messaging (FCM) to send notification to android device """ push_service = FCMNotification(api_key="AAAAisuS5ss:APA91bH5m303tDXY2eQlVAYygRIqH2oRAiiVDxaVnipG-McWJjVX3xWXXIOMauUV0dUhdPnqvrbI5tmZd2zHV9ixULm71m9uWtNNQjnoEIe0bTYgVzYlg32gkds07EJv_6WOC3vnzz-k") message_title = "Warning" message_body = "Too hot!" data_message = { "title" : "LoRa System WARNING!!!", "body" : message, } # result = push_service.notify_topic_subscribers(topic_name="LORA_SYSTEM", message_body=message_body, message_title=message_title) result = push_service.notify_topic_subscribers(topic_name="LORA_SYSTEM", data_message=data_message) print(result)
def send(self, notifications, users): for notification in notifications: object_data = self.get_object(notification) push_service = FCMNotification(api_key=FIREBASE_API_KEY) response = push_service.notify_topic_subscribers( topic_name=self.get_topic(object_data), message_body=self.build_notification_body(notification), message_title=self.title, click_action='FLUTTER_NOTIFICATION_CLICK', data_message={ 'type': self.object_field, 'id': object_data.pk }) return True
def incidents(user_id): # SEARCH FOR USER, SEND NOTIFICATION AND SEND INFORMATION #AIzaSyBzu6jeeyGabLpGPj7KutBzR-BmXwsMcrc #Expected Input = {USER_ID, LOCATION{latitude, longitude}} id = request.view_args['user_id'] crud.createIncident(request.json, id) push_service = FCMNotification( api_key="AIzaSyBzu6jeeyGabLpGPj7KutBzR-BmXwsMcrc") result = push_service.notify_topic_subscribers(topic_name="covadonga", message_body='Alerta!') response = jsonify({'prueba': 'pruebita'}) response.headers.add('Access-Control-Allow-Origin', '*') return response
def sendPush(): data_message = { "title": "Deep Pi - Alert", "body": "System detected fire. Please check it out.", } push_service = FCMNotification( api_key= "AAAAZW9shM0:APA91bEBRY3WT8AzjM86hWVhUaOJP9O_zKhVX8PDlVD6MVHV_7ofMu6FBDgKBt7gHCJ2RjYIOoeYkoFRPWVtlYtAF5Uou7HUe6Ky6ZLJ_I2JK1zCVjqyz3Z120IuHuVVg6W48Ywuxc29" ) print("[FCM MANAGER] Will send push") result = push_service.notify_topic_subscribers(topic_name="fire", content_available=True, data_message=data_message)
def topic_message(topic, data=None, title=None, body=None, silent=True): push_service = FCMNotification(api_key=settings.FCM_SERVER_KEY) if not data: data = {} if not body and not title: silent = True if title and silent: data['title'] = title if body and silent: data['message'] = body result = push_service.notify_topic_subscribers(topic_name=topic, message_title=title, message_body=body, data_message=data) return result
def uploadNotification(video_id, video_title, course): key = "AAAAhHPOtR4:......" push_service = FCMNotification(api_key=key) data = { "type":"upload", "video_title":video_title, "video_url":video_id, "click_action":"FLUTTER_NOTIFICATION_CLICK", "route":"youtube" } # Changed message_icon to ['notification']['image'] field in library files for my use case result = push_service.notify_topic_subscribers(topic_name=course, message_title="A new video has been uploaded", message_body="Please tap on this notification to continue", data_message=data, message_icon=f"https://img.youtube.com/vi/{data['video_url']}/hqdefault.jpg") if result['success'] == 1: print("notification sent")
def sendNotification(temp): push_service = FCMNotification( api_key= "AAAAwcaNGIE:APA91bG8XH4WgdqS7akF0PYAuSPJ8G-9t-YmjaRNGxwKfRLPinSWf3ngFAseKVmn1Ge3kN9XogJOIGlA5EeRJneQb0_Q2-bXgIy3-UKp0OVG0dOOKcRD4CE3SXMvzHjpU5ajps3VRGtN" ) message_title = "Room Temperature" if temp > 23: message_body = "The Room Temperature is more then 23c" else: message_body = "The Room Temperature is less then 16c" result = push_service.notify_topic_subscribers( topic_name="RoomTemperature", message_title=message_title, message_body=message_body, sound=True) #print "sending Notification" #print volume return
def sendnotif(self): push_service = FCMNotification( api_key= 'AAAAMLtwGK0:APA91bEqXYrlOa3f4Cgn-pEInxWzrEsVQr4pCnCCOMsXuyjqU1zpJyzIzyl1R6vY41Yd3qW71CBKahpk259jCxZlHi7Vidj_UDxOHQCp3l3VNBS65vwKs5nK3YbyHutl52p53_rn4kLe' ) try: result = push_service.notify_topic_subscribers( topic_name='global', message_body=self.body, message_title=self.head, color=self.col) print("Sent to %d Locations Sucessfully, %d Failed.." % (result['success'], result['failure'])) except: print("Error while sending Notification!") # no=Notify("Test Function","Testing through a class!!","blue") # no.sendnotif()
def notify(api_key: str, message: str, topic: str, title: str, data: object = {}): """ Notifies a topic :param api_key: Api key to send to :param message: Message that should be notified (optional) :param topic: Topic that message should be sent to :param title: Title of the message :param data: Extra data to send (optional) """ push_service = FCMNotification(api_key=api_key) if message is not None: data['message'] = message if title is not None: data['title'] = title result = push_service.notify_topic_subscribers(topic_name=topic, data_message=data) print(result)
class FirebaseUtils: def __init__(self, bucket, conf): self.bucket = bucket self.conf = conf self.push_service = FCMNotification(api_key=conf["api_key"]) # Upload image on Firebase def upload(self, frame,ts, notification = True): # Save frame on disk cv2.imwrite("images/snapshot.jpg", frame) # Create blob blob = self.bucket.blob('{base_path}/{timestamp}.jpg'.format(base_path = self.conf['base_path'], timestamp=ts)) # Upload image on firebase blob.upload_from_filename("images/snapshot.jpg", content_type="image/jpg") # Trigger notification if required if(notification): # Create notification message_title = "Intrusion detected" message_body = "ATTENTION! INTRUSION!" # Send notification to topic result = self.push_service.notify_topic_subscribers(topic_name=self.conf["base_path"], message_body=message_body, message_title = message_title)
def pushNotification(): push_service = FCMNotification( api_key= "AAAAuQBCBPE:APA91bGKiYJ_hPLifHUJebsjMSjlLUvjkoLpYcTCPDTkgHy7hwlOR6rSa0w3CFrfG7qg8p-p9jerFNoQT5G5DKMMyBz8JvJ4rzK0xGv_VCdCyHKWnbY3B0PLCj4TQlP7t_7S9IwABEum" ) jsonData = request.json cliente = jsonData['cliente'] pedido = jsonData['pedido'] cantidad = jsonData['cantidad'] telefono = jsonData['telefono'] colonia = jsonData['colonia'] calle = jsonData['calle'] numero = jsonData['numero'] dataPayLoad = { "cliente": cliente, "pedido": pedido, "cantidad": cantidad, "telefono": telefono, "colonia": colonia, "calle": calle, "numero": numero, } message_title = "Pedido" message_body = "Nuevo pedido realizado" result = push_service.notify_topic_subscribers( topic_name="restaurant_topic", message_title=message_title, message_body=message_body, click_action='FLUTTER_NOTIFICATION_CLICK', data_message=dataPayLoad) return result
def send_notification_to_topic(): body = request.get_json() if not body: raise MissingJSONBodyException(status_code=400) if 'topic' not in body or 'title' not in body or 'body' not in body: raise JSONBodyFormatException(status_code=400) topic_name = body.get('topic') message_title = body.get('title') message_body = body.get('body') push_service = FCMNotification(api_key=api_key) result = push_service.notify_topic_subscribers(topic_name=topic_name, message_body=message_body, message_title=message_title) print(result) success = bool(result['success']) if success: status_code = 200 else: status_code = 500 return jsonify({ 'success': success, }), status_code
class DsoftHttpRequest(): """ Initial the Http Request to backend server Set the username and password of caster user Initial the Firebase Notification """ def __init__(self): self.username = api.API_USER self.password = api.API_PWD self.token = '' self.push_fcm = FCMNotification(api_key=api.FCM_KEY) """ Login to Backend Server with user info from api constant file. Save the token to memory variable """ def login(self): jsonData = {"username": self.username, "password": self.password} r = requests.post(api.LOGIN_API, json=jsonData) if r.status_code == 200: self.token = r.json()['data']['access_token'] print('Login successful with access-token: {}'.format(self.token)) else: self.token = '' print('Login failed with error: {}'.format(str(r.status_code))) """ Get token """ def __get_token(self): return self.token """ Post work log when user is recognited @param: image_path = Image path is set into Backend Server /publish/evidence @param: username = Name of staff is recognited @param: status = Direction In or Out """ def post_worklog(self, image_path, username, status): userId = self.get_user_id(username) if userId == None: print('Failed to get username') return data = {"image": image_path} url = api.POST_WORKLOG + '/{}/{}'.format(userId, status) print(url) print(userId) r = requests.post(url, json=data, headers={'access-token': self.token}) if r.status_code == 200: print("Post worklog successful!") else: print("Failed to post worklog!") return r.status_code #self.__post_method(url, files= data) # def post_worklog(self, image_path, username, status): # userId = self.get_user_id(username) # if userId == None: # print('Failed to get username') # return # data = {"_id": userId, "username": username, "status": status, "image": image_path} # url = api.POST_WORKLOG + '/{}/{}'.format(userId, status) # print(userId) # r = requests.post(url, json=data, headers={'access-token': self.token}) # if r.status_code == 200: # print("Post worklog successful!") # else: # print("Failed to post worklog!") #self.__post_method(url, files= data) """ Get user info to return to client @param: user_name = Username of staff @return: userInformation """ def get_user_info(self, user_name): userID = self.get_user_id(user_name) url = api.GET_USER_INFO.format(userID) data = self.__get_method(url) return data """ Get user ID @param: username = Username of staff need to get UserID @return userID = String of userID """ def get_user_id(self, username): username = username.lower() url = api.GET_USER_ID.format(username) return self.__get_method(url) """ Generic GET method @param: url: Url of get method @return: 200: Successful 403: Error Not Found """ def __get_method(self, url): if not self.token: print("Token empty, try to login again!") self.login() r = requests.get(url, headers={'access-token': self.token}) if r.status_code == 200: return r.json()["data"] elif r.status_code == 403: print(r.json()["errors"]) # Try to login again self.login() return def opendoor(self, url, myfiles): r = requests.post(url, json = myfiles) return r.text """ Generic POST method @param: url = URL of post method @param: files = Files to upload if need """ def __post_method(self, url, files = None): if not self.token: print("Token empty, try to login again!") self.login() r = requests.post(url, files= files, headers={'access-token': self.token}) print(r.status_code) """ Send the notification with firebase @param: image_src: Path of image evidence """ def notify_stranger(self, image_src): self.push_fcm.notify_topic_subscribers( topic_name = 'unknown', message_title = 'Stranger detect!!!', message_body = image_src ) return 200
class GFireBase: def __init__(self, channel): self.config = channel.config self.push_service = FCMNotification(api_key=settings.FCM_API_SERVER_KEY) def notify_single(self, message): # TODO: Add model for subscribe list_username = list(message.user.all().values_list("username", flat=True)) subscriptions = Subscribe.objects.filter( user__username__in=list_username, channel_id=message.channel.id, active=True).values_list('contact', flat=True) list_contact = [] for contacts in subscriptions: for contact in contacts: list_contact.append(contact) subscriptions = list(list_contact) valid_registration_ids = self.push_service.clean_registration_ids(subscriptions) image = message.data.get('image') click_url = message.data.get('url') result = self.push_service.notify_multiple_devices(registration_ids=valid_registration_ids, message_title=message.title, message_body=message.body, extra_notification_kwargs={"image": image}, data_message=message.data, click_action="FLUTTER_NOTIFICATION_CLICK", content_available=True, extra_kwargs={"mutable_content": True} ) return result def notify_broadcast(self, message): image = message.data.get('image') click_url = message.data.get('url') topic = message.data.get("topic") user_type = message.data.get("user_type") if message.data.get("user_type") else "unknown_user" channel = message.channel topic_channel = f"{channel.type}_{user_type}" result = self.push_service.notify_topic_subscribers(topic_name=topic_channel, message_title=message.title, message_body=message.body, extra_notification_kwargs={"image": image}, data_message=message.data, click_action="FLUTTER_NOTIFICATION_CLICK", content_available=True, extra_kwargs={"mutable_content": True}) return result def subscribe_topic(self, channel, registration_ids): topic_channel = f"{channel.type}" registration_ids = list(registration_ids) result = self.push_service.subscribe_registration_ids_to_topic(registration_ids, topic_channel) return result def unsubscribe_topic(self, channel, registration_ids): topic_channel = f"{channel.type}" registration_ids = list(registration_ids) result = self.push_service.unsubscribe_registration_ids_from_topic(registration_ids, topic_channel) return result def validate_registration_id(self, token_id): subscriptions = list(token_id) print(subscriptions) valid_registration_ids = self.push_service.clean_registration_ids(subscriptions) print(valid_registration_ids) if len(valid_registration_ids) > 0: return True, valid_registration_ids return False, []
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'olucurious' from pyfcm import FCMNotification push_service = FCMNotification(api_key="<api-key>") registration_id="<device registration_id>" message = "Hope you're having fun this weekend, don't forget to check today's news" result = push_service.notify_topic_subscribers(topic_name="global", message_body=message) print result
def enviar_notificacao(sender, **kwargs): push_service = FCMNotification(api_key="AIzaSyDXv8_47S0_g64d5sHvwZWpH98gyJDUhtc") push_service.notify_topic_subscribers(topic_name="bread", message_body=kwargs['conteudo'])