コード例 #1
0
ファイル: views.py プロジェクト: Srbpunyani/yoolotto
 def post(self,request):
     data = json.loads(request.body)
     print data
     referring_user = data['first_referring_identity']
     event_occured = data['event']    
     event_details = EventInfo(referring_user = referring_user,event_occured = event_occured)
     event_details.save()
     print referring_user
     user_details = YooLottoUser.objects.get(email = referring_user)
     print user_details.id
     user_device_details = Device.objects.filter(user = user_details.id)
     for device in user_device_details:
         print device.id
         print device.device_type
         print device.device_token
         text = "You have been awarded for referral"
         try:
             if device.device_type == "IPHONE":
                 apn = APNSender(device.device_token, text=text,custom={"code": "referral_tracking"})
                 apn.send()
             elif device.device_type == "ANDROID":
                 gcm = GCMSender(to=[device.device_token], data={"text": text,"code": "referral_tracking"})
                 gcm.send()
         except:
             pass
         print "everything successfullllllllllllllll"
     return HttpResponse('result')
コード例 #2
0
 def handle(self, *args, **options):
     file = os.path.join(settings.LOG_BASE_PATH, "mass_notification-%s.log" 
         % datetime.datetime.now().isoformat())
     fp = open(file, "w")
     
     batch = []
     batches = []
     
     query = Device.objects.filter(device_type="ANDROID", device_token__isnull=False)
     query = Device.objects.filter(user_id=2441)
     
     for device in query:
         if len(batch) >= 500:
             batches.append(batch)
             batch = []
         batch.append(device.device_token)
             
     if batch:
         batches.append(batch)
     
     data = {"text": "Fixes coming soon, so sorry!", "code": "frenzy"}
     
     fp.write("GCM Data\n")
     fp.write(json.dumps(data) + "\n\n")
     
     for batch in batches:
         fp.write("Sending GCM Batch to %s Recipients\n" % len(batch))
         fp.write(json.dumps(batch) + "\n\n")
         
         try:
             gcm = GCMSender(to=batch, data=data)
             gcm.send()
         except Exception as e:
             fp.write(str(e))
             raise
         
     query = Device.objects.filter(device_type="IPHONE", device_token__isnull=False)
     query = Device.objects.filter(user_id=20433)
     
     text = "Fixes coming soon, Sorry! Free food in Yoo Prizes"
     
     for device in query:
         fp.write("Sending one-off APN to %s" % device.device_token)
         
         try:
             apn = APNSender(device.device_token, text=text)
             apn.send()
         except Exception as e:
             fp.write(str(e))
             raise
         
         time.sleep(1)
コード例 #3
0
ファイル: tasks.py プロジェクト: Srbpunyani/yoolotto
def notify_device(device, message, data={}):
    from yoolotto.communication.apn import APNSender
    from yoolotto.communication.gcm_sender import GCMSender

    try:
        if device.is_ios():
            apn = APNSender(device.device_token, text=message, custom=data)
            return apn.send()
        elif device.is_android():
            data = {"code": "frenzy", "draw_id": "12345"}

            data.update({"text": message})
            gcm = GCMSender(to=[device.device_token], data=data)
            return gcm.send()
    except Exception, e:
        return str(e)
コード例 #4
0
ファイル: views_9thFeb.py プロジェクト: Srbpunyani/yoolotto
def send_reject_notification(ticket_info,text,reason):
    log = ''
    user_devices = ticket_info.user.devices.all()
    for device in user_devices:
        if not device.device_token:
            log += "\nSkipped Device, No Token"
            continue

        if device.is_ios():
            apn = APNSender(device.device_token, text=text,custom={"code": "data_entry", "msg": reason,})
            apn.send()
            log += "\nAPN Outbound: %s" % device.device_token

        elif device.is_android():
            gcm = GCMSender(to=[device.device_token], data={"text": text,"code": "data_entry", "gameType": ticket_info.draw.component_id,"state":ticket_info.division.remote_id,"drawId":ticket_info.draw_id,"ticket_id":ticket_info.id,"msg":reason,})
            gcm.send()
            log += "\nGCM Outbound: %s" % device.device_token
コード例 #5
0
ファイル: manual_push.py プロジェクト: Srbpunyani/yoolotto
def notify_draw_result_for_ticket(ticket_id):
    from yoolotto.lottery.models import LotteryTicket
    from yoolotto.communication.apn import APNSender
    from yoolotto.communication.gcm_sender import GCMSender
        
    try:
        ticket = LotteryTicket.objects.get(pk=int(ticket_id))
    except:
        return
    
    if not ticket.user.preferences.jackpot_drawing:
        return
    
    log = ""
    log += "\nTicket: " + str(ticket.pk)
    text = "Results available for %s" % ticket.draw.component.name
    log += "\n" + text
    
    for device in ticket.user.devices.all():
        if not device.device_token:
            log += "\nSkipped Device, No Token"
            continue
        
        if device.is_ios():
            apn = APNSender(device.device_token, text=text, 
               custom={"code": "draw", "drawId": ticket.draw.pk,"state":state_codes[ticket.division.remote_id]})
            print apn.send()
            log += "\nAPN Outbound: %s" % device.device_token
        elif device.is_android():
            gcm = GCMSender(to=[device.device_token], data={"text": text,
                                                            "code": "draw", "drawId": ticket.draw.pk,
                                                            "state":ticket.division.remote_id,
                                                            "ticket_id":ticket.id
                                                            })
            print gcm.send()
            log += "\nGCM Outbound: %s" % device.device_token
    
    #ticket.notified = True
    ticket.save()
    
    return log
コード例 #6
0
ファイル: views.py プロジェクト: Srbpunyani/yoolotto
 def post(self, request):
     # Retrieve LMT A Record + Artur's 360 Nueces IP
     AUTHORIZED = [socket.gethostbyname("rio.leanmeantech.com"), "64.30.186.209", "127.0.0.1"]
     TOKEN = "uiiXC1vbTd45QR7O3Q8FlGHclXb9iAcZfY0GM0UVYaMnvd5F6ARMVFMeXND9rZQ4"
     
     if request.GET.get("token", None) != TOKEN:            
         raise WebServiceAuthenticationFailed()
     
     if request.META["REMOTE_ADDR"] not in AUTHORIZED:
         raise WebServiceAuthenticationFailed()
     
     protocol = request.GET.get("type", None)
     if protocol not in ["apns", "gcm"]:
         raise RuntimeError("specify a GET var named 'type' that is either apns or gcm")
     
     device_token = request.GET.get("device_token", None)
     if not device_token:
         raise RuntimeError("specify a GET var named 'device_token' that contains the push notification token")
     
     data = json.loads(request.body)
             
     if protocol == "apns":
         if "text" not in data:
             raise RuntimeError("expecting text in post body")
         
         apn = APNSender(device_token, text=data["text"], 
             custom=data.get("custom", {}), badge=data.get("badge", 0))
         apn.send()
         
         return data
     
     elif protocol == "gcm":
         gcm = GCMSender(to=[device_token], data=data)
         response = gcm.send()
         
         return gcm.send()
     
     raise RuntimeError()
コード例 #7
0
ファイル: manual_push.py プロジェクト: Srbpunyani/yoolotto
def notify_frenzy_for_user_without_ticket(component_name, draw_value, game_type,user_id,draw_id):
    from yoolotto.communication.apn import APNSender
    from yoolotto.communication.gcm_sender import GCMSender
    
    state=LotteryDraw.objects.get(id=draw_id).division.remote_id
    # reducing multiple frenzies notification for any user , 
    # based on user old hits for states in history
    # and also sending duplicate notification for state TX and game_type in 0/1 Megamillion/Powerball
    old_states=[str(_state) for _state in set(YooLottoUser.objects.get(id=user_id).tickets.values_list('division__remote_id',flat=True))]
    send_for_states=[]
    
    log=""
    
    if (not old_states and state=="TX"):
        send_for_states.append("TX")
    elif (state in old_states):
        send_for_states.append(state)
    else:
        log += "\nDevice auto skipped ,assume unnecessary state: %s" % state
    
    if old_states and state=="TX" and game_type in [0,1]: # 0/Megamillion(TX),1/Powerball(TX):
        #send duplicate notification for state that user has already played
        [send_for_states.append(i) for i in old_states if i!="CA"]
    
    send_for_states=list(set(send_for_states))
    for _index,right_state in enumerate(send_for_states):#loop for duplicate notification
        if right_state!="TX" and len(send_for_states) > 1:
            log += "\n Send duplicate notification for state: %s" % right_state
            
        user = YooLottoUser.objects.get(pk=int(user_id))
        log += "\nUser: "******"%s %s Jackpot is %s!" % (state_name,component_name, draw_value)
        log += "\n" + text
        
        
        for device in user.devices.all():
            if not device.device_token:
                log += "\nSkipped Device, No Token"
                continue
            
            if device.is_ios():
                apn = APNSender(device.device_token, text=text,
                                custom={"code": "frenzy", "gameType": game_type,
                                        "state":state_codes[right_state],
                                        "drawId":draw_id
                                        })
                apn.send()
                log += "\nAPN Outbound: %s" % device.device_token
            elif device.is_android():
                gcm = GCMSender(to=[device.device_token], data={"text": text,
                                                                "code": "frenzy", "gameType": game_type,
                                                                "state":right_state,
                                                                "draw_id":draw_id+_index
                                                                })
                gcm.send()
                log += "\nGCM Outbound: %s" % device.device_token
        
        
        log += "\n ---------------------------- \n"
       
        
    return log
コード例 #8
0
    def post(self,request):
      
	from yoolotto.util import currency
        import itertools

        # - parse json
        data = json.loads(request.body)
	end_component = 1
        valid = data['valid']
        state_codes={
             "TX":0,
             "CA":2,
             "AZ":3,
             "AR":4,
             "CO":5,
             "CT":6,
             "DE":7,
             "DC":8,
             "FL":9,
             "GA":10,
             "ID":11,
             "IL":12,
             "IN":13,
             "IA":14,
             "KS":15,
             "KY":16,
             "LA":17,
             "ME":18,
             "MD":19,
             "MA":20,
             "MI":21,
             "MN":22,
             "MO":23,
             "MT":24,
             "NE":25,
             "NH":26,
             "NJ":27,
             "NM":28,
             "NY":29,
             "NC":30,
             "ND":31,
             "OH":32,
             "OK":33,
             "OR":34,
             "PA":35,
             "RI":36,
             "SC":37,
             "SD":38,
             "TN":39,
             "VT":40,
             "VA":41,
             "WA":42,
             "WI":43,
             "WV":44,
         "WY":45
             }
        ticket_id = data['ticket']
        ticket_info = LotteryTicket.objects.get(id=ticket_id)

        play_id = data['playid']
        availability = LotteryTicketAvailable.objects.filter(play=play_id)[0]
        # - if valid
        if valid:

            
            # - get ticket info
            
            
            all_dates = data['drawdate'].split(",")
            defected = data["imagequality"]
            defected_ticket = False
            if defected == "No":
                defected_ticket = True
            draw_date = all_dates[0]
            data['drawdate'] = all_dates[0]
            division = data['state']
	    common_state = 1
            if division == 'CA':
                common_state = 2
            game_type_id = data['gametypeid']
            draw_time = data['drawTime']
            lines = []
            for item in data['lines']:
                lines.append(json.loads(json.dumps(item)))
            
            submission_record = None
            submission = uuid.uuid4().hex[:16]

            
            

            # - parse game type id
            if division == 'CA':
                game_types = {1:11,2:13}
                components = {1:"Powerballca",2:"MegaMillionsCA"}
            else:
                game_types = {1:1,4:6,8:7,7:5,6:4,3:2,5:3,2:0}
                components = {1:"Powerball",4:"TwoStep",7:"CashFive",3:"LottoTexas",2:"MegaMillions"}

            # - get game type
            game_type = game_types[game_type_id]

            # - get handler
            games = {}
            record = {}
            allocated = {}
            tickets = {}
            games[game_type] = EnumerationManager.game(game_type)
            game = games[game_type]#LotteryGame Obj
            handler = game.handler

            # - get component
            if game_type == 7 or game_type == 4 or game_type == 3:
                record = {'drawTime':draw_time}
                component = handler.get_component(record)
                end_component = None
                if data["consecutive"]:
                    record_copy = record
                    record_copy["drawTime"] = data["enddrawtime"]
                    end_component = handler.get_component(record_copy)
                #baseWager, sum, sumWager
                if game_type == 3:
                    enums = {1: "SUM",8: "ANY",9: "COMBO",10: "EXT",11: "EXTANY",}
                elif game_type == 4:
                    enums = {1: "SUM",2: "STR",3: "BOX",4: "STRBOX",5: "FRONT",6: "MID",7: "BACK",9: "COMBO"}
                if game_type == 3:
                    for line in lines:
                        line['sum'] = line.pop('sumitUp')
                        line['sumWager'] = line.pop('sumAmount')
                        line['baseWager'] = line['amount']
                        line['lineType'] = enums[line['lineType']]
			line['totalWager'] = line['amount']

			if line["lineType"] == "COMBO":
                            numbers = line['numbers']
                            if line['sum'] != None:
                                numbers = [line['sum']]
                            line["baseWager"] = currency.format(float(line["amount"]) / len(set(itertools.permutations(numbers))))
                        elif line["lineType"] in ["STRBOX", "EXTANY"]:
                            line["baseWager"] = currency.format(float(line["amount"]) / 2)
                        else:
                            line["baseWager"] = currency.format(line["amount"])

		elif game_type == 4:

                    for line in lines:
                        line['sum'] = line.pop('sumitUp')
                        line['sumWager'] = line.pop('sumAmount')
                        line['baseWager'] = line['amount']
                        line['lineType'] = enums[line['lineType']]
                        line['totalWager'] = line['amount']

			if line["lineType"] == "FRONT":
                            line["numbers"] = line["numbers"][0:2]+[0,0]
                        elif line["lineType"] == "MID":
                            line["numbers"] = [0]+line["numbers"][1:3]+[0]
                        elif line["lineType"] == "BACK":
                            line["numbers"] = [0,0]+line["numbers"][2:4]

			if line["lineType"] == "COMBO":
                            numbers = line['numbers']
                            if line['sum'] != None:
                                numbers = [line['sum']]
                            line["baseWager"] = currency.format(float(line["amount"]) / len(set(itertools.permutations(numbers))))
                        elif line["lineType"] in ["STRBOX", "EXTANY"]:
                            line["baseWager"] = currency.format(float(line["amount"]) / 2)
                        else:
                            line["baseWager"] = currency.format(line["amount"])

                else:
                    for line in lines:
                        line['sum'] = line.pop('sumitUp')
                        line['sumWager'] = line.pop('sumAmount')
                        line['baseWager'] = line['amount']
			line['totalWager'] = line['amount']

			

            else:
                component = LotteryGameComponent.objects.get(identifier=components[game_type_id])
                for line in lines :
                    line.pop('sumitUp')
                    line.pop('sumAmount')
                    line.pop('lineType')
                    line.pop('amount')
		    line['multiplier'] = data['ismultiplier']


            # - get updated draw
            date = datetime.datetime.strptime(draw_date, "%Y-%m-%d").date()
            updated_draw, created = LotteryDraw.objects.get_or_create(component=component,division_id=common_state,date=date)


            # - get record
            
            # - perform validation
            handler.preprocess_ticket(data)
            for item in lines :
                handler.validate_play(item)

            # - if draw is diffrent
            if updated_draw.id != ticket_info.draw.id :
                # create new ticket
                new_ticket_info, created = LotteryTicket.objects.get_or_create(deleted=False,user=ticket_info.user,draw=updated_draw,division=LotteryCountryDivision.objects.get(remote_id=division))
                valid_draw = updated_draw.id
                valid_ticket = new_ticket_info.id
                tickets[valid_ticket] = new_ticket_info

                submission_record, created = LotteryTicketSubmission.objects.get_or_create(submission=submission, ticket_id=valid_ticket)
                submission_record.save()

                # create new play
                for line in lines:
                    serialized = dumps(line)
                    play_record = LotteryTicketPlay(play=serialized,ticket=new_ticket_info,division=LotteryCountryDivision.objects.get(remote_id=division))
                    play_record.submission_old = submission
                    play_record.submission = submission_record
            
                    play_record.update_winnings(save=True)

                    line['gameType'] = game_type

                    available_record = LotteryTicketAvailable(available = True, json= line, ticket_id= valid_ticket, play_id=play_record.id, device = availability.device, image_first = "static/ticket/"+str(play_id)+"_1.jpg", defected = defected_ticket)

                    available_record.save()

                date = datetime.datetime.strptime(draw_date, "%Y-%m-%d").date()
                updated_draw, created = LotteryDraw.objects.get_or_create(component=component,division_id=common_state,date=date)

            else:
                # - if draw is same
                valid_draw = ticket_info.draw.id
                valid_ticket = ticket_info.id
                tickets[valid_ticket] = ticket_info

                submission_record, created = LotteryTicketSubmission.objects.get_or_create(submission=submission, ticket_id=valid_ticket)
                submission_record.save()

                availability.defected = defected_ticket
                #update previous play
                previous_play = LotteryTicketPlay.objects.get(id=play_id)

                if previous_play.play == None :
                    serialized = dumps(lines[0])
                    previous_play.play = serialized
                    previous_play.ticket = ticket_info
                    previous_play.division = LotteryCountryDivision.objects.get(remote_id=division)
                    previous_play.submission_old = submission
                    previous_play.submission = submission_record
                    previous_play.update_winnings(save=True)
                    lines.pop(0)
                
		availability.available = True
                availability.save()
                # create new play
                for line in lines:
                    serialized = dumps(line)
                    
                    play_record = LotteryTicketPlay(play=serialized,ticket=ticket_info,division=LotteryCountryDivision.objects.get(remote_id=division))
                    play_record.submission_old = submission
                    play_record.submission = submission_record
                    play_record.update_winnings(save=True)

                    line['gameType'] = game_type

                    available_record = LotteryTicketAvailable(available = True, json= line, ticket_id= valid_ticket, play_id=play_record.id, device = availability.device, image_first = "static/ticket/"+str(play_id)+"_1.jpg", defected = defected_ticket)

                    available_record.save()
            # - send notification

            user_devices = ticket_info.user.devices.all()
            text = 'your ticket is available'

            if game_type_id == 11:
                    gameType = 1
            elif game_type_id == 13:
                    gameType = 2
            else:
                    gameType = game_type_id
	    try:
            	for device in user_devices:
                    if not device.device_token:
                        continue

                    if device.is_ios():
                        apn = APNSender(device.device_token, text=text,
                                        custom={"code": "data_entry", "gameType": gameType,
                                                "drawId":valid_draw, "state":state_codes[division]
                                                })
                        apn.send()

                    elif device.is_android():

                        gcm = GCMSender(to=[device.device_token], data={"text": text,
                                                                        "code": "data_entry", "gameType": gameType,
                                                                        "state":division,
                                                                        "drawId":valid_draw,
                                                                        "ticket_id":valid_ticket
                                                                        })

                        gcm.send()
	    except:
		pass
            # - return result

            
	    
            try:
                user_client_record, created = UserClientLogin.objects.get_or_create(device=availability.device)
            except:
                user_client_record = UserClientLogin.objects.filter(device=availability.device)[0]

            for ticket in tickets.values():
                    allocated[ticket.pk] = ticket.update(availability.device,user_client_record.client_login)

            result = map(lambda x: x.representation(allocated=allocated), tickets.values())
            for _result in result:
                    coins = allocated.get(_result["ticket_id"], None)
                    if coins < 1:
                        coins = None

                    _result["coins"] = coins

            multi_draws = []
            draws = self.get_draws(all_dates,component,common_state,game_type,data['state'],end_component,handler)
            for each_draw in draws:

                multi_ticket_info, created = LotteryTicket.objects.get_or_create(deleted=False,user=ticket_info.user,draw=each_draw,division=LotteryCountryDivision.objects.get(remote_id=division))
                valid_ticket = multi_ticket_info.id

                submission_record, created = LotteryTicketSubmission.objects.get_or_create(submission=submission, ticket_id=valid_ticket)
                submission_record.save()

                for line in lines:
                    serialized = dumps(line)
                    play_record = LotteryTicketPlay(play=serialized,ticket=multi_ticket_info,division=LotteryCountryDivision.objects.get(remote_id=division))
                    play_record.submission_old = submission
                    play_record.submission = submission_record
            
                    play_record.update_winnings(save=True)

                    line['gameType'] = game_type

                    available_record = LotteryTicketAvailable(available = True, json= line, ticket_id= valid_ticket, play_id=play_record.id, device = availability.device, image_first = "static/ticket/"+str(play_id)+"_1.jpg")

                    available_record.save()

                #tickets[valid_ticket] = new_ticket_info
            #return result
        
        else:
            # - if reject
            
            # - send notification
            reason = data['RejectReason']
            availability.rejected = True
            availability.reason = reason
            availability.save()

            text = 'Your Ticket is Rejected'
            send_reject_notification(ticket_info,text,reason,)
            

        return {"sucess":True}