Advertisement
Guest User

SocketCliente.py

a guest
Feb 11th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.72 KB | None | 0 0
  1. import socket
  2. import threading
  3. import os
  4. import time
  5. import datetime
  6. import math
  7. import json
  8. import sys
  9.  
  10. #registroUsuario = True
  11.  
  12. #import Cliente.LlenarBaseCliente
  13. #import Cliente.Interfaz.Cliente
  14.  
  15. import ConfigBaseCliente
  16. import ModeloCliente
  17. import Interfaz.Login
  18. import Interfaz.Chat
  19.  
  20.  
  21. #global rcv, snd, sckt, chat, ventanaChat, ventanaLogin
  22.  
  23. class Chat(threading.Thread):
  24.     def __init__(self, sckt, ventanaChat, deltaTime):
  25.         super(Chat, self).__init__()
  26.  
  27.         self.rcv = Receive(sckt, ventanaChat, deltaTime)
  28.         self.snd = Send(sckt)
  29.  
  30.     def stop_children(self):
  31.         self.rcv.fin = True
  32.         self.snd.fin = True
  33.  
  34.     def run(self):
  35.         self.rcv.start()
  36.         self.snd.start()
  37.         self.rcv.join()
  38.         self.snd.join()
  39.         print('finalizo el chat')
  40.         #exit_handler()
  41.  
  42. class Archivo():
  43.     def __init__(self, ext, packages, name):
  44.         self.packages = packages
  45.         self.ext = ext
  46.         self.file = None
  47.         self.name = ''
  48.         self.nbuffer = 0
  49.         self.name = name
  50.         self.iniciarBuffer()
  51.  
  52.  
  53.     def iniciarBuffer(self, folder = r'./archivosCompartidos'):
  54.         newpath = folder + '/' + self.name
  55.         print(newpath)
  56.         if not os.path.exists(newpath):
  57.             os.makedirs(newpath)
  58.         self.name = newpath + '/' + datetime.datetime.now().strftime("%Y%m%d%H%M%S")+'.'+self.ext
  59.         self.file = open(self.name, 'wb')
  60.         print('me he creado', newpath)
  61.  
  62.     def actualizarInfo(self, info):
  63.         self.file.write(info)
  64.         self.nbuffer += 1
  65.         print('voy en : ', self.nbuffer)
  66.         if self.nbuffer == int(self.packages):
  67.             self.file.close()
  68.             print('Ya tengo todos los paquetes, soy : ', self.name)
  69.             print('\n\n##############################################################################\n\n')
  70.  
  71. class Receive(threading.Thread):
  72.     def __init__(self, skt, ventanaChat, deltaTime):
  73.         super(Receive, self).__init__()
  74.         self.skt = skt
  75.         self.archi = None
  76.         self.fin = False
  77.         self.message = ''
  78.         self.ventanaChat = ventanaChat
  79.         self.deltaTime = deltaTime
  80.         self.hora = time.localtime(time.time())
  81.         self.actualizarHora()
  82.  
  83.     def recibirArchivo(self, message):
  84.         message = message.split('uwu'.encode())
  85.         #byte:232323:png:3
  86.         print('archi: ',self.archi.packages, self.archi.nbuffer)
  87.         print('mes: ', message)
  88.  
  89.         if self.archi:
  90.             if self.archi.packages == message[1].decode() and self.archi.ext == message[2].decode() and self.archi.nbuffer == int(message[3].decode()):
  91.                 self.archi.actualizarInfo(message[0])
  92.  
  93.     def actualizarHora(self):
  94.         desfase = self.deltaTime.split(":")
  95.         desfase = [int(i) for i in desfase]
  96.         self.hora = time.localtime(time.time())
  97.         self.hora = "["+str(self.hora[3]+desfase[0])+":"+str(self.hora[4]+desfase[1])+":"+str(self.hora[5]+desfase[2])+"]"
  98.  
  99.     def run(self):
  100.         self.message = ''
  101.         while not self.fin:
  102.             self.message = self.skt.recv(1024)
  103.             #serv:typeOfService:[info]
  104.             if self.message:
  105.                 print('Ha llegado un mensaje: \t')
  106.                 #print('->> \t',self.message.decode())
  107.                 data = self.message.split(':'.encode(), 2)
  108.                 print('\t',data)
  109.                 owner = data[0]
  110.                 if owner.decode() == 'sv':
  111.                     typeOfService = data[1].decode()
  112.                     if typeOfService == 'rf':
  113.                         self.recibirArchivo(data[2])
  114.                     elif typeOfService == 'fileInfo':
  115.                         self.message = data[2].decode().split(':')
  116.                         self.archi = Archivo(message[0],message[1],message[2])
  117.                         #print('instancia de archi')
  118.                     elif typeOfService == 'fileReceived':
  119.                         self.message = data[2].decode()
  120.                         if ventanaChat:
  121.                             #mostrar el link de descarga en la vista de chat
  122.                             pass
  123.                     elif typeOfService == 'exitAccepted':
  124.                         self.fin = True
  125.  
  126.                     elif typeOfService == 'updateUsersEntry':
  127.                         infoUser = data[2].decode()
  128.                         print("######### oyeeee ya voy a tengo la info del usuario #########3")
  129.                         infoUser = json.loads(infoUser)
  130.                         print(type(infoUser))
  131.                         print("######### oyeeee ya voy a emitir la info a la señal #########3")
  132.                         self.ventanaChat.entro.emit(infoUser)
  133.                         #self.ventanaChat.entrousuariosignal(infoUser)
  134.  
  135.                     elif typeOfService == 'updateUsersExit':
  136.                         infoUser = data[2].decode()
  137.                         print("######### oyeeee ya voy a tengo la info del usuario #########3")
  138.                         infoUser = json.loads(infoUser)
  139.                         print(type(infoUser))
  140.                         print("######### oyeeee ya voy a emitir la info a la señal #########3")
  141.                         self.ventanaChat.salio.emit(infoUser)
  142.  
  143.                 else:
  144.                     self.message =':'.encode().join(data).decode().split(":",1)
  145.                     print(self.message)
  146.                     mensaje = self.message[1]
  147.                     user = self.message[0]
  148.                     print("user ->> "+ user)
  149.                     self.actualizarHora()
  150.                     cosas = {}
  151.                     cosas['hora'] = self.hora
  152.                     cosas['usuario'] = user
  153.                     cosas['mensaje'] = mensaje
  154.                     self.ventanaChat.escribio.emit(cosas)
  155.                     #print("Hilo: "+self.message, type(self.message))
  156.  
  157.         print('deje de recibir')
  158.  
  159. class Send(threading.Thread):
  160.     def __init__(self, skt):
  161.         super(Send, self).__init__()
  162.         self.skt = skt
  163.         self.masaje = ''
  164.         self.fin = False
  165.  
  166.     def run(self):
  167.         self.masaje = ''
  168.         while not self.fin:
  169.             if self.masaje != '':
  170.                 if self.masaje == 'okis':
  171.                     # se añaden ':' para hacer split
  172.                     self.masaje += ':**'
  173.                 else:
  174.                     self.masaje += ':*'
  175.                 #masaje = '' # Provisional para que no ocurra ningun error
  176.                
  177.                 print("---> : "+self.masaje)
  178.                 self.skt.send(self.masaje.encode('UTF-8'))
  179.                 #enviar la informacion del archivo adjunto
  180.                 if self.masaje == '#exit:*':
  181.                     break
  182.                 self.masaje = ''
  183.         print('deje de enviar')
  184.  
  185. class Cliente():
  186.     def __init__(self):
  187.         self.rcv = None
  188.         self.snd = None
  189.         self.sckt = None
  190.         self.chat = None
  191.         self.ventanaChat = None
  192.         self.ventanaLogin = None
  193.         self.deltatime = None
  194.         self.InitializeSocket()
  195.         self.Login()
  196.  
  197.     def InitializeSocket(self):
  198.         self.sckt = socket.socket()
  199.         self.sckt.connect(("192.168.0.102", 8092))
  200.         print(self.sckt)
  201.         hora = time.localtime(time.time())[3:6]
  202.         mensaje = '*Updthur:'+str(hora[0])+":"+str(hora[1])+":"+str(hora[2])
  203.         self.sckt.send(mensaje.encode())
  204.         self.deltatime = self.sckt.recv(1024).decode()
  205.  
  206.     def llenarBase(self):
  207.         estados = ConfigBaseCliente.sessioncliente.query(ModeloCliente.Estados).all()
  208.         if len(estados) == 0:
  209.             #print(estados)
  210.             estado1 = ModeloCliente.Estados(Descripcion='Mensaje no llegó al servidor.')
  211.             ConfigBaseCliente.sessioncliente.add(estado1)
  212.             estado2 = ModeloCliente.Estados(Descripcion='Mensaje llegó al servidor.')
  213.             ConfigBaseCliente.sessioncliente.add(estado2)
  214.             estado3 = ModeloCliente.Estados(Descripcion='Mensaje no llegó al cliente.')
  215.             ConfigBaseCliente.sessioncliente.add(estado3)
  216.             estado4 = ModeloCliente.Estados(Descripcion='Mensaje llegó al cliente.')
  217.             ConfigBaseCliente.sessioncliente.add(estado4)
  218.             ConfigBaseCliente.sessioncliente.commit()
  219.  
  220.     def Login(self):
  221.         Interfaz.Login.main(self)
  222.  
  223.     def verificarDatosVentanaOlvidoClave(self, ventana):
  224.  
  225.         usuario = ventana.olvidoVentana.lineEditUsuario.text()
  226.         respuestaSecreta = ventana.olvidoVentana.lineEditRespuesta.text()
  227.         mensaje = '*' + 'RC'+':'+usuario+':'+respuestaSecreta
  228.         print("******** voy a enviar la info *************")
  229.         self.sckt.send(mensaje.encode('UTF-8'))
  230.         print("******** ya envié la info *************")
  231.         error = self.sckt.recv(1024).decode('UTF-8')
  232.         print("******** ya ya recibí una respuesta *************")
  233.         if error[:5] != 'error':
  234.             ventana.olvidoVentana.hide()
  235.             ventana.olvidoVentana.deleteLater()
  236.             ventana.ventana_clave_nueva(usuario)
  237.         else:
  238.             ventana.olvidoVentana.labelError.setText(error[5:])
  239.             ventana.olvidoVentana.labelError.show()
  240.  
  241.     def editarDatosCuenta(self, ventana, campo, datos):
  242.         if campo == 'Sexo':
  243.             if ventana.ventanaEditarDatos.widget.widget.radioButtonMasculino.isChecked() == True:
  244.                 datos = 'Masculino'
  245.             else:
  246.                 datos = 'Femenino'
  247.         mensaje = '*ED:'+campo+':'+str(datos)
  248.         print(mensaje)
  249.         self.sckt.send(mensaje.encode())
  250.         time.sleep(0.5)
  251.         error = self.chat.rcv.message
  252.         print(error)
  253.         if error[:5] != 'error': #si no hay error es porque se guardó
  254.             print('se ha actualizado el campo' + campo)
  255.             if campo == 'Nombre':
  256.                 Interfaz.Chat.actualizarVistaEditarNombre(ventana, datos)
  257.             elif campo == 'Sexo':
  258.                 Interfaz.Chat.actualizarVistaEditarSexo(ventana, datos)
  259.             elif campo == 'Fecha':
  260.                 Interfaz.Chat.actualizarVistaEditarFecha(ventana, datos)
  261.             elif campo == 'Clave':
  262.                 Interfaz.Chat.actualizarVistaEditarClave(ventana)
  263.             elif campo == 'Respuesta':
  264.                 Interfaz.Chat.actualizarVistaEditarRespuesta(ventana)
  265.         else:
  266.             if campo == 'Clave':
  267.                 Interfaz.Chat.verificacion1(ventana.ventanaEditarDatos.widget.widget2, 'EditarClave Nofocus', None)
  268.                 ventana.ventanaEditarDatos.widget.widget2.labelClaveError.setText("Contraseña actual incorrecta.")
  269.             else:
  270.                 print('ha ocurrido un error')
  271.  
  272.     def controladorInicioSesion(self, ventana):
  273.  
  274.         nickname = ventana.lineEditUsuario.text()
  275.         password = ventana.lineEditPassword.text()
  276.  
  277.         mensaje = '*'+'DC'+':'+nickname+':'+password
  278.         self.sckt.send(mensaje.encode('UTF-8'))
  279.         error = self.sckt.recv(1024).decode('UTF-8')
  280.         if error[:5] != 'error': #Si no hay error llegan los datos en el error
  281.             datos = error.split('<>')
  282.             print(datos)
  283.             user = json.loads(datos[0])
  284.             room = json.loads(datos[1])
  285.             room['owner']='Sistema'
  286.             usersRoom = json.loads(datos[2])
  287.             ventana.hide()
  288.             ventana.deleteLater()
  289.             ConfigBaseCliente.main()
  290.             self.llenarBase()
  291.             self.sckt.send('*IS'.encode('UTF-8'))
  292.             self.ventanaChat = Interfaz.Chat.Ventana_Principal(self)
  293.             self.ventanaChat.constructor(user,room,usersRoom,None,None) #--Enviar Parámetros. (usuario-->dict, sala-->dict, usuariosSala-->list[dicts], usuariosMensajesPrivados-->list[dicts], mensajesPrivados-->list[dicts]):
  294.             self.ventanaChat.setIndexTab(0)
  295.             self.ventanaChat.show()
  296.             #b.show()
  297.             self.chat = Chat(self.sckt, self.ventanaChat, self.deltatime)
  298.             self.chat.start()
  299.         else:
  300.             ventana.labelError.setText(error[5:])
  301.             ventana.labelError.show()
  302.  
  303.     def controladorRegistro(self, ventana):
  304.  
  305.         nombreCompleto = ventana.ventanaRegistro.widget.widget.lineEditNombre.text()
  306.         nickname = ventana.ventanaRegistro.widget.widget.lineEditNickname.text()
  307.         password = ventana.ventanaRegistro.widget.widget2.lineEditClave.text()
  308.         respuestaSecreta = ventana.ventanaRegistro.widget.widget2.lineEditRespuesta.text()
  309.         fecha = ventana.ventanaRegistro.widget.widget.dateEditFechaNacimiento.date().toString('dd/MM/yyyy')
  310.         sexo = None
  311.         if ventana.ventanaRegistro.widget.widget.radioButtonMasculino.isChecked() == True:
  312.             sexo ='Masculino'
  313.         else:
  314.             sexo='Femenino'
  315.         mensaje = '*'+'DR'+':'+nombreCompleto+':'+nickname+':'+password+':'+respuestaSecreta+':'+sexo+':'+fecha
  316.         self.sckt.send(mensaje.encode('UTF-8'))
  317.         error = self.sckt.recv(1024).decode('UTF-8')
  318.         if error[:5] != 'error':
  319.             ventana.ventanaRegistro.hide()
  320.             ventana.ventanaRegistro.deleteLater()
  321.             ventana.alerta('Registro exitoso.')
  322.         else:
  323.             ventana.ventanaRegistro.widget.widget.labelErrorNickname.setText(error[5:])
  324.             ventana.ventanaRegistro.widget.widget.labelErrorNickname.show()
  325.  
  326.     def controladorNuevaClave(self, ventana):
  327.  
  328.         clave = ventana.claveNuevaVentana.lineEditClave.text()
  329.         mensaje = '*'+'NC'+':'+clave
  330.         self.sckt.send(mensaje.encode('UTF-8'))
  331.         ventana.claveNuevaVentana.hide()
  332.         ventana.claveNuevaVentana.deleteLater()
  333.         ventana.alerta('Contraseña modificada con éxito.')
  334.         error = self.sckt.recv(1024).decode('UTF-8')
  335.  
  336.     def controladorEnviarArchivos(self, archivo):
  337.  
  338.         #enviar byte por byte con el tamaño total, el tipo de archivo, y que parte se envía
  339.         #byte:232323:png:3
  340.         nombreArchivo = archivo.split('/')[-1]
  341.         tipo = nombreArchivo.split('.')[-1]
  342.         print('\n\n##############################################################################\n\n')
  343.         archi = open(archivo,'rb')
  344.         info = archi.read()
  345.         size = len(info)
  346.         total = 6 + 5 + len(tipo) + len('uwu'*3) + 5 #solo se pueden enviar archivos de máximo 100mb
  347.         step = 1024 - total
  348.         nsends = math.ceil(size/step)
  349.         #sckt.send('*PART:'.encode() + info)
  350.         mensajeArchivo = '*EN:'+tipo+':'+str(nsends)
  351.         #print(mensajeArchivo)
  352.         print('Tengo el mensaje listo para enviar')
  353.         self.sckt.send(mensajeArchivo.encode())
  354.         print('Se ha enviado el mensaje de informacion')
  355.         time.sleep(0.5)
  356.         print('Hey :', nsends, step)
  357.         for i in range(nsends):
  358.             encd = '*PART:'.encode() + info[i*step:(i+1)*step] + 'uwu'.encode() + str(nsends).encode() + 'uwu'.encode() + tipo.encode() + 'uwu'.encode() + str(i).encode()
  359.             #print(encd.split('uwu'.encode()))
  360.             time.sleep(0)
  361.             self.sckt.send(encd)
  362.         print('Se han enviado todas las partes')
  363.         print('\n\n##############################################################################\n\n')
  364.         archi.close()
  365.         print('se ha cerrado el archivo')
  366.  
  367.     def controladorRecibirArchivos(self, archivo):
  368.         pass
  369.  
  370.     def consultarInformacionUsuario(self, ventana):
  371.         mensaje = "*ReqInfo:"
  372.         self.sckt.send(mensaje.encode())
  373.         time.sleep(0.1)
  374.         error = self.chat.rcv.message
  375.         print("Respuesta del servidor: "+error+" : Fin del mensaje")
  376.         error = json.loads(error)
  377.         #print(type(error))
  378.         ventana.informacionusuarioventana(error)
  379.  
  380.     def controladorComandos(self, comando):
  381.         self.chat.snd.masaje = comando
  382.  
  383.     def controladorMensajesEnviar(self, ventana):
  384.         self.chat.rcv.ventanaChat = ventana
  385.         self.chat.snd.masaje = ventana.tabSala.lineEditChat.text()
  386.         print(ventana.tabSala.lineEditChat.text())
  387.         ventana.tabSala.lineEditChat.setText("")
  388.  
  389.     def cerrarSesionChat(self, ventana, crearventana = True):
  390.         self.chat.stop_children()
  391.         mensaje = '*RUSS:'
  392.         self.sckt.send(mensaje.encode())
  393.         if os.path.exists("cliente.db"):
  394.             ConfigBaseCliente.sessioncliente.close()
  395.             os.remove("cliente.db")
  396.         else:
  397.             print("No existe la base de datos")
  398.         ventana.hide()
  399.         ventana.deleteLater()
  400.         #error = sckt.recv(1024).decode()
  401.         #print(error)
  402.         if crearventana:
  403.             self.ventanaLogin = Interfaz.Login.Ventana_Login(self)
  404.             self.ventanaLogin.show()
  405.  
  406.     def salirChat(self, ventana):
  407.         self.cerrarSesionChat(ventana, False)
  408.         self.salir(ventana)
  409.  
  410.     def salir(self, ventana):
  411.         #matar el sckt
  412.         mensaje = '#exit*'
  413.         self.sckt.send(mensaje.encode('UTF-8'))
  414.         time.sleep(1)
  415.         self.sckt.shutdown(socket.SHUT_RDWR)
  416.         self.sckt.close()
  417.         print("Me cerré")
  418.         ventana.hide()
  419.         ventana.deleteLater()
  420.         sys.exit()
  421.  
  422. if __name__ == "__main__":
  423.     cliente = Cliente()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement