Commit 99716152 by Tu Nombre

se optimiso la entrada de mails, y se controla la salida

1 parent dd45ed58
......@@ -18,7 +18,7 @@ class StatePhoneWs():
def ChequearTelefono(self, telefono):
"""Chequea estado es el server remoto si esta conectado se almasena la
respuesta en cache durante 30 segundos para mejorar performance y si no esta
respuesta en cache durante 60 segundos para mejorar performance y si no esta
disponible no se almasena y la proxima respuesta debera hacerse contra el server
remoto para asegurarme de q se solucione el problema"""
test = self.revisarCache(telefono)
......@@ -27,9 +27,10 @@ class StatePhoneWs():
W = self.chequear_stado_WB(telefono)
if "error" in W.keys():#si hay algun error no actualiso el estado en cache
return(W)
hora = datetime.datetime.now() + datetime.timedelta(seconds=30)
hora = datetime.datetime.now() + datetime.timedelta(seconds=60)
self.Consultas[telefono] = {"hora": hora,
"estado": W}
print("Chequeando telefono saliente", W)
return(W)
def revisarCache(self, telefono):
......@@ -69,6 +70,7 @@ class StateMail():
hora = datetime.datetime.now() + datetime.timedelta(seconds=120)
self.Consultas[self._GenerarKey(User, Pass, Port, Host)] = {"hora": hora,
"estado": W}
print("chequeando servidor de salida", W)
return(W)
def revisarCache(self, User, Pass, Port, Host):
......
......@@ -7,4 +7,6 @@ SMTP_username = "anac.avisos@gmail.com"
SMTP_password = "xvc7733455"
SMTP_HOST = "smtp.gmail.com"
SMTP_PORT = 587
SMS_URL = "http://192.168.15.120:8080/v1/sms/send/"
\ No newline at end of file
SMS_URL = "http://192.168.15.120:8080/v1/sms/send/"
folder = "msg/"
db = "/dev/shm/messages.db"
\ No newline at end of file
......@@ -9,9 +9,10 @@ import os, ipdb, time, threading, random, datetime, config
app = Flask(__name__)
TelState = StatePhoneWs()
MailState = StateMail()
# carpeta de los mensajes
msgfolder = "msg/"
msgfolder = config.folder#"msg/"
# id mínimo para una tabla
minid = 1
# id máximo para una tabla
......@@ -25,10 +26,9 @@ prefix_lenght = 16
# tiempo límite que debe pasar para eliminar cosas
operation_timer = 86400
# conección a base de datos
process = Process("messages.db")
process = Process(config.db, TelState, MailState)
#Cache de estado de telefonos
TelState = StatePhoneWs()
MailState = StateMail()
@app.route('/')
def main():
......@@ -66,25 +66,26 @@ def data():
os.mkdir(path)
key = request.files.get('key')
if key:
request.files['key'].save(path + "rand.key.enc")
#if key:
# print("desencripto deploy.py 70")
# request.files['key'].save(path + "rand.key.enc")
# denecripto llave simétrica con mi llave privada y la guardo en la carpeta del emisor
os.system("openssl rsautl -decrypt -inkey rsa_key.pri -in " + path + "rand.key.enc -out " + path + "rand.key")
os.remove(path + "rand.key.enc")
# os.system("openssl rsautl -decrypt -inkey rsa_key.pri -in " + path + "rand.key.enc -out " + path + "rand.key")
# os.remove(path + "rand.key.enc")
for file in request.files:
# si hay llave y no es esta
filepath = path + file
if key and file != "key":
request.files[file].save(filepath + ".enc")
#if key and file != "key":
# request.files[file].save(filepath + ".enc")
# desencripto archivo con la llave simétrica y lo guardo en la carpeta del emisor
os.system("openssl enc -d -aes-256-cbc -in " + filepath + ".enc -out " + filepath + " -pass file:" + path + "rand.key")
os.remove(filepath + ".enc")
else:
request.files[file].save(filepath)
# os.system("openssl enc -d -aes-256-cbc -in " + filepath + ".enc -out " + filepath + " -pass file:" + path + "rand.key")
# os.remove(filepath + ".enc")
#else:
request.files[file].save(filepath)
if key:
os.remove(path + "rand.key")
#if key:
# os.remove(path + "rand.key")
return str(process.datastore(
random.randrange(minid,maxid),
......@@ -132,13 +133,13 @@ def cons():
# Intenta enviar mensajes
def attempt():
p = Process('messages.db')
p = Process(config.db, TelState, MailState)
p.send()
threading.Timer(retry_timer, attempt).start()
# Limpia basura
def clean():
p = Process('messages.db')
p = Process(config.db, TelState, MailState)
paths = p.paths()
now = datetime.datetime.now()
......@@ -158,8 +159,8 @@ def clean():
# Inicio del servicio
if __name__ == "__main__":
# Genero llaves
os.system("openssl genrsa -out rsa_key.pri 4096") # private key
os.system("openssl rsa -in rsa_key.pri -out rsa_key.pub -outform PEM -pubout") # public key
#os.system("openssl genrsa -out rsa_key.pri 4096") # private key
#os.system("openssl rsa -in rsa_key.pri -out rsa_key.pub -outform PEM -pubout") # public key
# Demonio attempt
attempt()
# Demonio clean
......
......@@ -5,9 +5,11 @@ import ipdb, os, json
class Process:
def __init__(self,db):
def __init__(self,db,estadoTelefono,estadoMail):
self.db = db
self.conn = DBconnection(db)
self.statePhone = estadoTelefono
self.stateMail = estadoMail
# Guarda la data
def datastore(self,id,path):
......@@ -61,9 +63,13 @@ class Process:
if not os.path.exists(query[Table.path]):
self.conn.query("DELETE FROM msg WHERE id = ?",(query[Table.id],))
continue
serv = serviceFactory(query[Table.serv])
success = serv.send(query)
try:
serv = serviceFactory(query[Table.serv])
success = serv.send(query,self.statePhone,self.stateMail)#envia al servicio se salida
except:
success = {'texto': False}
print("Rompio el proseso de envio procces 71")
#print("proces linea 72 success=", success)
d = json.loads(query[Table.type])
partial = False
......
......@@ -41,7 +41,7 @@ class Wpp1(ServiceBase):
uid = config.WS_uid
server = config.FILE_server
def send(self,data):
def send(self,data,stadotel,stadomail):
tel = data["dest"]
v = ValidacionTelefonosArgentinos()
tel = v.ValidarTelefono(tel)
......@@ -50,10 +50,10 @@ class Wpp1(ServiceBase):
tel = "Error"
#print("telefono a envia ",tel)
data["dest"] = tel
n = self._send(data)
n = self._send(data,stadotel)
return(n)
def _send(self,data):
def _send(self,data,stadotel):
print(data)
types = json.loads(data[Table.type])
try:
......@@ -76,6 +76,7 @@ class Wpp1(ServiceBase):
f.close()
if type(text) == bytes:
text = text.decode("utf-8")
self.controlSalida(stadotel,origen)
result = requests.get(url = Wpp1.URL + Wpp1.URLmode[types[file]],params = {'token':Wpp1.token,'uid':origen,'to':data[Table.dest],'text':text})
succ[file] = result.json()['success']
else:
......@@ -87,6 +88,11 @@ class Wpp1(ServiceBase):
succ[file] = False
return succ
def controlSalida(self,stadotel,telefono):
n = stadotel.ChequearTelefono(telefono)
if not n["success"] == True:
raise NameError('Telefono_Desconectado')
def validatetype(self,type):
return type in Wpp1.Allowed
......@@ -109,6 +115,9 @@ class Mail(ServiceBase):
def __init__(self):
self.__username = config.SMTP_username
self.__password = config.SMTP_password
def iniciarConn(self):
#print("inicializo cliente default mail")
self.s = smtplib.SMTP(host = config.SMTP_HOST, port = config.SMTP_PORT)
self.s.starttls()
self.s.login(self.__username,self.__password)
......@@ -117,7 +126,7 @@ class Mail(ServiceBase):
# N = self._send(data)
# return(N)
def send(self,data):
def send(self,data,stadotel,stadomail):
types = json.loads(data[Table.type])
info = json.loads(data[Table.info])
msg = MIMEMultipart()
......@@ -138,7 +147,7 @@ class Mail(ServiceBase):
succ[file] = True
#self.s.send_message(msg)
try:
self.Envio(msg,info)
self.Envio(msg,info,stadomail)
except:
print("ROMPIO ALGO EN EL ENVIO")
succ[file] = False
......@@ -151,7 +160,7 @@ class Mail(ServiceBase):
u = self._Mail__username
return(u)
def Envio(self,msg,info):
def Envio(self,msg,info,stadomail):
try:
smtp = info["smtp"]
except:
......@@ -159,11 +168,21 @@ class Mail(ServiceBase):
if smtp == False:
#print(info, type(info))
print("mail sale por default")
self.iniciarConn()
n = self.s.send_message(msg)
else:
print("mail sale por cliente")
self.ControlMail(stadomail,smtp)
n = self.SMTPcliente(msg, smtp)
return(n)
def ControlMail(self,stadomail,smtp):
est = stadomail.ChequearMailServer(User=smtp["username"],
Pass=smtp["password"],
Port=smtp["port"],
Host=smtp["host"])
if est == False:
raise NameError("Mail_Server_Fall")
def SMTPcliente(self,msg, Serversmtp):
print(Serversmtp, type(Serversmtp))
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!