def hello(request): # run twisted if it is not running run_twisted() # get the token number = request.body.replace(" ", "") number = number.replace("<","") number = number.replace(">","") try: user = UserInfo.objects.get(name = number) except UserInfo.DoesNotExist: print 'not exists!' return HttpResponse("The user doesn't exist") else: token_hex = user.token aps = {'aps': { 'sound': 'default', 'badge': 1, 'message': 'Hello from Qianli :)'} } configure({'HOST': 'http://localhost:7077/'}) provision('lg2013', open('/usr/share/nginx/www/qianli/apns-dev.pem').read(), 'sandbox') notify('lg2013', token_hex, aps) tmr = TimerClass() tmr.start() html = "<html>send notification</html>" return HttpResponse(html)
def request_feedback(): if not pyapns.client.OPTIONS['CONFIGURED']: log.info('configuration on the fly') configure({'HOST': 'http://localhost:7077/'}) with open(os.path.abspath(config_file)) as f: config = pyapns._json.loads(f.read()) for app in config['autoprovision']: app_id = app['app_id'] log.info("requesting feeback for %s" % app_id) pyapns.feedback(app_id, async=False, callback=got_feedback, errback=got_error)
def __init__(self, **data): super(APN, self).__init__(**data) self.badge = data['badge'] try: self.message_data = data['message_data'] except KeyError: self.message_data = False configure(data['config']['PYAPNS']) provision(self.config['provision'], open( self.config['certfile']).read(), self.config['environment'])
def __init__(self, user_id): configure(PyAPNS_Server) self.user_id = user_id self.notifications = { 'aps': { 'alert': None, 'sound': 'default', 'badge': 1, } }
def write_message(request): if request.method == 'POST': other_user_id = request.POST['other_user_id'] user_id = request.POST['user_id'] content = request.POST['content'] seller = int(request.POST['seller']) if seller == 0: unseller = 1 else: unseller = 0 other_user = User.objects.get(id=other_user_id) user = User.objects.get(id=user_id) try: chatRoom = ChatRoom.objects.get(user=user, other_user=other_user, seller=seller) except: chatRoom = ChatRoom.objects.create(user=user, other_user=other_user, seller=seller) try: other_chatRoom = ChatRoom.objects.get(user=other_user, other_user=user, seller=unseller) except: other_chatRoom = ChatRoom.objects.create(user=other_user, other_user=user, seller=unseller) if seller == 1: Message.objects.create(seller_chatRoom=chatRoom, buyer_chatRoom=other_chatRoom, content=content, seller=1) else: Message.objects.create(seller_chatRoom=other_chatRoom, buyer_chatRoom=chatRoom, content=content, seller=0) chatRoom.message_count = 0 chatRoom.last_message = content other_chatRoom.message_count += 1 other_chatRoom.last_message = content chatRoom.save() other_chatRoom.save() if other_user.profile.device_type == 1: pushMessage = user.first_name + ':' + content configure({'HOST': 'http://localhost:7077/'}) provision('univer', open('/home/projects/univer/univ/APNSWrapper/ck.pem').read(), 'sandbox') notify('univer', other_user.profile.deviceToken, {'aps':{'alert': pushMessage, 'badge': 10, 'sound': 'flynn.caf'}}) return HttpResponse(str(chatRoom.id)) elif other_user.profile.device_type == 2: return HttpRespose('android') elif other_user.profile.device_type == 3: return HttpResponse('blackberry') elif request.method == 'PUT': return HttpResponse('put 요청입니다') elif request.method == 'DELETE': return HttpResponse('DELETE 요청입니다.') elif request.method == 'GET': return HttpResponse('get요청입니다.')
def send_notif(message="", silent=True, event_id=None): configure({'HOST': 'http://localhost:7077/'}) provision('BeTherePush', os.environ["PEMPEM"], 'sandbox') if silent: if event_id: notify('BeTherePush', token_hex, { 'aps': { 'content-available': '1' }, 'event_id': event_id }) else: notify('BeTherePush', token_hex, {'aps': { 'content-available': '1' }}) else: notify('BeTherePush', token_hex, {'aps': {'alert': message}})
def send_notification(token, aps): """ 向目标手机发送通知: token - 目标手机的token aps - 通知的payload,包括显示数字和内容等 """ run_twisted() configure({'HOST': 'http://localhost:7077/'}) # provision('lg2013', open('/usr/share/nginx/www/qianli/apns-dev.pem').read(), 'sandbox') # notify('lg2013', token, aps) # provision('com.ashstudio.qianli', open('/usr/share/nginx/www/qianli/development.pem').read(), 'sandbox') # provision('com.ashstudio.qianli', open('/usr/share/nginx/www/qianli/apns-dev.pem').read(), 'sandbox') # 有且只能provision一次!!!如果有相同的app id, 第二次将视为无效 provision('com.ashstudio.qianli', open('/usr/share/nginx/www/qianli/apns-pro.pem').read(), 'production') provision('com.development.qianli', open('/usr/share/nginx/www/qianli/apns-dev.pem').read(), 'sandbox') notify('com.ashstudio.qianli', token, aps) notify('com.development.qianli', token, aps) # provision('com.ashstudio.qianliAdhocDistribution', open('/usr/share/nginx/www/qianli/apns-pro.pem').read(), 'production') # notify('com.ashstudio.qianliAdhocDistribution', token, aps) logger = logging.getLogger(__name__) logger.debug("send notification LG") try: feedbacktime = LastFeedback.objects.get(name = 'APNS') except LastFeedback.DoesNotExist: feedbacktime = LastFeedback(name = 'APNS', lastfeedback = datetime.datetime.now()) feedbacktime.save() da=datetime.datetime.now() daydelta=da.day-feedbacktime.lastfeedback.day hourdelta=da.hour-feedbacktime.lastfeedback.hour secondsdelta = daydelta * 86400 + hourdelta * 3600 if secondsdelta>86400: logger = logging.getLogger(__name__) logger.debug("execute feedback service") feedbacktime.lastfeedback = datetime.datetime.now() feedbacktime.save() feedback('com.ashstudio.qianli', async=True, callback=got_feedback)
def push(app_id, message=None, badge=0, sound=None, custom=None): # FIXME: init service and push merged in one function - bad! #init_twisted() log.warn('auto-init of service currently not realiable; use manual start!') with open(os.path.abspath(config_file)) as f: config = pyapns._json.loads(f.read()) ## configure on the fly if not pyapns.client.OPTIONS['CONFIGURED']: log.info('configuration on the fly') configure({'HOST': 'http://localhost:7077/'}) if 'autoprovision' in config: for app in config['autoprovision']: if app['app_id'] == app_id: log.info('found configuration for %s' % app_id) assert os.path.exists(app['cert']) is True, "no file found at %s" % app['cert'] provision(app['app_id'], open(app['cert']).read(), app['environment']) ## create notification notification = {'aps':{}} if message: notification['aps'].update({'alert': message}) if badge: notification['aps'].update({'badge': int(badge)}) if sound: notification['aps'].update({'sound': sound}) if custom: for key in custom: notification.update({key:custom[key]}) log.debug('[%s] %d token; notification:\n%s\n' % (app_id, len(config['tokens']), notification)) # notifications = [] # for token in config['tokens']: # notifications.append(notification) notify(app_id, config['tokens'], notification, async=False)
def messages(request): if request.method == 'POST': postString = str(request.POST).encode("utf-8") # a = json.loads(request.POST) # return HttpResponse(a) firstCutString = postString[15:] reversedString = ''.join(reversed(firstCutString)) secondCutString = reversedString[10:] secondReversedString = ''.join(reversed(secondCutString)) data = json.loads(secondReversedString) other_user_id = data['other_user_id'] user_id = data['user_id'] content = data['content'] sellerString = data['seller'] # other_user_id = request.POST['other_user_id'] # user_id = request.POST['user_id'] # content = request.POST['content'] # seller = request.POST['seller'] if sellerString == '1': seller = True unseller = False else: seller = False unseller = True other_user = User.objects.get(id=other_user_id) user = User.objects.get(id=user_id) try: chatRoom = ChatRoom.objects.get(user=user, other_user=other_user, seller=seller) except: chatRoom = ChatRoom.objects.create(user=user, other_user=other_user, seller=seller) try: other_chatRoom = ChatRoom.objects.get(user=other_user, other_user=user, seller=unseller) except: other_chatRoom = ChatRoom.objects.create(user=other_user, other_user=user, seller=unseller) if seller == 1: Message.objects.create(seller_chatRoom=chatRoom, buyer_chatRoom=other_chatRoom, content=content, seller=1) else: Message.objects.create(seller_chatRoom=other_chatRoom, buyer_chatRoom=chatRoom, content=content, seller=0) chatRoom.message_count = 0 chatRoom.last_message = content other_chatRoom.message_count += 1 other_chatRoom.last_message = content chatRoom.save() other_chatRoom.save() pushMessage = user.first_name + ':' + content if other_user.profile.device_type == 1: configure({'HOST': 'http://localhost:7077/'}) provision('univer', open('/home/projects/univer/univ/APNSWrapper/ck.pem').read(), 'sandbox') notify('univer', other_user.profile.deviceToken, {'aps':{'alert': pushMessage, 'badge': 10, 'sound': 'flynn.caf'}}) return HttpResponse(str(chatRoom.id)) elif other_user.profile.device_type == 2: API_KEY = 'AIzaSyBIoZYJ1mOKB8x32svoYCqCSeS4yEhxbQM' gcm = GCM(API_KEY) # uni_title = user.first_name.decode('utf-8') uni_content = content.encode('utf-8') uni_name = user.first_name.encode('utf-8') ticker = uni_name + ':' + uni_content # return HttpResponse(type(uni_content)) # ticker = user.first_name+':'+uni_content # return HttpResponse(type(ticker)) data = {'title': uni_name, 'content': uni_content, 'ticker': ticker} # Plaintext request reg_id = other_user.profile.deviceToken gcm.plaintext_request(registration_id=reg_id, data=data) # JSON request # reg_ids = [reg_id] # response = gcm.json_request(registration_ids=reg_ids, data=data) return HttpResponse('200') elif other_user.profile.device_type == 3: return HttpResponse('blackberry') elif request.method == 'PUT': return HttpResponse('put 요청입니다') elif request.method == 'DELETE': return HttpResponse('DELETE 요청입니다.') elif request.method == 'GET': return HttpResponse('get요청입니다.')
# This script should be scheduled to execute periodically to send push notifications to clients from pyapns import configure, provision, notify, feedback import MySQLdb configure({'HOST': 'http://localhost:7077/'}) provision('tqt', open('KutuProduction.pem').read(), 'production') # Get all the active deviceIDs db = MySQLdb.connect(db="TONGQUETAI", user="******", passwd="123456", charset="utf8"); cursor = db.cursor(); query = "select id, token from Device where isActive=TRUE"; cursor.execute(query); devices = cursor.fetchall(); for device in devices: deviceToken = device[1]; deviceID = device[0]; # Query the messages for this device unReadQuery = "select count(*) from Message where deviceID=%s and isRead=FALSE"%deviceID; cursor.execute(unReadQuery); result = cursor.fetchone(); unRead = int(result[0]); if unRead==0: continue; # Send the most recent unsent message msgQuery = "select id,messageText from Message where deviceID=%s and isSent=FALSE ORDER BY createdOn DESC"%(deviceID); cursor.execute(msgQuery); msgs = cursor.fetchall(); if not msgs: #Only send badge numbers
def write_message(request): if request.method == 'POST': other_user_id = request.POST['other_user_id'] user_id = request.POST['user_id'] content = request.POST['content'] seller = int(request.POST['seller']) if seller == 0: unseller = 1 else: unseller = 0 other_user = User.objects.get(id=other_user_id) user = User.objects.get(id=user_id) try: chatRoom = ChatRoom.objects.get(user=user, other_user=other_user, seller=seller) except: chatRoom = ChatRoom.objects.create(user=user, other_user=other_user, seller=seller) try: other_chatRoom = ChatRoom.objects.get(user=other_user, other_user=user, seller=unseller) except: other_chatRoom = ChatRoom.objects.create(user=other_user, other_user=user, seller=unseller) if seller == 1: Message.objects.create(seller_chatRoom=chatRoom, buyer_chatRoom=other_chatRoom, content=content, seller=1) else: Message.objects.create(seller_chatRoom=other_chatRoom, buyer_chatRoom=chatRoom, content=content, seller=0) chatRoom.message_count = 0 chatRoom.last_message = content other_chatRoom.message_count += 1 other_chatRoom.last_message = content chatRoom.save() other_chatRoom.save() if other_user.profile.device_type == 1: pushMessage = user.first_name + ':' + content configure({'HOST': 'http://localhost:7077/'}) provision( 'univer', open('/home/projects/univer/univ/APNSWrapper/ck.pem').read(), 'sandbox') notify('univer', other_user.profile.deviceToken, { 'aps': { 'alert': pushMessage, 'badge': 10, 'sound': 'flynn.caf' } }) return HttpResponse(str(chatRoom.id)) elif other_user.profile.device_type == 2: return HttpRespose('android') elif other_user.profile.device_type == 3: return HttpResponse('blackberry') elif request.method == 'PUT': return HttpResponse('put 요청입니다') elif request.method == 'DELETE': return HttpResponse('DELETE 요청입니다.') elif request.method == 'GET': return HttpResponse('get요청입니다.')
def messages(request): if request.method == 'POST': postString = str(request.POST).encode("utf-8") # a = json.loads(request.POST) # return HttpResponse(a) firstCutString = postString[15:] reversedString = ''.join(reversed(firstCutString)) secondCutString = reversedString[10:] secondReversedString = ''.join(reversed(secondCutString)) data = json.loads(secondReversedString) other_user_id = data['other_user_id'] user_id = data['user_id'] content = data['content'] sellerString = data['seller'] # other_user_id = request.POST['other_user_id'] # user_id = request.POST['user_id'] # content = request.POST['content'] # seller = request.POST['seller'] if sellerString == '1': seller = True unseller = False else: seller = False unseller = True other_user = User.objects.get(id=other_user_id) user = User.objects.get(id=user_id) try: chatRoom = ChatRoom.objects.get(user=user, other_user=other_user, seller=seller) except: chatRoom = ChatRoom.objects.create(user=user, other_user=other_user, seller=seller) try: other_chatRoom = ChatRoom.objects.get(user=other_user, other_user=user, seller=unseller) except: other_chatRoom = ChatRoom.objects.create(user=other_user, other_user=user, seller=unseller) if seller == 1: Message.objects.create(seller_chatRoom=chatRoom, buyer_chatRoom=other_chatRoom, content=content, seller=1) else: Message.objects.create(seller_chatRoom=other_chatRoom, buyer_chatRoom=chatRoom, content=content, seller=0) chatRoom.message_count = 0 chatRoom.last_message = content other_chatRoom.message_count += 1 other_chatRoom.last_message = content chatRoom.save() other_chatRoom.save() pushMessage = user.first_name + ':' + content if other_user.profile.device_type == 1: configure({'HOST': 'http://localhost:7077/'}) provision( 'univer', open('/home/projects/univer/univ/APNSWrapper/ck.pem').read(), 'sandbox') notify('univer', other_user.profile.deviceToken, { 'aps': { 'alert': pushMessage, 'badge': 10, 'sound': 'flynn.caf' } }) return HttpResponse(str(chatRoom.id)) elif other_user.profile.device_type == 2: API_KEY = 'AIzaSyBIoZYJ1mOKB8x32svoYCqCSeS4yEhxbQM' gcm = GCM(API_KEY) # uni_title = user.first_name.decode('utf-8') uni_content = content.encode('utf-8') uni_name = user.first_name.encode('utf-8') ticker = uni_name + ':' + uni_content # return HttpResponse(type(uni_content)) # ticker = user.first_name+':'+uni_content # return HttpResponse(type(ticker)) data = { 'title': uni_name, 'content': uni_content, 'ticker': ticker } # Plaintext request reg_id = other_user.profile.deviceToken gcm.plaintext_request(registration_id=reg_id, data=data) # JSON request # reg_ids = [reg_id] # response = gcm.json_request(registration_ids=reg_ids, data=data) return HttpResponse('200') elif other_user.profile.device_type == 3: return HttpResponse('blackberry') elif request.method == 'PUT': return HttpResponse('put 요청입니다') elif request.method == 'DELETE': return HttpResponse('DELETE 요청입니다.') elif request.method == 'GET': return HttpResponse('get요청입니다.')
#!/usr/bin/python
from pyapns import configure, provision, notify, feedback configure({'HOST': 'http://localhost:7077/'}) #provision('com.beta.wizcard', open('/Users/aammundi/projects/git/wizcard-server/certs/wizcard_ios_apns_production.pem').read(), 'production') provision('com.beta.wizcard', open('./certs/wizcard_ios_apns_production.pem').read(), 'production') #provision('com.beta.wizcard', open('/Users/aammundi/projects/git/wizcard-server/certs/wizcard_ios_apns_dev.pem').read(), 'sandbox') #notify('com.beta.wizcard', '5f660dfacba5f8222946811724e012e2a6887460768083b39277d7e259b1675e', {'aps':{'alert':'Hello!'}}) #notify('com.beta.wizcard', '6c4f3dcb31cb45bdaf399206ea065b9795bee698cd56a60bcd40ee336741d4dd', {'aps':{'alert':'Hello!'}}) notify('com.beta.wizcard', '6c4f3dcb31cb45bdaf399206ea065b9795bee698cd56a60bcd40ee336741d4dd', {'aps': { 'alert': 'senthil, test apns notif!' }})
def initEnv(): configure({'HOST': 'http://localhost:7077/'}) provision('iPhoneQQ', open('ck_dev.pem').read(), 'sandbox') feedback('iPhoneQQ', async=True, callback=got_feedback)
def __init__(self, host, app_id, apns_certificate_file, mode="sandbox"): self.app_id = app_id pyapns.configure({"HOST": host}) pyapns.provision(app_id, open(path.join(RESOURCES_DIRECTORY, apns_certificate_file)).read(), mode)
def __init__(self, host, app_id, apns_certificate_file, mode=APNS_ENVIRONMENT): self.app_id = app_id pyapns.configure({'HOST': host}) pyapns.provision(app_id, open(apns_certificate_file).read(), mode)