Пример #1
0
def send(req, phone):
    from SMS import SMS
    sms = SMS("成少雷", "SMS_102315005")

    # 验证码
    num = random.randint(10000, 99999)

    para = "{'number':'%d'}" % num
    # 阿里云服务器会修改cookie路径,需要重新吧cookie的path设置/
    res = sms.send(phone, para)

    # 将验证码写入文件
    response = Response(req)
    response.set_cookie('phone', phone)
    response.set_cookie('code', num)

    req.start_response("200 ok", response.header)
    #
    html = b"""
    <html>
    <head>
       <meta charset='utf-8'>
       <meta http-equiv='refresh' content='0;url=/login'>
    </head>
    <body></body>
    </html>
    """
    return [html]
Пример #2
0
def login():
    auth = request.authorization
    if not auth:
        return jsonify({'message': 'Authotization Not Provided!'}), 400
    else:
        username = auth.username
        password = auth.password

        for user in users_list:
            if username == user.name and password == user.password:
                token = jwt.encode(
                    {
                        'name':
                        user.name,
                        'exp':
                        datetime.datetime.utcnow() +
                        datetime.timedelta(minutes=15)
                    }, os.environ['SECRET_KEY'])

                mail = Mail(
                    user.mail, 'Login',
                    'http://0.0.0.0:50/user-login?token={}'.format(
                        token.decode('utf-8')))
                mail.send()
                sms = SMS(user.phone, 'Someone Logged into your account')
                sms.send()
                return jsonify({'token': token.decode('utf-8')}), 200
            else:
                return jsonify({'message':
                                'Username or Password is Invalid'}), 400
        return jsonify({'message': 'Username or Password is Invalid'}), 400
Пример #3
0
 def run(self):
     sendSkt = lightblue.socket()
     sendSkt.bind(("", 0))
     sendSkt.listen(1)
     lightblue.advertise("SMS Gateway (Response Thread)", sendSkt,
                         lightblue.RFCOMM)
     db = database()
     conn2, addr2 = sendSkt.accept()
     print "Connected to Response Server", addr2
     while 1:
         time.sleep(1)
         db = database()
         rows = db.popOutboxMsg()
         for row in rows:
             print "Sending Msg -> %s" % (row[0])
             sms = SMS(str(row[0]), row[1], row[2], row[3], str(row[4]))
             toSend = sms.toXML()
             print toSend
             conn2.send(toSend.replace("\n", "\\n"))
             res = conn2.recv(1024)
             print res
             while (res != "1" and res != "2"):
                 res = conn2.recv(1024)
                 print res
             db.setOutboxProcessed(str(row[0]), res)
Пример #4
0
def checkSMS(e):
    global contact_addr
    global textMode
    SAY("Ok, is this correct?")
    SAY(e)
    ans = trueOrFalse()
    if ans:
        sms = SMS()
        sms.send([contact_addr, e])
        SAY("Ok, text message sent")
        textMode = False
    else:
        SAY("Ok, try again")
        newE = listenForText()
        Print(newE)
        checkSMS(newE)
Пример #5
0
def combiReformer(liste):
    cpt = 0
    nouveau = []
    message = ""

    if len(liste) < 2:
        return 0
    for i in range(len(liste)):
        l = []
        if estInteressant(liste[i]):
            l.append(liste[i][0])
            l.append(['m', '*', 'm'])
            l.append(liste[i][2])
            cpt = 1
            message += liste[i][0][0] + " Vs " + liste[i][0][1] + "\n"
            message += "[m ,* ,m]\n"
            message += "------------\n"
        else:
            l = deepcopy(liste[i])
            message += liste[i][0][0] + " Vs " + liste[i][0][1] + "\n"
            message += "[" + str(liste[i][1][0]) + ", " + str(
                liste[i][1][1]) + ", " + str(liste[i][1][2]) + "]\n"
            message += "------------\n"

        nouveau.append(l)
    if cpt == 0:
        return 0
    else:
        SMS(message)
        return nouveau
Пример #6
0
 def fill_queue(self):
     """
     Will attempt to GET enough SMSs from the URL to fill the internal queue
     back to MAX_SMS. If there are 5 in the queue, and MAX_LENGTH is 12, 7
     will be requested.
     
     Sens an HTTP GET request to the URL with the following parameters:
     max_sms, key
     
     Returns the new length of the sms_queue
     """
     current_length = len(self.sms_queue)
     desired_sms = self.MAX_SMS - current_length  
     data_dict = {
         'max_sms' : desired_sms,
         'key' : self.key
     }
     
     # Make the request
     result = requests.get(self.url, params=data_dict)      
       
     if result.status_code == requests.codes.ok: 
         for sms in result.json['sms']:
             new_sms = SMS.from_dictionary(sms)
             self.sms_queue.append(new_sms)
             
         count = result.json['sms_count']
         if VERBOSE:
             logger.log(self, "grabbed %s messages from django queue" % count)
             
         return current_length + count        
     else:
         logger.log_error(self, "error filling queue: %d - %s" % (result.status_code, result.error))
         save_error_response(result)
         return current_length
Пример #7
0
 def fill_queue(self):
     """
     will fill the queue back up to however many it can
     will only try once
     """
     
     desired_sms = self.MAX_SMS - len(self.sms_queue)    
     data_dict = {
         'max_sms' : desired_sms,
         'key' : self.key
     }
     
     result = requests.get(self.url, params=data_dict)        
     if not result.status_code == requests.codes.ok:
         logger.log_error(self, "error filling queue: %d - %s" % (result.status_code, result.error))
         log_response(result)
         return 0
     
     count = result.json['sms_count']
     
     for sms in result.json['sms']:
         new_sms = SMS.from_dictionary(sms)
         self.sms_queue.append(new_sms)
     
     if VERBOSE:
         logger.log(self, "grabbed %s messages from django queue" % count)
     
     return len(self.sms_queue)
class TestSMS_store(TestCase):
    sms1 = SMS("+361224", "20190101 15:40", "BUÉK!")
    sms2 = SMS("+363012", "20191224 08:00", "Kellemes karácsonyt!")
    sms3 = SMS("+3619008", "20190501 15:40", "Éljen május 1!")

    def setUp(self):
        self.test_store = SMS_store()
        self.test_store.add_new_arrival(self.sms1.fromn, self.sms1.time,
                                        self.sms1.text)
        self.test_store.add_new_arrival(self.sms2.fromn, self.sms2.time,
                                        self.sms2.text)
        self.test_store.add_new_arrival(self.sms3.fromn, self.sms3.time,
                                        self.sms3.text)

    def test_add_new_arrival(self):
        self.assertEqual(self.sms1, self.test_store.store[0])
        self.assertEqual(self.sms2, self.test_store.store[1])
        self.assertEqual(self.sms3, self.test_store.store[2])

    def test_message_count(self):
        self.assertEqual(3, self.test_store.message_count())

    def test_get_unread_indexes(self):
        self.assertEqual([0, 1, 2], self.test_store.get_unread_indexes())

    def test_get_message(self):
        smscpy = SMS(self.sms2.fromn, self.sms2.time, self.sms2.text)
        smscpy.viewed = True
        self.assertEqual(smscpy, self.test_store.get_message(1))

    def test_delete(self):
        self.test_store.delete(1)
        self.assertEqual(self.sms1, self.test_store.store[0])
        self.assertEqual(self.sms3, self.test_store.store[1])
        self.assertEqual(2, self.test_store.message_count())

    def test_clear(self):
        self.test_store.clear()
        self.assertEqual(0, self.test_store.message_count())
Пример #9
0
 def run(self):
     s = lightblue.socket()
     s.bind(("", 0))
     s.listen(2)
     lightblue.advertise("SMS Gateway (Request Thread)", s,
                         lightblue.RFCOMM)
     conn, addr = s.accept()
     print "Connected to Request Server", addr
     while 1:
         resp = conn.recv(1024)
         print resp
         msg = SMS(resp)
         db = database()
         db.pushInboxMsg(msg.id, msg.to, msg.frm, msg.text, msg.timestamp)
     conn.close()
     s.close()
Пример #10
0
 def listen(self):
     print "Enter Your SMS:"
     sms_dict = {}
     
     sms_dict['to_number'] = raw_input("To: ")
     sms_dict['from_number'] = raw_input("From: ")
     sms_dict['body'] = raw_input("Body:\n")
     
     
     if sms_dict['to_number'] == "DO:QUIT":
         return False
                 
     sms = SMS.from_dictionary(sms_dict)
     
     logger.log_receive(self, sms)
     self.receive_callback(sms)
         
Пример #11
0
 def listen(self):
     """
     Used STDIN and STDOUT to get string values for the to,
     from, and body attributes of the sms to build.
     
     Will return False if the To parameter is 'DO:QUIT'
     """
     print "Enter Your SMS:"
     sms_dict = {}
     
     sms_dict['to_number'] = raw_input("To: ")
     sms_dict['from_number'] = raw_input("From: ")
     sms_dict['body'] = raw_input("Body:\n")
     
     
     if sms_dict['to_number'] == "DO:QUIT":
         return False
                 
     sms = SMS.from_dictionary(sms_dict)
     
     logger.log_receive(self, sms)
     self.receive_callback(sms)
         
Пример #12
0
class SMSTest(unittest.TestCase):
    def setUp(self):
        lunchr.loadUrl = minimock.Mock('lunchr.loadUrl', returns='0')
        self.SMS = SMS('username', 'password', 'type')

    def tearDown(self):
        del self.SMS
        minimock.restore()

    def test_constructor(self):
        """
        Tests that SMS constructor sets values properly.
        """
        self.assertEquals('username', self.SMS.username)
        self.assertEquals('password', self.SMS.password)
        self.assertEquals('type', self.SMS.type)

    def test_send(self):
        """
        Tests that SMS.send() can send an SMS.
        """
        result = self.SMS.send('phonenumber', 'message')
        self.assertEquals('0', result)
 def test_get_message(self):
     smscpy = SMS(self.sms2.fromn, self.sms2.time, self.sms2.text)
     smscpy.viewed = True
     self.assertEqual(smscpy, self.test_store.get_message(1))
Пример #14
0
def checkCombi(resultat, combi):
    tailleCombi = len(combi)
    i = 0
    fini = 0
    message = ""
    perdu = 0
    gagner = 0
    notFinish = 0
    while i < len(combi):
        c = combi[i]
        find = 0
        for match in resultat:

            if c[0][0] == match[0][0]:
                find = 1
                fini = fini + 1
                message += c[0][0] + " " + str(match[1][0]) + "-" + str(
                    match[1][1]) + " " + c[0][1]
                mise = miseSur(c[1])
                if match[1][0] > match[1][1] and mise == 'v':
                    tailleCombi = tailleCombi - 1
                    message += " Ok\n"
                    gagner = gagner + 1
                elif match[1][0] < match[1][1] and mise == 'p':
                    tailleCombi = tailleCombi - 1
                    message += " Ok\n"
                    gagner = gagner + 1
                elif match[1][0] == match[1][1] and mise == 'n':
                    tailleCombi = tailleCombi - 1
                    message += " Ok\n"
                    gagner = gagner + 1
                elif match[1][0] > 0 and match[1][1] > 0 and mise == 'm':
                    tailleCombi = tailleCombi - 1
                    message += " Ok\n"
                    gagner = gagner + 1
                else:
                    message += "-X-\n"
                    perdu = perdu + 1
                message += "----------------\n"

        if find == 0:
            notFinish = notFinish + 1
            message += c[0][0] + " Vs " + c[0][1] + "-PF-"

        i = i + 1
    if tailleCombi == 0:
        message += "\n Combi GAGNEE"
        SMS(message)
        return "GAGNEE"
    elif fini == len(combi):
        message += "\n Combi PERDU\n"
        message += "Match gagner : " + str(gagner) + "\n"
        message += "Match perdu : " + str(perdu)
        SMS(message)
        return "PERDU"
    else:
        message += "Match gagner : " + str(gagner) + "\n"
        message += "Match perdu : " + str(perdu) + "\n"
        message += "Match Non Fini : " + str(notFinish)
        message += "\nAu moins un match pas fini\n"
        SMS(message)
        return "PAS FINI"
Пример #15
0
 def setUp(self):
     lunchr.loadUrl = minimock.Mock('lunchr.loadUrl', returns='0')
     self.SMS = SMS('username', 'password', 'type')
Пример #16
0
    def one(self):
        """
        Called to read an SMS from file_
        
        Three states:
            - waiting
            - headers
            - body        
        """
                

        
        # Will be the values for the SMS
        to_ = ""
        from_ = ""
        body = ""
        
        # extra for the body line counting
        length = 0;
        bodyLinesRemaining = 0;
        
        # initial state
        state = "waiting"
        
        while True:           
            # get one line from file_
            try:
                line = self.file_.readline()
            except IOError as e: # in socket closed
                return None

            if line == "": # EOF
                return None
                        
            # Now we strip the newline, because if we had
            # done it before the EOF check, there would
            # have been false EOFs
            line = line.strip()

            # waiting state
            if state == "waiting":
                if line == "TEXT":
                    state = "headers"
                else:
                    raise RuntimeError("Invalid line while waiting for text: %s" % line);
                
            # header state
            elif state == "headers":
                headerMatch = self.HEADER_RE.match(line)
                if headerMatch:
                    key = headerMatch.group(1)
                    value = headerMatch.group(2)

                    if key == "LENGTH":
                        try:
                            length = int(value)
                        except ValueError:
                            raise RuntimeError("LENGTH value must be integer")
                    elif key == "TO":
                        to_ = value
                    else:
                        from_ = value
                    
                elif line == "":
                    # Headers are finished
                    state = "body"
                    bodyLinesRemaining = length        
                else:
                    raise RuntimeError("Invalid line while parsing headers: %s" % line)
            
            # body state    
            elif state == "body":
                body += line + "\n" # undo the line.strip()
                bodyLinesRemaining -= 1

                if bodyLinesRemaining == 0:
                    # We have slurped up all the body that we need to
                    out = SMS(to_, from_, body)
                    out.trim() # remove the last \n as described by the spec
                    return out
            
            # unknown state?
            else:
                raise RuntimeError("Invalid state in message parser: %s" % state)
Пример #17
0
def combiner(liste):
    message = ""
    cote = 1.0
    maxHeure = 1
    maxMinute = 0
    minHeure = 23
    minMinute = 59
    lastGameForCombi = []
    listeCombi = []
    listeBonCombi = []
    totalMatch = 0
    pm = []
    for foot in liste:
        hv = foot[2][0]
        nn = foot[2][1]
        exv = foot[2][2]

        if hv >= 60 and exv <= 20:
            minHeure, minMinute = premierMatch(minHeure, minMinute, foot)
            maxHeure, maxMinute = dernierMatch(maxHeure, maxMinute, foot)
            message += foot[0][0] + " Vs " + foot[0][1] + "\n"
            message += "[1 , * , * ] \n"
            message += "[" + str(foot[2][0]) + "%, " + str(
                foot[2][1]) + "% , " + str(foot[2][2]) + "%]" + "\n"
            message += "-------------\n"
            cote *= foot[1][0]
            totalMatch = totalMatch + 1
            tmp = deepcopy(foot)[:-1]
            tmp[1][0] = "1"
            tmp[1][1] = "*"
            tmp[1][2] = "*"
            listeCombi.append(tmp)

        elif hv <= 20 and exv >= 60:
            minHeure, minMinute = premierMatch(minHeure, minMinute, foot)
            maxHeure, maxMinute = dernierMatch(maxHeure, maxMinute, foot)
            message += foot[0][0] + " Vs " + foot[0][1] + "\n"
            message += "[* , * , 1 ] \n"
            message += "[" + str(foot[2][0]) + "%, " + str(
                foot[2][1]) + "% , " + str(foot[2][2]) + "%]" + "\n"
            message += "-------------\n"
            cote *= foot[1][2]
            totalMatch = totalMatch + 1
            tmp = deepcopy(foot)[:-1]
            tmp[1][0] = "*"
            tmp[1][1] = "*"
            tmp[1][2] = "1"
            listeCombi.append(tmp)
        elif abs((hv - exv)) <= 6:
            minHeure, minMinute = premierMatch(minHeure, minMinute, foot)
            maxHeure, maxMinute = dernierMatch(maxHeure, maxMinute, foot)
            message += foot[0][0] + " Vs " + foot[0][1] + "\n"
            message += "[m , * , m ] \n"
            message += "[" + str(foot[2][0]) + "%, " + str(
                foot[2][1]) + "% , " + str(foot[2][2]) + "%]" + "\n"
            message += "-------------\n"
            cote *= foot[1][1]
            totalMatch = totalMatch + 1
            tmp = deepcopy(foot)[:-1]
            tmp[1][0] = "m"
            tmp[1][1] = "*"
            tmp[1][2] = "m"
            listeCombi.append(tmp)

    cote = round(cote, 2)
    message += "cotes Total = " + str(cote) + "\n"
    message += "Total Match = " + str(totalMatch) + "\n"
    message += "First Match commence à :" + str(minHeure) + "h" + str(
        minMinute) + "\n"
    message += "Dernier Match commence à :" + str(maxHeure) + "h" + str(
        maxMinute)
    print(listeCombi)
    SMS(message)
    return listeCombi, maxHeure, maxMinute