alexarcan

server_proj.py

May 26th, 2016
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.35 KB | None | 0 0
  1. import socket # for sockets
  2. import re # for regex
  3. import picamera
  4. import threading # for threads
  5. import os # for using os.urandom()
  6. import hashlib # for hashing the passwords
  7. import random # for generating random confirmation code
  8. import string # for string.ascii_uppercase and string.digits
  9. import smtplib # for sending mails
  10. import urllib # for reading html files
  11. from email.mime.text import MIMEText
  12.  
  13.  
  14. #######################################################################################
  15. # IMPORTANT NOTES:
  16. #
  17. # -Each message that the server sends to client MUST be ended with \n (flushed)
  18. # Thus a message cannot contain \n because otherwise it will be sent separately
  19. #
  20. #
  21. #
  22. ######################################################################################
  23.  
  24.  
  25. PORT = 5013
  26. APP_NAME = 'AwesomeChatApp'
  27. MAX_EMAIL_CHARS = 50
  28. MIN_USERNAME_CHARS = 5
  29. MAX_USERNAME_CHARS = 20
  30. MIN_PASSWORD_CHARS = 10
  31. MAX_PASSWORD_CHARS = 30
  32. RANDOM_CHARS_COUNT = 32
  33. CONFIRMATION_CODE_LENGTH = 7
  34. EMAIL_FROM = APP_NAME
  35. EMAIL_FROM_ADDRESS = 'artener94@yahoo.com'
  36. SMTP_SERVER = "smtp.mail.yahoo.com"
  37. SMTP_PORT = 587
  38. SMTP_USERNAME = "artener94@yahoo.com"
  39. SMTP_PASSWORD = "Amiga1200"
  40. BUFFER_SIZE=10240
  41.  
  42.  
  43. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  44. server_socket.bind(("", PORT))
  45. server_socket.listen(5)
  46.  
  47. clientThreads = []
  48.  
  49.  
  50. class MessageType:
  51. CLOSE_CONNECTION = 'CLOSE_CONNECTION'
  52. NORMAL_MESSAGE = 'NORMAL_MESSAGE'
  53. QUERY = 'QUERY'
  54. RESPONSE_SUCCESS = 'RESPONSE_SUCCESS'
  55. RESPONSE_FAILED = 'RESPONSE_FAILED',
  56. FRIEND_REQUEST = 'FRIEND_REQUEST'
  57.  
  58.  
  59. class Operation:
  60. CREATE_USER = 'CREATE_USER'
  61. TRY_LOGIN = 'TRY_LOGIN'
  62. VERIFY_CODE = 'VERIFY_CODE'
  63. LOGOUT = 'LOGOUT'
  64. CHECK_FRIEND_REQUESTS = 'CHECK_FRIEND_REQUESTS'
  65. SEND_IMAGE='SEND_IMAGE'
  66.  
  67.  
  68. class ResponseMessage:
  69. NO_FRIEND_REQUESTS = 'NO_FRIEND_REQUESTS'
  70.  
  71.  
  72.  
  73.  
  74. def removeClient(userIDtoRemove):
  75. print 'Removing user with id: ', userIDtoRemove
  76. for index, client in enumerate(clientThreads):
  77. if client.userID == userIDtoRemove:
  78. del clientThreads[index]
  79. print 'client: ', client.userID
  80. print 'index: ', index
  81. print ' has been removed!'
  82. break
  83.  
  84.  
  85.  
  86. def showClients():
  87. print 'Showing the clients...'
  88. for index, client in enumerate(clientThreads):
  89. print 'client: ', client.userID
  90. print 'index: ', index
  91. print ''
  92.  
  93.  
  94.  
  95.  
  96. ### Client thread ###
  97.  
  98.  
  99. class ClientThread(threading.Thread):
  100. userID = None
  101. isOnline = False
  102.  
  103.  
  104. def __init__(self, socket, ip, port):
  105. threading.Thread.__init__(self)
  106.  
  107. self.socket = socket
  108. self.ip = ip
  109. self.port = port
  110.  
  111. print 'New thread started for: %s:%s' % (str(ip), str(port))
  112.  
  113.  
  114. def run(self):
  115.  
  116. while True:
  117.  
  118. print '\nReceiving data from Client...'
  119. data = None
  120. try:
  121. data = self.socket.recv(512)
  122. except:
  123. print 'Connection lost!'
  124. removeClient(self.userID)
  125. break;
  126. print 'Received data: ', data
  127.  
  128. showClients()
  129.  
  130. # extract 'messageType' from the received message
  131. messageTypeAndRest = data.split(':', 1)
  132. messageType = messageTypeAndRest[0]
  133. rest = messageTypeAndRest[1]
  134.  
  135. if messageType == MessageType.CLOSE_CONNECTION:
  136. print 'MessageType is CLOSE_CONNECTION'
  137. print 'Closing connection...'
  138. self.socket.close()
  139. break
  140.  
  141. elif messageType == MessageType.NORMAL_MESSAGE:
  142. print 'MessageType is NORMAL_MESSAGE'
  143.  
  144. elif messageType == MessageType.QUERY:
  145. print 'MessageType is QUERY'
  146. # extract 'operation' from the received message
  147. operationAndParams = messageTypeAndRest[1].split(':', 1)
  148. operation = operationAndParams[0]
  149.  
  150. if operation == Operation.SEND_IMAGE:
  151. # get image
  152. # decompose image in bytes
  153. # in a while loop send 1024 bytes each time
  154. # when nothing to send, exit while
  155. # optional: send message that image has been successfully sent
  156.  
  157. #activez camera si fac poza
  158. #stochez poza pe disk in acelasi folder cu server_proj.py + extensia .png
  159. #filename4324.png, filename142.png (random)
  160. #SAU VEZI DACA SE SUPRASCRIE POZA si ii spun captured_image.png
  161. print("About to take a picture.");
  162. with picamera.PiCamera() as camera:
  163. camera.capture("poza.png")
  164. print("Picture taken.")
  165. avatar_file = open("poza.png", "rb")
  166. avatar_file_bytes = avatar_file.read(BUFFER_SIZE)
  167. while (avatar_file_bytes):
  168. print 'Sending %s bytes...', BUFFER_SIZE
  169. send_message = '%s%s' % (avatar_file_bytes, '\n')
  170. self.socket.send(avatar_file_bytes)
  171. avatar_file_bytes = avatar_file.read(BUFFER_SIZE)
  172. data = self.socket.recv(512)
  173. print 'Received data: ', data
  174.  
  175. print 'file opened!'
  176. avatar_file.close()
  177. responseMsj='Picture successully sent!\n'
  178. response = '%s:%s' % (MessageType.RESPONSE_SUCCESS, responseMsj)
  179. self.socket.send(response)
  180.  
  181.  
  182.  
  183.  
  184. print 'Connection has been closed.'
  185.  
  186.  
  187. print "TCPServer Waiting for client on port ", PORT
  188.  
  189.  
  190. """
  191. Accept for connecions and for each
  192. connection create a Client socket
  193. """
  194. while True:
  195. (client_socket, (ip, port)) = server_socket.accept()
  196. print "I got a connection from %s:%s" % (str(ip), str(port))
  197.  
  198. newThread = ClientThread(client_socket, ip, port)
  199. newThread.start()
  200. clientThreads.append(newThread)
Add Comment
Please, Sign In to add comment