def get_gcm(): if not hasattr(threadlocal, "gcm"): settings = get_settings() # JSON request API_KEY = os.environ.get("GCM_API_KEY", settings.get("gcm.api_key")) threadlocal.gcm = GCM(API_KEY) return threadlocal.gcm
def send_notification(app_id): api_key = "AIzaSyBzAFQ19gB3BctG6VL8lO85VWf8I-vD_Gs" gcm = GCM(api_key) data = {'title': 'Notify', 'extra': "Welcome to Arduino"} print(data) response = gcm.json_request(registration_ids=[app_id], data=data) return response
def __init__(self, config, log): Sender.__init__(self, config, log) self.access_key = config.get('Messenger', 'gcm_access_key') self.base_deeplink_url = config.get('Messenger', 'base_deeplink_url') self.gcm = GCM(self.access_key) self.canonical_ids = [] self.unregistered_devices = []
def __init__(self, *args, **kwargs): _config = BOOTSTRAP_CONFIG.get("gcm") _api_key = _config.get("api_key") self.gcm = GCM(_api_key) self.push_handler = PushHandler(self) self.redis = redis.Redis(REDIS_HOST, REDIS_PORT, db=1) return
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabZones` where (zone_name='%s' or zone_code='%s') and region='%s'"%(doc.zone_name,doc.zone_code,doc.region)) if res: frappe.throw(_("Zone '{0}' already created with same Zone Name '{1}' or Zone Code '{2}' for Region '{3}'..!").format(res[0][0],doc.zone_name,doc.zone_code,doc.region)) notify_msg = """Dear User,\n\n Zone is created with name '%s' for region '%s'.\n\nRegards,\n\n Love World Synergy"""%(doc.zone_name,doc.region) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if notify: if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Zone Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) ofc = frappe.new_doc("Offices") ofc.office_id = doc.name ofc.office_name = doc.zone_name ofc.office_code = doc.zone_code ofc.insert()
def _send_gcm_to_token(token_key, message): logging.info("Executing deferred task: _send_gcm_to_token, %s, %s" % (token_key, message)) token = dao.get_gcm_token_for_key(token_key) gcm = GCM(dao, sys.modules[__name__]) gcm.send_gcm([token], message)
def askForReplace(self, request, pk=None): queryset = Appointment.objects.get(id=pk) gcm = GCM("AIzaSyCEimvyhdLB38RIIOTITtZ6JwttrWO07JU") data = { 'message': 'Horario vago do dia ' + str(queryset.line.date) + ' as ' + str(queryset.time) + ' com o ' + queryset.line.medic.name + ' na clinica ' + queryset.line.clinic.name + '.', 'year': str(queryset.line.date.year), 'month': str(queryset.line.date.month), 'day': str(queryset.line.date.day), 'time': str(queryset.time), 'clinic': str(queryset.line.clinic.id), 'medic': str(queryset.line.medic.id) } reg_id = 'APA91bF0k32Tyqlhiy9DxfNO7B-6eKNSilMGtfKaehOQ3XV-suYwdwK-3meSTTlCKxUCc5U2B8eAGv5S9bbnAOLe5ww_eqmVyAm5fqVwYyy_dmZCQRRK9veZkZ22K6-Dsj9WNI2LTFeZ6OcwfsQ3NfSh4WyJ8S2tBQ' gcm.plaintext_request(registration_id=reg_id, data=data) queryset2 = Appointment.objects.filter(line__id=queryset.line.id, check=False, patient__isnull=False) for e in queryset2: reg_id = e.patient.gcm_id if reg_id is not None and not reg_id == "": gcm.plaintext_request(registration_id=reg_id, data=data) queryset.delete() return json_response({'message': 'deleted succefully'})
def processGCMRequest(): apiKey = "AIzaSyDTJukW0BARTSXHRiWPCt8y_e17A9PuYfg" gcm = GCM(apiKey) data = request.json notificationTitle = data['notificationTitle'] notificationBody = data['notificationBody'] tags = data['tags'] allSubscriptions = Subscriptions.objects.all() regIdList = [] for subscription in allSubscriptions: if (len(set(tags).intersection(set(subscription.subscriptionList))) and subscription.pushAllowed == "true"): regIdList.append(subscription.registrationId) if (len(regIdList) != 0): newNotification = Notifications() newNotification.notificationTitle = notificationTitle newNotification.notificationBody = notificationBody newNotification.registrationIds = regIdList newNotification.save() response = gcm.json_request(registration_ids=regIdList, data=data) return jsonify({ "notification_title": notificationTitle, "notification_text": notificationBody })
def send_GCM_notification(token, data): logger.debug("Sending GCM Notification to [%s]..." % token) try: gcm = GCM(settings.GCM_API_KEY) # Plaintext request #response = gcm.plaintext_request( registration_id=token, collapse_key='Updated Steps', data=data, time_to_live=86400 ) <-- currently broken in library response = gcm.plaintext_request(registration_id=token, data=data) logger.debug("Sent Push to: [%s] sent: %s" % (token, response)) return "Success" except GCMNotRegisteredException: logger.error("Token [%s] Not Registered!" % token) return "NotRegistered" except GCMMismatchSenderIdException: logger.error("Token [%s] Bad Sender error" % token) return "Mismatch" except GCMUnavailableException: logger.error("Failed for [%s]... try again" % token) return "Unavailable" except: LogTraceback() return "Error"
def make_request(self, api_key, message): gcm = GCM(api_key) response = gcm.json_request(**message.content) invalid_reg_ids = 0 # Handling errors if 'errors' in response: for error, reg_ids in response['errors'].items(): # Check for errors and act accordingly if error in ['NotRegistered', 'InvalidRegistration']: invalid_reg_ids += GCMDevice.objects.filter( registration_id__in=reg_ids).update(is_active=False) if 'canonical' in response: for reg_id, canonical_id in response['canonical'].items(): # Replace reg_id with canonical_id GCMDevice.objects.filter(registration_id=reg_id).update( registration_id=canonical_id) status = GCMMessage.STATUSES.DELIVERED if len(message.content['registration_ids']) == invalid_reg_ids: status = GCMMessage.STATUSES.ERROR elif invalid_reg_ids > 0: status = GCMMessage.STATUSES.PARTIALLY_DELIVERED return status, response
def makeDecision(request): logger.debug(request.body) json_data = json.loads(request.body) user_id = json_data["user_id"] options = json_data["options"] asked_to = json_data["asked_to"] asked_by_user = User.objects.get(id=user_id) question = Question(statement=json_data["question"], date_time_asked=datetime.datetime.now(), asked_by=asked_by_user) question.save() self_vote = Vote(user_id=asked_by_user, question=question) self_vote.save() for i in options: option = Option(name=i, quest_id=question.id) option.save() question.options.add(option) gcm_ids = [] for i in asked_to: user = User.objects.get(phone=i) vote = Vote(user_id=user, question=question) vote.save() gcm_ids.append(user.gcm_id) gcm = GCM(settings.GCM_API_KEY) data = {"action": "Requesting your Opinion"} gcm_status = gcm.json_request(registration_ids=gcm_ids, data=data) logger.debug(gcm_status) serializer = QuestionSerializer(question, context={'user_id': user_id}) return JSONResponse(serializer.data)
def send_push(token, data): try: gcm = GCM(constants.GCM_PUSH_API_KEY) response = gcm.json_request(registration_ids=[token], data=data) except Exception, e: print e pass
def sendMessageGcmtest(registration_ids,message): '''url="https://android.googleapis.com/gcm/send" headers = {'Authorization': 'key='+gcm["GOOGLE_API_KEY"], 'Content-Type':'application/json'} payload = {'registration_ids': registration_ids, 'data': message} r = requests.post(url, data, headers=headers) print json.dumps(payload) print r''' results="" reg="" gcm = GCM(gcm_api["GOOGLE_API_KEY"]) data = {'warning': message} condition_gcm="SELECT gcm_regid FROM gcm_users" try: cursor.execute(condition_gcm) results = cursor.fetchall() #reg=results[0][0] for reg in results: reg=[reg[0]] response = gcm.json_request(registration_ids=reg, data=data) print response reg #print results except: print "error" reg=[reg] print reg
def __init__(self, debug=None): setup = AllSetup() self.push_debug = setup.push_debug self.host = setup.host self.port = setup.port self.user = setup.user self.passwd = setup.passwd self.db = setup.db self.gcm_api_key = setup.gcm_api_key self.auth = "" self.gcm = None self.push = None try: self.conn = self.getConnection() self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor) if (debug == 1): self.update_check('on') self.must_goon() self.gcm = GCM(self.gcm_api_key) self.push = PushData() self.push.readData(setup.push_file) except MySQLdb.Error, e: print "Error 1 %d: %s" % (e.args[0], e.args[1]) self.closeAll() sys.exit(1)
def push_to_user(user, sender, type): data = { 'type': type, 'target_jid': user.key().name(), 'nudger': sender.first_name, 'toFn': user.first_name, 'toLn': user.last_name } gcm = GCM(API_KEY) response = gcm.json_request(registration_ids=user.gcm_registration_ids, data=data) # Handling errors if 'errors' in response: for error, reg_ids in response['errors'].items(): # Check for errors and act accordingly if error is 'NotRegistered': # Remove reg_ids from database for reg_id in reg_ids: user.gcm_registration_ids.remove(reg_id) user.put() if 'canonical' in response: for reg_id, canonical_id in response['canonical'].items(): # Repace reg_id with canonical_id in your database user.gcm_registration_ids.remove(reg_id) user.gcm_registration_ids.append(canonical_id) user.put()
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabCells` where cell_name='%s' and cell_code='%s' and senior_cell='%s'"%(doc.cell_name,doc.cell_code,doc.senior_cell)) if res: frappe.throw(_("Another Cell '{0}' With Cell Name '{1}' and Cell Code '{2}' exist in Senior Cell '{3}'..!").format(res[0][0],doc.cell_name,doc.cell_code,doc.senior_cell)) notify_msg = """Dear User,\n Region is created with name '%s' for Senior Cell '%s' \n \n Regards,\n Love World Synergy"""%(doc.cell_name,doc.senior_cell) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Region Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) frappe.errprint(res1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600)
def push_message(username, token, pk): print(token, pk) gcm = GCM(GCM_APIKEY) gcm.plaintext_request(registration_id=token, data={}, collapse_key='new', time_to_live=TIME_TO_LIVE)
def checkDataAndNotify(): profiles = Profile.objects.all() data = {} currentTime = time.time() recentTime = currentTime - 24 * 3600 for profile in profiles: dbName = "User_" + str(profile.id) collection = connection[dbName]["funf"] newNotifications = False recentEntries = collection.find({"time": {"$gte": recentTime}}) if (recentEntries.count() == 0): addNotification( profile, 1, "Stale behavioral data", "Analysis may not accurately reflect your behavior.", None) newNotifications = True #addNotification(profile, 2, "Survey", "Take this survey", "/survey/?survey=1"); #newNotifications = True if (newNotifications and Device.objects.filter(datastore_owner=profile).count() > 0): gcm = GCM(settings.GCM_API_KEY) #addNotification(profile, 2, "Push successful", "Push notifications are working properly.") for device in Device.objects.filter(datastore_owner=profile): #pdb.set_trace() gcm.plaintext_request(registration_id=device.gcm_reg_id, data={"action": "notify"})
def sendGCMNotification(registrationTokenList, message): gcm = GCM(GCM_API_KEY) #print 'send message to gcm registration ids ' + ', '.join(registrationTokenList) retVal = gcm.json_request(registration_ids=registrationTokenList, data={"message": message}, delay_while_idle=False) return retVal
def __init__(self, _app): self.application = _app _config = BOOTSTRAP_DATA.get("gcm") _api_key = _config.get("api_key") self.gcm = None if _api_key != None: self.gcm = GCM(_api_key) return
def notify_one_user(token, msg): gcm = GCM(GCM_KEY) data = {'update': msg} gcm_push_response = gcm.json_request(registration_ids=[token], data=data) if bool(gcm_push_response): print token[:20] + " is invalid or outdated" else: print "Sent " + msg + " to " + token[:20]
def push_payload(payload): """ Pushes a payload through the proper broker to the current device instance. Payload should be structured like: { "metadata": { "received_at": <unix ts>, "pushed_at": <unix ts>, "from_id": "<device uuid>" }, "payload": "<aes256 salted, encrypted JSON payload>", "signature": "<salted HMAC-SHA1 payload>" } Supported brokers: - Google Cloud Messaging (through `python-gcm`) :param dict payload: Dictionary of push payload. :rtype: None :returns: None """ if not self.target_id: raise ValueError("No target id has been set") config = manager.get_instance().config gcm_conf = config.get_section('gcm') g = None try: g = GCM(gcm_conf.get_string('api_key', None)) except (Exception e): raise e resp = g.json_request( registration_ids=self.target_id, data=payload, delay_while_idle=True, time_to_live=3600 ) if resp and 'success' in resp: for devid, succid in resp['success'].items(): LOG.info('Pushed payload to device %s' % (devid)) if 'errors' in resp: for err, devids in resp['errors'].items(): if err in ['NotRegistered', 'InvalidRegistration']: for devid in devids: print('Invalid device id: %s' % (devid)) if 'canonical' in resp: for devid, canonical_id in resp['canonical'].items(): d = Device.get(target_id=devid) d.target_id = canonical_id d.save()
def notify_user(destination_user, message): gcm = GCM(GCM_API_KEY) reg_id = [destination_user.gcm_id] data = {'message': message} print('Notification sent to test account, destination=' + destination_user.email + ', message=' + message) if destination_user.gcm_id != 'TESTACCOUNT': response = gcm.json_request(registration_ids=reg_id, data=data)
def _Start(): assert options.options.id and options.options.data_key and options.options.data_value api_key = secrets.GetSecret(API_KEY_NAME) print 'API key: %s' % api_key g = GCM(api_key) data = {options.options.data_key: options.options.data_value} # Do not catch any of the exceptions for now, we'd like to see them. g.plaintext_request(registration_id=options.options.id, data=data)
def push(): global API_KEY gcm = GCM(API_KEY) data = {'param1': 'value1', 'param2': 'value2'} # Downstream message using JSON request global registrationIds reg_ids = registrationIds response = gcm.json_request(registration_ids=reg_ids, data=data) return "pushed :-)"
def send_push_mesage(msg, the_time): logging.getLogger('BoilerLogger').debug('sending boiler sms message: %s' % msg) gcm = GCM(PUSH_NOTIFICATION_API_KEY) data = {'message': msg, 'time': str(the_time)} topic = 'global' try: gcm.send_topic_message(topic=topic, data=data) except: logging.getLogger('BoilerLogger').debug( 'can not send push message, ignore.')
def push_send(push_id, push_type): # push_type = 0,1 # 0 : 즉시발송 # 1 : 푸쉬삭제 API_KEY = 'AIzaSyByl17d2XCjWqZy4Wa7RaWmlsbkB1bGfHs' reg_ids = [] # 푸시 보낼 사용자 선택. members = Member.objects.filter(push_acceptable=True) response = 'member is 0' if len(members) > 0: for member in members: reg_ids.append(member.push_id) # 푸시에 사용될 메시지 가져오기. push = Push.objects.filter(id=push_id) if len(push) > 0: push = Push.objects.get(id=push_id) # 푸시 메시지 생성. gcm = GCM(API_KEY) date = str(push.activated_date_time).replace(" ", "-").replace(":", "-") date = date[:date.find('.')] data = { 'subject': 'Funing', 'contents': push.contents, 'date': date, 'id': push_id, 'type': int(push_type) } # 푸시 보내기. response = gcm.json_request(registration_ids=reg_ids, data=data) # 푸시 에러 핸들링. if 'errors' in response: for error, reg_ids in response['errors'].items(): # Check for errors and act accordingly if error is 'NotRegistered': # Remove reg_ids from database for reg_id in reg_ids: # print reg_id Member.objects.get(push_id=reg_id).delete() if 'canonical' in response: for canonical_id, reg_id in response['canonical'].items(): # print 'canonical_id : %s' % canonical_id # print 'reg_id : %s' % reg_id # Repace reg_id with canonical_id in your database member = Member.objects.get(push_id=canonical_id) member.push_id = reg_id member.save() return response
def send_push_gcm(token, content): google_api_key = "AAAAgGY9xAc:APA91bFwKXq9w7sB6EKzNGvIKInrc8VF8TRu3SInUM1zbisRmSX9gnlMcWFam4uIMoeAv0CGhNlwrEHvEI7htSbg6-2YHQ2hIgD0agKF95GZ_tEduz4pTDSJiQj2tpZ10hGPPLapIEvm" gcm = GCM(google_api_key) data = {'message': content, 'title': 'Chibe'} try: gcm.plaintext_request(registration_id=token, data=data) except: PushNotification.objects.filter(token=token).delete() pass
def sendNotification(gcm_id, data, type): gcm_obj = GCM(API_KEY) try: response = gcm_obj.plaintext_request(registration_id=gcm_id, data=data) return response except gcm.gcm.GCMInvalidRegistrationException: return {'error': 'gcm.gcm.GCMInvalidRegistrationException'} except gcm.gcm.GCMNotRegisteredException: return {'error': 'gcm.gcm.GCMNotRegisteredException'} except: return {'error': 'oooops'}
def remove_key_data(gcm_iid): # Send request to phone to delete revoked private key gcm = GCM(cfg.config.gcm_api_key) data = {"action": "revoke"} # Check if there were errors and retry if needed response = gcm.json_request(registration_ids=[gcm_iid], data=data) if 'errors' in response: remove_key_data.retry( args=[gcm_iid], countdown=cfg.config.celery.remove_key_data.timeout )