示例#1
25
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
                                            )
示例#2
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
示例#3
0
文件: fcm.py 项目: xtrinch/fcm-django
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
示例#4
0
def push_test_ios(request):

    push_service = FCMNotification(api_key="AAAAwJiGQL0:APA91bH0yzNqpkRvB8hgnz64g-OKSjjGJADjtr8njfmY_EuucOAXFciONvfn9ooxqkkPHb3Mt9wZ2LLEEfQn4KFVkKfS8A_7sMQh9mjHUXsGLBseO31m_zOy9c39k3wwim8x0ojvw6ia")
    title_ios = str("구독중인 "+ "헿" + " 이/가 변경되었습니다!")
    message_ios = str("민섭이혀엉~")
    try:
        toke_ = ["ec575CPxhj8:APA91bEd64mo-Qw_a6mKYmEIgJ3ui4_qOv_6Cd96XRoHiDeR_IX_zbliwvdNDyNAbASmut9tuPPgY00MzUlVRP33x11I6YxfRY2T-Syli8U0FeJ1L2AuClaIa5PhbzR0uLvouDmOwfXQ"]
        result = push_service.notify_single_device(registration_id=toke_[0], message_title=title_ios,
                                                   message_body=message_ios)
        # result = push_service.notify_multiple_devices(message_title=title_ios, message_body=message_ios, registration_ids=toke_, data_message={})
    except Exception as e:
        print(e)
    return render(request, 'refresh/push_server_page.html')
示例#5
0
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)    
示例#6
0
def MOTION (PIR_PIN):
    print ("Motion detected by PIR. E-mail notification sent")
    addTimeToNotification()
    print (notificationTime)
    camera()
    push_service = FCMNotification(api_key="AIzaSyBxUGqEvrIxL0-5-wzfhr2EjmHXdQe3vcA")
    message_title = "Varsel"
    message_body = "Bevegelse oppdaget av bevegelsessensor"
    result = push_service.notify_single_device(registration_id=registration, message_title=message_title, message_body=message_body)
    print result
    #print registration
    #writelog()
    sleep(5)
示例#7
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)
示例#8
0
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)
示例#9
0
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)
示例#10
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
示例#11
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;
示例#12
0
    "projectId": "lnctdata",
    "storageBucket": "lnctdata.appspot.com",
    "messagingSenderId": str(os.getenv('messageid1')),
    "databaseURL": "https://lnctdata.firebaseio.com"
}
firebase = Firebase(config)
database = firebase.database()


def getAttendance():
    users = database.child().get().val()
    for x in users:
        data = dict(users[x])
        token = data.get('token')
        loggedout = data.get('loggedout')
        if (token and loggedout == 'False'):
            password = f.decrypt(data.get('password').encode())
            attendance = main(x, password.decode())
            send(token, data.get('name'), attendance)


push_service = FCMNotification(api_key=str(os.getenv('fcmkey')))


def send(registration_id, name, attendance):
    message_title = 'Hey ' + name + '!'
    message_body = "Your attendance is " + str(attendance) + '%'
    result = push_service.notify_single_device(registration_id=registration_id,
                                               message_title=message_title,
                                               message_body=message_body)
示例#13
0
    for a in hase:
        ida=a['_id']
        category=a['category']

    print(i)
    print(ida)
    print(category)
    i=i+1
    string = '{"id":"' + str(ida) + '","category":"' + str(category) + '"}'


    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()
示例#14
0
def send(account, subject):
    push_service = FCMNotification(api_key=FCM_API_KEY)
    push_service.notify_topic_subscribers(topic_name=account,
                                          message_body=subject)
示例#15
0
文件: a.py 项目: Asmodius/sanic-fcm
from pyfcm import FCMNotification

# FCM_API_KEY = 'AIzaSyCjBdZMAfObGEQ-JW44lZEcrZ6cQp5pPy0'  # заменить на боевом сервере!
# заменить на боевом сервере!
FCM_API_KEY = ('AAAAX9g1pF4:APA91bGiOWHhq7vCuPjzm-V79CMp7pnbASTaYN7pWf1lPH7P8DCWtL9_OYCmQKY'
               '-qb2DmIdjdxbk3NyDPJpWVrzMJzXnLYqUJzmM1UH3O2e89DNGguhSOBlrC4DWkC8uSzCDO0M2mvB6')

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 = '0:1432811719975865%54f79db3f9fd7ecd'
registration_id = ('9WNAyu45m-RHB9VA9aT2XzQnePEgbegFHxdlbuFXB7MELt_JFVm7faFYUIrPYoHcXsRmDoMrBV4SHA'
                   '0Kjm-y215vf_Uz1-1j6e933hbYXtVEsX6gMwyU0_eWSy2KrSpYfxVwLZoN_VdrYi9cYb/retMs')

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,
                                           dry_run=True)
print(result)

res = {
    'multicast_ids': [-1],
    'success': 0,
    'failure': 1,
    'canonical_ids': 0,
    'results': [{'error': 'InvalidRegistration'}],
    'topic_message_id': None
}
示例#16
0
def FCMDATA(request, userNumber, orderID, merchantName, merchantNumber,
            userName, itemsList, netPrice, itemPrice, orderNo, status,
            available, amountItems, confreeStatus, ETA, category, date,
            merchantFcm):

    # d= Fcm.objects.values_list('instance_token', flat=True).order_by('p_id')
    # a= [x.encode('utf-8') for x in d]
    # d= {"to":a,"message":"hello contree"}
    #  fd=(json.dumps(d,indent=2))
    from pyfcm import FCMNotification

    # push_service = FCMNotification(api_key="AIzaSyD4KKKdU3Vs9-l5aInS_fArrs33zfpcRcQ")
    #"AIzaSyAyr0ors7D1lVnhescbztbu7Z8F1pKqwEw"
    # OR initialize with proxies

    #proxy_dict = {
    #         "http"  : "http://fcm.googleapis.com/fcm/send",
    #        "https" : "http://fcm.googleapis.com/fcm/send",
    #     }
    push_service = FCMNotification(
        api_key="AIzaSyD4KKKdU3Vs9-l5aInS_fArrs33zfpcRcQ",
        proxy_dict="https://fcm.googleapis.com/fcm/send")

    # Your api-ey can be gotten from:  https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging
    registration_id = str(merchantFcm)
    #print registration_id
    # registration_id = "eokhSdiw62A:APA91bG2TeLHBbWG7yqgqjJ9R9Tsq4REy454uKkcsPEWGjaUVJO0t-inEUR-dmm8gpzlPfzPY9OtWsJGLWs3Ypo3zSsS9GTH0GkoO2JjBwjVUY_ZBMQmSTWqoBlb9t-KIUDm6X1Fm5Qz"

    message_title = "Data Merchant Order"
    #message_body =  "hrlo"

    d = {
        "userNumber": userNumber,
        "orderID": orderID,
        "merchantName": merchantName,
        "merchantNumber": merchantNumber,
        "userName": userName,
        "itemsList": itemsList,
        "netPrice": netPrice,
        "itemPrice": itemPrice,
        "orderNo": orderNo,
        "status": status,
        "available": available,
        "amountItems": amountItems,
        "confreeStatus": confreeStatus,
        "ETA": ETA,
        "category": category,
        "date": date,
        "fcm": registration_id
    }
    # print d

    result = push_service.notify_single_device(registration_id=registration_id,
                                               message_title=message_title,
                                               message_body=d)
    #print message_body
    # Send to multiple devices by passing a list of ids
    #d= Fcm.objects.values_list('instance_token', flat=True).order_by('p_id')
    # print d
    #a=[x.encode("utf-8")for x in d]
    #print a
    #registration_ids = a
    # registration_ids = ["dF3sPsoN4WM:APA91bGDQ2mFcPbkYqKOl0OJdKhvCX3xndN7Ek-3ms2rRI_qfcqxdyIpZPYpIkLrCyE_cM_zqWPsb7vuXe_vVyHdFRqDlemYXoKZpZt0nux8qE4FXlXSvPoJNK-K3ZdyGk6dXQj5yAxP","fVKt48LuSBE:APA91bFh1rOCmjTrhz1NZUsdRVCrgay6YRTwj9u5qfMe0IiQO3ZDkzP50hJuNwC6BZZM1lTUJb1FtNNeiCiNAefRuJCQJpBxBXpNPt6dqYVkUyC9ONYWCpXon1J4MLx3ntGAQa2YYycp","eNvxhcQ4zRo:APA91bGwN9g4dpAOW0BvjDlnImiVjnI893JI9rG3J1CSFC8yC6Sm9NtOR5avCZt8VeZeh_L8F5kMpckVBnGzKEW8_PNdzGOv_FQI363lPWkuRGhwm2evGHVumjpJpXm4dfWpGAfEhSYv","cPJ0ZttEsmU:APA91bFQARBaCuF6aFskaTuk_ymz32V8Y-lvFAvUtlz4s2BMQJjZoKZItFPQ22yuVGI-9UgfMWnzGSGsmNlIvfjR_sTZZDx_5f3sLEAQ-VnpGi9UGZmKcFXHBYH5FFZ7mu1A-s-QBpch"]
    #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
    t = json.dumps(result)
    if (result["success"] == 1):
        return HttpResponse("your message has been sent successfully")
    else:
        #return HttpResponse("NOT sent message somthing went wrong")
        return HttpResponse(json.dumps(d))
示例#17
0
from pyfcm import FCMNotification

api_key = "YOUR_SERVER_KEY"
registration_id = "YOUR_DEVICE_TOKEN"
push_service = FCMNotification(api_key)

for i in range(1, 2):
    data = {
        "collapse_key": "123456",
        "name": "ashutosh",
        "no": "9911224455",
        "count": 1
    }
    result = push_service.single_device_data_message(registration_id,
                                                     data_message=data)
    print(result)
示例#18
0
#UNTUK SAVE GAMBAR
def save(encoded_data, filename):
    arr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
    img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
    return cv2.imwrite(filename, img)


def tambahLogs(logs):
    f = open(
        app.config['LOGS'] + "/" + secure_filename(strftime("%Y-%m-%d")) +
        ".txt", "a")
    f.write(logs)
    f.close()


push_service = FCMNotification(api_key=app.config['FCM_ANDROID'])


def push_notifications(id_user, id_notification_category, data_users,
                       message_title, message_body):
    dt = Data()
    registration_ids = data_users

    message_body = {
        "title": message_title,
        "body": str(id_notification_category) + '#' + message_body,
        "content_available": True,
        "priority": "high"
    }

    query1 = 'INSERT INTO `notification`(`id_user`, `id_notification_category`, `message_title`, `message_body`) VALUES (%s,%s,%s,%s)'
示例#19
0
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'])
示例#20
0
from flask import Flask, request
from flask_restful import Resource, Api
from pyfcm import FCMNotification

push_service = FCMNotification(
    api_key=
    "AAAAbyL8xP4:APA91bGR-5gW5_yHzD8CuQYgiko11sJ_tzo9Oupp1XjAZBaxHpYLXaUz9M4vjOA49spcm296a3N3q5C98qeG0GDRa29S44Py3XBfXSbP1K1o7sX9L_jOBe0PV2oElanPVOAlPKaK-JTW"
)

#push_service = FCMNotification(api_key="<api-key>", proxy_dict={})


class SendingNotification(Resource):
    def __init__(self, **kwargs):
        self.db = kwargs['data']

    def post(self):
        userData = request.get_json(force=True)
        registration_id = "dLtl5QjoVIE:APA91bHvXmfh3TZTTVlKAMaxZDjeJuy8ynraEA3-7p6UqWon_5xAc-DWHjwe_6SZmdB_AZXKvat-YGA3ukhjzLLnVLHjcsrlmlU10nMw5rZMQ1DOJAQQx4Nd64HZPdsHCIi6qSJB8_LF"
        message_title = str(userData["title"])
        message_body = str(userData["message"])
        result = push_service.notify_single_device(
            registration_id=registration_id,
            message_title=message_title,
            message_body=message_body)
        # result = push_service.notify_multiple_devices()
        return {"msg": result}
示例#21
0
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import requests
import traceback
from ..config import Config
from pyfcm import FCMNotification

push_service = FCMNotification(api_key=Config.FCM_SERVER_API_KEY)


def get_favorite_eventid_information(eventid):
    data = dict()
    url = "%s%s" % (Config.FAVORITE_EVENTID_ENDPOINT_PREFIX, eventid)
    headers = {"ROKWIRE-API-KEY": Config.ROKWIRE_API_KEY}
    req = requests.get(url, headers=headers)
    if req.status_code == 200:
        req_data = req.json()
        data['ndevices'] = len(req_data)
        data['tokens'] = [device.get("deviceToken") for device in req_data]
    return data


def send_notification(title, body, data, tokens):
from urllib.parse import urlencode, quote_plus
from pymongo import MongoClient
import xmltodict, json
from datetime import date, timedelta
from pyfcm import FCMNotification

cluster = MongoClient(
    "mongodb://*****:*****@cluster0-shard-00-00.6v20o.mongodb.net:27017,cluster0-shard-00-01.6v20o.mongodb.net:27017,cluster0-shard-00-02.6v20o.mongodb.net:27017/three-step?ssl=true&replicaSet=atlas-1s13em-shard-0&authSource=admin&retryWrites=true&w=majority"
)

db = cluster["three-step"]
local_realtime_close = db['local_realtime_close']
local_realtime_open = db['local_realtime_open']

APIKEY = "AAAAsLhtlp8:APA91bF7A7f_Rr0tBhpZmgBAzZ5wAIGifzAyMtLJgerJyR-uX6t6bdpjyZ6dNE1IDOk22wm3vItH9xx4mZwzzI_4lcbGBJ-ZBi8kHh9Cxwf_2Kb14SUAnDPkCFPZhHGEP-pdYEeucLfS"
push_service = FCMNotification(APIKEY)

jsonObj = {}

url = 'http://www.localdata.go.kr/platform/rest/TO0/openDataApi'

today_form = date.today()
day1_form = date.today() - timedelta(1)
day2_form = date.today() - timedelta(2)
day3_form = date.today() - timedelta(3)
day4_form = date.today() - timedelta(4)
day5_form = date.today() - timedelta(5)
day6_form = date.today() - timedelta(6)
day7_form = date.today() - timedelta(7)

today = today_form.strftime('%Y%m%d')
示例#23
0
    def send_error_push_notifications(self, registration_ids, error_message):
        push_service = FCMNotification(api_key=os.getenv('FCM_API_KEY'))

        data_message = {"title": "Error", "message": error_message}
示例#24
0
文件: Web.py 项目: sdg9670/SHS-Server
from flask import Flask, request
import json
import datetime
import databaseManager
from pyfcm import FCMNotification

db = databaseManager.DatabaseManager('localhost', 'root', '!Dasom0129', 'shs')
push_service = FCMNotification(
    api_key=
    "AAAAXE7sxxA:APA91bGJVD6TxWf_9WBZS97vToJ18SG-OnslG8g-crwm1WjJxPVa9gBvPFm3C4ma0lpHuOZuLOepeOPftXA4DmBQjcsejFFKjt2rFarqpdk8zNm2oay-JCLpu5N_bAWezdSKYGUP8RD1"
)
app = Flask(__name__)


def json_default(value):
    if isinstance(value, (datetime.datetime)):
        return value.__str__()


@app.route('/doorlock_image', methods=['GET'])
def GetDoorLockImage():
    dong = request.args.get('dong')
    ho = request.args.get('ho')
    data = None
    data = db.executeQuery(
        "select * from doorlock_image where dong = %s and ho = %s order by id desc",
        (dong, ho))
    print(str(json.dumps(data, ensure_ascii=False, default=json_default)))
    return json.dumps(data, ensure_ascii=False, default=json_default)

示例#25
0
from rest_framework.views import APIView
from rest_framework.parsers import FormParser, MultiPartParser


from api.models import (
    Device,
    Location,
    Event,
    Trip,
    Session
)
from .auth import DemoTokenAuthentication

from math import sin, cos, sqrt, atan2, radians

push_service = FCMNotification(api_key="AAAAwxOFtl0:APA91bFAEvVwO9ZPtZi2gczrXOl2VH72Nx_BeXFwr2jg44LPDiwTqaonjOguxTtAHNrTFSV9c84d2oNiq2Gm-Q0FDiNUlf24lY2eTfMnnQn8pQx3_Hk5L-4kvfHbgqVQk8M1zgNZiIgo")


def calculate_distance(p1,p2):
    # approximate radius of earth in km
    R = 6373.0


    lat1 = radians(p1[0])
    lon1 = radians(p1[1])
    lat2 = radians(p2[0])
    lon2 = radians(p2[1])

    dlon = lon2 - lon1
    dlat = lat2 - lat1
示例#26
0
import logging
from raven.contrib.django.raven_compat.models import client as sentry_client

from django.conf import settings
from pyfcm import FCMNotification

from karrot.subscriptions import stats
from karrot.subscriptions.models import PushSubscription

logger = logging.getLogger(__name__)

fcm = None

if hasattr(settings, 'FCM_SERVER_KEY') and settings.FCM_SERVER_KEY:
    fcm = FCMNotification(api_key=settings.FCM_SERVER_KEY)
else:
    logger.warning('Please configure FCM_SERVER_KEY in your settings to use push messaging')


def notify_subscribers(subscriptions, fcm_options):
    if len(subscriptions) < 1:
        return
    tokens = [item.token for item in subscriptions]

    success_indices, failure_indices = _notify_multiple_devices(
        registration_ids=tokens,
        **fcm_options,
    )

    success_subscriptions = [subscriptions[i] for i in success_indices]
    failure_subscriptions = [subscriptions[i] for i in failure_indices]
示例#27
0
文件: fcm.py 项目: xtrinch/fcm-django
def fcm_send_bulk_data_messages(
            api_key,
            registration_ids=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,
            content_available=None,
            timeout=5,
            json_encoder=None):
    """
    Arguments correspond to those from pyfcm/fcm.py.

    Sends push message to multiple devices,
    can send to over 1000 devices

    Args:
        api_key
        registration_ids (list): FCM device registration IDs.
        data_message (dict): Data message payload to send alone or with the notification message

    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.
    """
    push_service = FCMNotification(
        api_key=SETTINGS.get("FCM_SERVER_KEY") if api_key is None else api_key,
        json_encoder=json_encoder,
    )
    return push_service.multiple_devices_data_message(
        registration_ids=registration_ids,
        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,
        content_available=content_available,
        timeout=timeout
    )
示例#28
0
###########################################################
###########TODO:pip install eventlet while using heroku
###############:pip install gunicorn.......
###########TODO:add ip address while deploying ###############################################################################################>>>>>>>
######################################################

app = Flask(__name__)

#app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@ec2-54-235-104-136.compute-1.amazonaws.com:5432/d5qk9k31qkg616'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DATABASE_URL", "error")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
socketio = SocketIO(app)

push_service = FCMNotification(
    api_key=
    "AAAALb0py6M:APA91bEOOXI7rph7KXP4VhjYe_xApxZzmnjkX2a-3R3OxvhlZQXQx7w8YS6JK6KrRIiK6wXX5GzdCHlH9KRyir5tPnfQp_Ni0Hp6Oolnushxlb9bgTDq4vofY2LhpActkAqf_SdYS7_2"
)

slnoforcommt = 0


class filestore(db.Model):
    __tablename__ = "filestore"
    slno = db.Column('slno', db.Integer, autoincrement=True, primary_key=True)
    userid = db.Column('userid', db.Integer)
    naof = db.Column("comm", db.String(20))
    etime = db.Column("etime", db.Integer)

    def __init__(self, userid, naof):
        self.userid = userid
        self.naof = naof
示例#29
0
 def init_push_service(self, api_key):
     self.push_service = FCMNotification(api_key=api_key)
示例#30
0
from pyfcm import FCMNotification
push_service = FCMNotification(api_key="AAAALXgG6s8:APA91bHaUoZ9MwS78rdihRMc7GsN-NQ8oNDSEjEZcDMeU7DyAr_8EJRHCB_o13ydJXpGYLu4Nl3sA5rpNW6pPdK5Q9Fa50R6zdO6fiQnDU8OG7ZC7hieVYdTn_NeeBTY-XIRwowDh0KA")

registration_idLenovo="efNEoC5EUlg:APA91bGjWMcjMp2LxuyjRPjoAkdTL_px4t8iHITBNrku2gdPAsczs-hvPO8SKcyYxyhg1yMhTT3anZSxRnkJjS85aQyDErb4pGfvrfA8N7uDSmqb_vSaM4D5xODzUuCCwY88ApFw5MkU"
registration_idLoki = "cJgkzsCtdWI:APA91bFtwDKqHfyTUz4FNPV8OepucAQ8Wx840xddmjV0HztLHkkQsz2is7QFZK7o67SC4yjXV0oceWywSCkGTkfOpE9V_C51PddQIfaE3F5SkOWvAkqY7RYinze8Z0FjWCe57sy4p6lC"
registration_idLaptop="edgivMskGxQ:APA91bH-vIHwz1l4-kDmlqhwoJ41NwQGOGb2KCawiOMGAhmtGabeI_nGdUmp9AJ8GdtslFf3UMao-Wy9SAsd_eCa7ELxUUliFdW48k7sZCxAP_MPVLLjyuLVn86LOad3_xvQ_-eXAokX"
registration_ids = [registration_idLoki, registration_idLenovo,registration_idLaptop]

message_title = "CricNotify"
message_icon="firebase-logo.png"

def fbpush(message_body):
    try:
        result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title,message_body = message_body ,message_icon=message_icon)
        print(result)
    except:
        print("An exception occurred while trying to notify firebase")
示例#31
0
from pyfcm import FCMNotification

push_service = FCMNotification(
    api_key=
    "AAAAm7WZSgs:APA91bEtIkVJdK_dVnRvfHrnRgQm5y3WL5bdhm4WNvarrBQWYELpcS-Gjr3C8u5iLX0GkT79b3jVWHu5EGPKP6tvr6zrC7w0xjiiX-vo7In8MUNdrDqzZnY9_M5PErhHWLREr5arBBBi"
)

registration_id = "f1oLvxtvIN8:APA91bHVrK_Qcz22fVlnITN6DTf6z2AOqxxxvDsh8uInUap_wmAi9f_F8MIbrWEHxMpfiH-n_WIxfWg_IF1QGmV89Jz45rSKweB6Rq7QB5x5VGGKi_YtE-D-0BobctikxdIhAy6vMCAh"
message_title = "Deutchland deutchland"
message_body = "Uber Alles"
result = push_service.notify_single_device(registration_id=registration_id,
                                           message_title=message_title,
                                           message_body=message_body)
print(result)
示例#32
0
import datetime
import firebase_admin
from firebase_admin import credentials, auth, db
from pyfcm import FCMNotification

push_service = FCMNotification(
    api_key=
    'AAAA5UoD0m8:APA91bGfwqFu_W6POM9liLPR_HQpFVW2Jn1dXHmOLb1px9aHxx_3q8f1_7MISFx-57u14Tu8MLY6BRiK2L8TNZjd-o5BSBI0n9OGK3ql4AwJAyxcDytaZvjTQY6LiwTiptVSjQDdl_Jj'
)

#Firebase Initialization
cred = credentials.Certificate(
    'static/cubetastic-33-firebase-adminsdk-89yl9-fe0a5bbca0.json')
default_app = firebase_admin.initialize_app(
    cred, {'databaseURL': 'https://cubetastic-33.firebaseio.com'})


def create_user(uid, email, location, phone, username, profilePic):
    db.reference('users').child(uid).set({
        'email': str(email),
        'location': str(location),
        'phone': str(phone),
        'profilePic': str(profilePic),
        'username': str(username)
    })
    return 'created user ' + str(username) + '.'


def user_exists(uid, username):
    users = db.reference('users').get()
    usernameExists = []
示例#33
0
#!/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)
示例#34
0
文件: push.py 项目: dfsan/meteocool
    if os.path.isfile(apns_config_file):
        config = None
        with open(apns_config_file) as conf_file:
            config = json.load(conf_file)
        apns = APNsClient(
            team_id=config["team_id"],
            bundle_id=config["bundle_id"],
            auth_key_id=config["auth_key_id"],
            auth_key_filepath=config["auth_key_filepath"],
            use_sandbox=config["use_sandbox"]
        )

    # Android push setup. The API key comes from the environment.
    fcm = None
    if os.getenv('FCM_API_KEY', None):
        fcm = FCMNotification()

    # mongodb setup
    db_client = MongoClient("mongodb://mongo:27017/")
    # both will be created automatically when the first document is inserted
    db = db_client["meteocool"]
    collection = db["collection"]

    # forecast file enumeration & import
    forecast_files = sorted(glob.glob(radar_files + "/FX*_*_MF002"))
    max_ahead = 0
    forecast_maps = {}
    for f in forecast_files:
        forecast_maps[max_ahead] = wrl.io.radolan.read_radolan_composite(f)
        max_ahead = max_ahead + 5
    max_ahead -= 5
示例#35
0
    def post(self, request, *args, **kwargs):
        user = request.user
        print(request.data.keys())
        if 'to_userid' not in request.data.keys():
            return Response(
                {
                    'message': 'Please provide to user id',
                    'success': 'False',
                },
                status=400)
        if 'notification_msg' not in request.data.keys():
            return Response(
                {
                    'message': 'Please provide to notification_msg',
                    'success': 'False',
                },
                status=400)
        if 'notification_type' not in request.data.keys():
            return Response(
                {
                    'message': 'Please provide to notification_type',
                    'success': 'False',
                },
                status=400)

        uid = request.data['to_userid']
        if not uid or uid == '':
            return Response(
                {
                    'message': 'Please provide to user id',
                    'success': 'False',
                },
                status=400)

        touser = User.objects.filter(id=uid).first()
        if not touser:
            return Response(
                {
                    'message': 'Invalid to user id',
                    'success': 'False',
                },
                status=400)

        notification_msg = request.data['notification_msg']
        if not notification_msg or notification_msg == '':
            return Response(
                {
                    'message': 'Please provide to notification_msg',
                    'success': 'False',
                },
                status=400)

        notification_type = request.data['notification_type']
        if not notification_type or notification_type == '':
            return Response(
                {
                    'message': 'Please provide to notification_type',
                    'success': 'False',
                },
                status=400)
        if notification_type not in ('4', '5'):
            return Response(
                {
                    'message': 'Please provide valid notification_type',
                    'success': 'False',
                },
                status=400)

        api_key = ''
        if api_key != '':
            print('inside push notification')
            push_service = FCMNotification(api_key=api_key)
            registration_id = friend.device_token
            message_title = "KishMalik Notification"
            message_body = notification_msg
            result = push_service.notify_single_device(
                registration_id=registration_id,
                message_title=message_title,
                message_body=message_body)

            un = UserNotification(
                user=touser,
                notification=notification_msg,
                req_type=notification_type,
                ref_id=user.id,
            )
            un.save()

            return Response(
                {
                    'message': 'Notification sent successfully',
                    'success': 'True',
                },
                status=200)
        else:
            return Response(
                {
                    'message': 'Please provide firebase api key',
                    'success': 'False',
                },
                status=400)
示例#36
0
 def __init__(self, api_key=FCM_API_KEY, user_keys=FCM_USER_ID_PATH):
     self.client = FCMNotification(api_key=api_key)
     self.user_keys = user_keys
     with open(user_keys, 'r') as f:
         self.user_ids = [i.strip() for i in f.readlines()]
            id_user=id_user,
            notification_picture=notification_picture)
        notifications.append(notification)
    try:
        db.session.add_all(notifications)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
    devices = Device.query.filter(Device.id_user.in_(users)).all()
    if len(devices) > 0:
        data_message = {"notification_type": notification_type}
        registration_ids = [device.registration_id for device in devices]
        push_notification_service.notify_multiple_devices(
            registration_ids=registration_ids,
            message_title=notification_title,
            message_body=notification_body,
            extra_kwargs={"id_notification_type": id_notification_type},
            click_action="FCM_PLUGIN_ACTIVITY",
            data_message=data_message)


# from pyfcm import FCMNotification
api_key = "AAAA9D-eCTQ:APA91bEMC9JRBAfymOc3qbQ8tRwTdbJJEydsGlkJ0jYRZ14SUM0cdNxBIB2axPgb4hhXh-s9wNtcml_uTgM-FL-lhIHnZb9FFDxuypQuKvAkgaxTE1Zs42yCy9N0uN4CfxFjVr4s1DWP"
push_service = FCMNotification(api_key=api_key)
registration_id = api_key
message_title = "Hello World"
message_body = "My First PushNotification"
result = push_service.notify_single_device(registration_id=registration_id,
                                           message_title=message_title,
                                           message_body=message_body)
print result
示例#38
0
__version__ = '1.5.4'  # Versioning: http://www.python.org/dev/peps/pep-0386/

import json
import logging
import random
import sys
import psycopg2
import requests
from faker import Faker
from pyfcm import FCMNotification

import push_helper as ph

# Instantiate PyFCM With API Key
push_service = FCMNotification(
    api_key=
    "AAAAkWfmn0k:APA91bFaHkrZQH6X7HlnUVlRXotiGOphHGsI4Uyjto0dh-cZQQsLOjhktEfKnw3niwy_6xO866KXKVyhrqEDVcFnh-Yp7uM2qnekeEiRJM-hCvJcp1zIhIR-aBQNZoYfmHyiecHd_cfG"
)
# Instantiate logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Create a file handler
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Establish connection to Postgres RDS
logger.info('Establishing database connection...')
conn = psycopg2.connect(
    database="pushengine",
    user="******",
    password="******",
    host="blackbox.c5oicakkxsxn.us-west-2.rds.amazonaws.com",
示例#39
0
#!/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
from notify_run import Notify

# import time
# from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.service import Service
from selenium import webdriver

# from selenium.webdriver.support.ui import WebDriverWait  # this & next two both needed for waiting
# from selenium.webdriver.common.by import By
# from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.common.keys import Keys

from pyfcm import FCMNotification

push_service = FCMNotification(
    api_key="AAAAK38byIs:APA91bE38_IOtCtCaB7RBykOwQfg8OJ5Thu2NpSjT7oYsINGc6c96o5OILv11BQnEH1KCWbQq1CBD4vgsrPx7J25hKWFF9287Ef5iaveACcRpi7_P_tcfS98GgHH5I5L10ZiRoQe1aNv")

registration_id = "cH3pt0ZYRxKE7KBw0VTS4j:APA91bFaoW4oYlNzWw0NdW4z0Q59EDdh2dfhjhPaFu-D4z_0D3i9ueVydTw8NSH3qS_9z_hSWHweWukNliIH2Iws1wg_TN0cRWf39R7SV0dCBzlXMJNWSsbMnfz_TwudIH-KcvjzINGU"

VAPID_CLAIMS = {
    "sub": "mailto:[email protected]"
}


def send_web_push_v2(subscription_information, message_body):
    return webpush(
        subscription_info=subscription_information,
        data=message_body,
        vapid_private_key='cLfnivpT-GEqRPEVgTimVEl66wQFOhZyk_WmbKMxKEI',
        vapid_claims=VAPID_CLAIMS
    )
示例#41
0
def notify():
    """ Notifications to the App via firebase server """
    dynamodb = boto3.resource('dynamodb', region_name='us-east-2')
    dynamoTables = dynamodb.Table('alerts')
    val = " "
    try:
        response = dynamoTables.get_item(
            Key={
                'coin_id': "tokenId"
            }
        )
        response_BTC = dynamoTables.get_item(
            Key={
                'coin_id': "BTC"
            }
        )
        response_LTC = dynamoTables.get_item(
            Key={
                'coin_id': "LTC"
            }
        )
        response_ETH = dynamoTables.get_item(
            Key={
                'coin_id': "ETH"
            }
        )
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        item = response['Item']
        item_btc = response_BTC['Item']
        item_eth = response_ETH['Item']
        item_ltc = response_LTC['Item']
        print("Get Item Succeeded")
        results = (json.dumps(item, indent=4, cls=DecimalEncoder)) 
        results_BTC = (json.dumps(item_btc, indent=4, cls=DecimalEncoder))
        results_ETH = (json.dumps(item_eth, indent=4, cls=DecimalEncoder))
        results_LTC = (json.dumps(item_ltc, indent=4, cls=DecimalEncoder)) 
        jsondata_charts = json.loads(results)
        jsondata_btc = json.loads(results_BTC)
        jsondata_eth = json.loads(results_ETH)
        jsondata_ltc = json.loads(results_LTC)
        token = jsondata_charts['token']
        items = [jsondata_btc, jsondata_ltc, jsondata_eth]
        for i in items:
            ticker = i['coin_id']
            if i['alert_below'] > check_for_break(ticker) and i['alert_below'] != 0:
                print("ALERT BELOW TRIGGERED")
                
                #For Demo / Grading purposes - Change to settings variable 
   
                push_service = FCMNotification(api_key="AAAAHsWsHB4:APA91bGfadwyPWvdbEZK7fAnYv-v2Z7zUxlQKi3nKA1ZGxGNx4hozTWfkMvyFcinayfcym2VG1pdRXDEHG5xUItUAKHmltZSVsvpDxafZqt8zeK9f6KGxdFVuESeZuHCv6bloCU0N-3s")
                registration_id = token
                message_title = ticker + " Price Reached"
                message_body = "Price Alert Triggered: " + ticker + " is below trigger price."
                result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)
                dynamoTables.put_item(
                        Item = {
                            'coin_id': ticker,
                            'alert_above': 0,
                            'alert_below': 0
                        }
                    )
                return result
            if i['alert_above'] < check_for_break(ticker) and i['alert_above'] != 0:
                print("ALERT ABOVE TRIGGERED")
                print(token)
                
                 #For Demo / Grading purposes - Change to settings variable 
                push_service = FCMNotification(api_key="AAAAHsWsHB4:APA91bGfadwyPWvdbEZK7fAnYv-v2Z7zUxlQKi3nKA1ZGxGNx4hozTWfkMvyFcinayfcym2VG1pdRXDEHG5xUItUAKHmltZSVsvpDxafZqt8zeK9f6KGxdFVuESeZuHCv6bloCU0N-3s")
                registration_id = token
                message_title = ticker + " Price Reached"
                message_body = "Price Alert Triggered: " + ticker + " is above trigger price."
                result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)
                dynamoTables.put_item(
                        Item = {
                            'coin_id': ticker,
                            'alert_above': 0,
                            'alert_below': 0
                        }
                    )
                return result
示例#42
0
sql = "select * from push where pushTime like "

time = ('%s:%s' % ((str(now.hour)).zfill(2), str(now.minute).zfill(2)))

time = "'" + time + "%'"

#sql =sql+time

#print(time)

sql = "select * from push where pushTime = '01:00:00'"
print(sql)

cursor.execute(sql)
result = cursor.fetchall()

userList = []
print(result)
for row_data in result:
    row_data = list(row_data)
    print(row_data)
    user = row_data[1]
    #api key 설정
    push_service = FCMNotification(api_key=conf["fcm"]["key"])

    #db에서 사용자 push_token 가져와야함
    result = push_service.notifiy_single_device(registration_id=push_tokens,
                                                message_title=message_title,
                                                message_body=message_body)
示例#43
0
                selectedOut = outings[i]
    else:
        minimumOut = None
        selectedOut = None
    if(selectedPain == input_selectedPain and selectedOut == input_selectedOut and isOuting == c_isOuting):
        return False
    else:
        return True



if __name__ == '__main__':
    us = UltrasonicClass.Ultrasonic() #method list : getDistance, Cleanup // this syntax is like " UltrasonicClass.UltraSonic us = new UltrasonicClass.Ultrasonic()" in JAVA
    sm = StepClass.StepMotor() #method list : step
    fcm = firebase.FirebaseApplication("https://ddoyak-362cb.firebaseio.com/",None) #fcm database object
    push_service = FCMNotification(api_key="AAAANJ-9vtU:APA91bGKUyUHMY0Rj32m9FhP4eFJTP-9xwFmSHjkTqJDmmDEmZL5tJOtJ2PvrAwL5jBErjs8uC9pjE8WRua1Iooakul7lACDwAvgYg8n5r3Jfix8Ggcw89KXVQ50UCgg-hCbPj7_uaddOsNd09fk4q-eWbt0sW2G7A")
    iteration = 0
    pygame.mixer.init()
    pygame.mixer.music.load("ifonger.mp3")
    
    mode = True # true:time check , false:distance check(whether user dose medicine)
    threshold = 7.1 # threshold of ultrasonic sensor value
    isOuting = False
    
    #Connect ID
    ids = fcm.get("/", None).keys()
    while True:
        sys.stdout.write("[SYSTEM] Input the patient ID : ")
        patient_id = raw_input()
        if(patient_id in ids):
            print("[SYSTEM] Account '"+patient_id+"' ' is connected! ")
 def init_push_service(self, api_key):
     self.push_service = FCMNotification(api_key=api_key)
示例#45
0
文件: fcm.py 项目: xtrinch/fcm-django
def fcm_send_message(
        registration_id,
        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_id (str): 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_single_device(
        registration_id=registration_id,
        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
示例#46
0
import os

# https://github.com/olucurious/PyFCM

from pyfcm import FCMNotification

api_key = os.environ.get('FCM_API_KEY'),
push_service = FCMNotification(api_key="api_key")


def send_messages(registration_ids: list,
                  title: str,
                  body: str,
                  dataDict: dict = None):
    result = push_service.notify_multiple_devices(
        registration_ids=registration_ids,
        message_title=title,
        message_body=body,
        data_message=dataDict)
    if result:
        if result['failure'] == 0:
            print(result)
    # TODO: Need to save result in log file also can trigger a mail to developer
示例#47
0
文件: test.py 项目: iamonuwa/PyFCM
#!/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 = "Hi john, your Uber driver is around"
result = push_service.notify_single_device(registration_id=registration_id, message_body=message)
print result
示例#48
0
from pyfcm import FCMNotification
from project.api.common.base_definitions import BaseFlask

# flask config
conf = Config(root_path=os.path.dirname(os.path.realpath(__file__)))
conf.from_object(os.getenv('APP_SETTINGS'))

# instantiate the extensions
db = SQLAlchemy()
migrate = Migrate()
bcrypt = Bcrypt()
mail = Mail()

sentry = None
twilio_client = Client(conf['TWILIO_ACCOUNT_SID'], conf['TWILIO_AUTH_TOKEN'])
push_service = FCMNotification(api_key=conf['FCM_SERVER_KEY'])


def create_app():
    # instantiate the app
    app = BaseFlask(__name__)

    # configure sentry
    if not app.debug and not app.testing:
        global sentry
        sentry = Sentry(app, dsn=app.config['SENTRY_DSN'])

    # set up extensions
    db.init_app(app)
    bcrypt.init_app(app)
    migrate.init_app(app, db)
示例#49
0
# To run this script use python fcmNotification.py or python *.py, where * is you file name
# This is python script to send fcm notification with payload or data
# I haved used documentation from  "https://github.com/olucurious/PyFCM"

from pyfcm import FCMNotification

push_service = FCMNotification(api_key="AIzaSyC41OgOOzW27O8Dt_ZvIqbA5Tt3PaVhyLw")

# Comment out below code for proxy server

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


# registration_ids = "," for multiple device notification
registration_id = "duev9DEuV-o:APA91bHJreL63jKVc99Jennbwl3tULi8u2DmCCJECUYc45p6sExMUqd_jJT02ObZSzCFBCyzSGeDrFIrEfd_mjpr0qykCeGe8F7lx9uMf-nQ3SXVbAQ9WJ-dXMa8YTma5tPbMGhd_kUL"

# message title and body is for notification title and body
message_title = "Adurcup"
message_body = "This is body of message"

# data_message is data payload load in our case JSON object
data_message = {
                  "current_service" : {
                    "address_line_one" : "Shivanta Road jaisa kuch address, Malviya Nagar",
                    "address_line_two" : "MALVIYA NAGAR, DELHI",
                    "area" : 1200,
                    "date" : "20 July 2016",
示例#50
0
 def clean_token(self):
     push_service = FCMNotification(api_key=self.env['ir.config_parameter'].sudo().get_param('mail_notify.fcm_server_key'))
     tokens = self.sudo().search([]).mapped('token')
     tokens = push_service.clean_registration_ids(tokens)
     self.sudo().search([('token', 'not in', tokens)]).unlink()