Exemplo n.º 1
0
def notify_users(firebase_connection, raspi_id, api_key, status):
    utils.print_with_timestamp('Sending notification to user')
    push_service = pyfcm.FCMNotification(api_key=api_key)

    utils.log_usage(status)

    # Loop until we get a device ID.
    phone_ids = None
    while not phone_ids:
        phone_ids = firebase_connection.get('devices/{}/phone_IDs'.format(raspi_id), None)
        if not phone_ids:
            time.sleep(1)

    results = []
    for phone in phone_ids.keys():
        if status == 'open':
            status = 'opened'

        timestamp = datetime.datetime.now().strftime('%I:%M %p on %A %b %d, %Y')
        msg = 'Your door was {} at {}'.format(status, timestamp)
        result = push_service.notify_single_device(registration_id=phone,
            message_title='Garage door update', message_body=msg, sound="Default")

        # TO-DO: Try to send notifications multiple times if there is a failure
        if not result['success']:
            utils.print_with_timestamp('notification failed to send')
            utils.log_error('notification-failure', data=result)

        results.append(result)

    return results
Exemplo n.º 2
0
def send(id, visitor):
    push_service = pyfcm.FCMNotification(api_key="####")

    message_body = visitor + "님이 방문했습니다"
    registration_id = getToken(id)
    data = {"title": "BANGBANG 방문자 알림", "body": message_body}

    if registration_id != "empty":
        result = push_service.notify_single_device(
            registration_id=registration_id, data_message=data)
        print(result)
    else:
        print("등록된 기기가 없습니다.")
Exemplo n.º 3
0
 def __init__(self, **kwargs):
     params = {'api_key': kwargs['api_key']}
     if 'proxy' in kwargs and kwargs['proxy']:
         proxies = kwargs['proxy'] if isinstance(kwargs['proxy'], list) else [kwargs['proxy']]
         proxy_dict = {}
         for proxy in proxies:
             if proxy.startswith('http://'):
                 proxy_dict.update({'http': proxy})
             elif proxy.startswith('https://'):
                 proxy_dict.update({'https': proxy})
             else:
                 raise ProxyError('proxy type not supported')
         if bool(proxy_dict):
             params.update({'proxy_dict': proxy_dict})
     self.service = pyfcm.FCMNotification(**params)
Exemplo n.º 4
0
def send_push_notification(payload):
    try:
        push_service = pyfcm.FCMNotification(api_key=API_KEY)

        start = time()
        result = push_service.notify_single_device(
            registration_id=REGISTRATION_ID, data_message=payload)
        end = time()

        print('Notification took %.2f seconds to send' % (end - start))
        print(dumps(result, indent=3))

    except pyfcm.errors.FCMServerError as e:
        # This usually occurs when the PI has a weak internet connection
        # or FCM's servers can't be reached for some reason
        print("Couldn't send notification: %s" % e)
Exemplo n.º 5
0
 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.senderID = router_conf.get("senderID")
     self.auth = router_conf.get("auth")
     self._base_tags = ["platform:fcm"]
     try:
         self.fcm = pyfcm.FCMNotification(api_key=self.auth)
     except Exception as e:
         self.log.error("Could not instantiate FCM {ex}", ex=e)
         raise IOError("FCM Bridge not initiated in main")
     self.log.debug("Starting FCM router...")
Exemplo n.º 6
0
 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...")
Exemplo n.º 7
0
def push():
    print("push start!")
    with open('./status.json', encoding='utf-8') as j_file:
        json_data = json.load(j_file)
    push_service = pyfcm.FCMNotification(
        api_key=
        'AAAAmKROC5Y:APA91bEi-2ni1Qz4kWrIPGf5WGnkUU4E4ZLJQ_O_HFqLl3SRuTcXuMyM4-ajlETZ4gXFe6OqPov6dvrpCNBYOkss5a022I6bEfImBNnQYKabtJ0QJCi4LHzQl4WLWXskqaqoqzAPdEkr'
    )
    print(json_data['token'])
    try:
        response = push_service.notify_single_device(
            registration_id=json_data['token'],
            message_title='화재발생',
            message_body='화재가 발생하였습니다. 대피 바랍니다.',
            sound='Default')
    except errors.InvalidDataError:
        print("error:push invalid data")
        return None
    else:
        return response
Exemplo n.º 8
0
def send_fcm_notification(msg_title: str, msg_body: str, device_id: str):
    push_service = pyfcm.FCMNotification(api_key=API_KEY)
    device_id = 'device {}'.format(device_id)
    result = push_service.notify_single_device(registration_id=device_id,
                                               message_title=msg_title,
                                               message_body=msg_body)

    if not result['success']:
        with open('notification_failures.txt', 'a') as errors_file:
            errors_file.write('Notification failure occurred at {}\n'.format(
                datetime.datetime.now()))
            errors_file.write(
                'Attempted to send msg_title: {}\n'.format(msg_title))
            errors_file.write(
                '               and msg_body: {}\n'.format(msg_body))
            errors_file.write('to device: {}\n'.format(device_id))
            errors_file.write('with api_key: {}\n'.format(API_KEY))
            errors_file.write(
                '\n-------------------------------------------------\n')

    return result
Exemplo n.º 9
0
def get_fcm_service_channel():
    return fcm.FCMNotification(api_key=FCM_SERVER_KEY)
Exemplo n.º 10
0
import pyfcm as fcm

from bottle import route, abort
#from bson.objectid import ObjectId

from logger import get_logger
from constants import *
from utils import *

sys.path.append(CONFIG_FILE_PATH)
from config import *

log = get_logger(logFileName="webServer.log")
con = get_mongo_connection()
db = get_app_db(con)
fcm_service = fcm.FCMNotification(api_key=FCM_SERVER_KEY)


@route('/register', method='POST')
def user_alert():
    form = None
    try:
        users = get_users_collection(db)
        user = json.load(bottle.request.body)

        if "token" not in user:
            raise Exception("App Registration Token missing!")

        fcm_service.notify_single_device(
            registration_id=user["token"],
            message_title="Registration Successful!",
Exemplo n.º 11
0
def main(argv):
    pass


if __name__ == '__main__':
    main(sys.argv)
import logging
import random
import db_helpers as helpers
import time

import config
import pyfcm

if config.FIREBASE_APIKEY:
    fcm = pyfcm.FCMNotification(api_key=config.FIREBASE_APIKEY)


def HandleNotification(game_state, queued_notification_id,
                       queued_notification):
    """Helper function to propogate a notification."""

    if 'playerId' in queued_notification and queued_notification[
            'playerId'] is not None:
        public_player_ids = [queued_notification['playerId']]
    elif 'groupId' in queued_notification:
        public_player_ids = game_state.get(
            '/groups/%s' % queued_notification['groupId'], 'players')
        if public_player_ids is None:
            public_player_ids = []
        else:
Exemplo n.º 12
0
 def load_config(self, fcm_api_key, telegram_api_key):
     if fcm_api_key is None or fcm_api_key == "":
         self.fcm = None
         logging.error("No FCM key found, disabling")
     else:
         self.fcm = pyfcm.FCMNotification(fcm_api_key)
Exemplo n.º 13
0
 def fcm(self):
     return fcm.FCMNotification(**settings.PUSH_FCM)
 def __init__(self):
     self.push_service = pyfcm.FCMNotification(api_key=MY_API_KEY)
     self.logger = logging.getLogger(constants.NAZWA_LOGGERA)
     return
Exemplo n.º 15
0
# Send to single device.
import argparse
import pyfcm

if __name__ == '__main__':
    # parse arguments or use defaults
    parser = argparse.ArgumentParser(description='OpenHAB Push Notifier')
    parser.add_argument('-topic',    required=True,  help='Topic')
    parser.add_argument('-msg',    required=True,  help='Message')

    args = parser.parse_args()

    push_service = pyfcm.FCMNotification(api_key="AAAAryqDsSM:APA91bGIv1tk_ilQPP3Srhh96k1QDIZcbvpE5VtTXrdOxd7dOnbG1cYHcCqC-u3mUB6vLXjwaPg-BJYu3YCtLVne8fd8AWT20taskHT7Icfk4UKW6epFunvhTBC4vqptO0uO7lffuLnI")

    registration_id = "cg3ysVO1BAY:APA91bFXJaO8pPehkP2jxTBLebF3fem92kHpNkkDYDt6ju-q9Jw63IBu-EYdDXd2UMvcfXvjxLxNyoMmxC-z6HRluiUyccgGlqWbOCL42mUPZCG2ExOwT5r9wo5J5W_vxK1ff2s9D8_I"
    message_title = "OpenHAB Event"
    message_body = "PYFCM test message"
    #push_service.notify_topic_subscribers(topic_name="global", message_body=message_body)
    result = push_service.notify_single_device(registration_id=registration_id, message_title=args.topic, message_body=args.msg)

    print result