示例#1
0
    def push(self):
        user_apns = User_Apns.objects.filter(user=self.user_id)

        for apns in user_apns:
            #            if settings.DEBUG:
            #                if 'iPad' in apns.device.dev_name:
            #                    APNS_KEY = self.guoku_apns_dir + 'iPadCAPCK.sandbox.pem'
            #                    provision('com.guoku', open(APNS_KEY).read(), 'sandbox')
            #                else:
            #                    APNS_KEY = self.guoku_apns_dir + 'guokuCK.sandbox.pem'
            #                    provision('com.guoku.iphone', open(APNS_KEY).read(), 'sandbox')
            #            else:
            if apns.device.app_version == '3000':
                if 'iPad' in apns.device.dev_name:
                    APNS_KEY = self.guoku_apns_dir + 'iPadCAPCK.pem'
                    provision('com.guoku', open(APNS_KEY).read(), 'sandbox')
                else:
                    APNS_KEY = self.guoku_apns_dir + 'guokuCK.pem'
                    provision('com.guoku.iphone',
                              open(APNS_KEY).read(), 'production')
                if 'iPad' in apns.device.dev_name:
                    notify('com.guoku', apns.device.dev_token,
                           self.notifications)
                else:
                    notify('com.guoku.iphone', apns.device.dev_token,
                           self.notifications)
示例#2
0
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)
示例#3
0
 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'])
示例#4
0
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요청입니다.')
示例#5
0
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}})
示例#6
0
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)
示例#7
0
文件: spring.py 项目: whiskey/spring
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)
示例#8
0
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요청입니다.')
示例#9
0
# 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
示例#10
0
 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)
示例#11
0
文件: python.py 项目: erhuok/yamler
from pyapns import configure, provision, notify
configure({'HOST': 'http://localhost:7077/'})
provision('justoa', open('cert.pem').read(), 'production')
s = '94d9f9607fbd0889b550430619912b1d1276749488be7c5f26e6c37b750a8bcc'
res = notify('justoa', s, {'aps':{'alert': 'Hello!', 'sound':'default'}})
示例#12
0
#!/usr/bin/python 
from pyapns import configure, provision, notify
import time

configure({'HOST': 'http://localhost:7077/'})

provision('com.tencent.mqq', open('ck_mqq_dis.pem').read(), 'production')

notify('com.tencent.mqq', 'c3765d1dc9b0058dfc1dced29eba088261df202f5a09f262cb536f7b8528b07b', {'aps':{'alert': 'Hello!'}})
time.sleep(1)
notify('com.tencent.mqq', 'c3765d1dc9b0058dfc1dced29eba088261df202f5a09f262cb536f7b8528b07b', {'aps':{'alert': 'Hello2'}})
time.sleep(3)
notify('com.tencent.mqq', 'c3765d1dc9b0058dfc1dced29eba088261df202f5a09f262cb536f7b8528b07b', {'aps':{'alert': 'Hello5'}})
示例#13
0
#!/usr/bin/python
示例#14
0
文件: push.py 项目: gerald-kim/rdict
from pyapns import configure, provision, notify

token = '561889ee286a61c2c3fcf2989aa0929b8f743adc595577d30339a33cdfd5c5da'
configure({'HOST': 'http://localhost:7077/'})
provision('5525D75T6C.com.ampliostudios.awtest', open('apns-dev.pem').read(), 'sandbox')
notify('5525D75T6C.com.ampliostudios.awtest', token, {'aps':{'badge': 9}})
示例#15
0
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)
示例#17
0
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요청입니다.')
示例#18
0
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요청입니다.')
示例#19
0
#!/usr/bin/python
示例#20
0
 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)