Advertisement
Guest User

chat_program_server_code

a guest
Jan 10th, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 22.50 KB | None | 0 0
  1. import socket
  2. import threading
  3. from time import sleep
  4. import os
  5. from passlib.hash import pbkdf2_sha256
  6. import pickle
  7.  
  8. # Let the user know when they have unread DM's
  9. # Add ability to delete account.
  10. # Up to date version as of 7/1/19
  11.  
  12. class ChatServer:
  13.     def __init__(self):
  14.         self.host = '127.0.0.1'
  15.         self.port = 9003
  16.         self.starting_dir = os.getcwd()
  17.         self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  18.         self.server.bind((self.host, self.port))
  19.         self.user_directory = {}
  20.         self.ports_taken = []
  21.         self.chat_logs = []
  22.         self.check_for_user_directory()
  23.         self.listen()
  24.  
  25.     def check_for_user_directory(self):  #Checks that '.user' is in the script's executing directory.
  26.         if '.users' in os.listdir():
  27.             pass
  28.         else:
  29.             os.mkdir('.users')
  30.  
  31.     def listen(self):
  32.         self.server.listen(5)
  33.         while True:
  34.             print(self.ports_taken)
  35.             print('Server running!')
  36.             c, addr = self.server.accept()
  37.             print('Connection from {}'.format(addr))
  38.             self.handle_client(c)
  39.             # handle_information_thread = threading.Thread(target=self.handle_client(c))
  40.             # handle_information_thread.start()
  41.  
  42.     def create_new_account(self, username, password, client):  # Sets up a new account
  43.         os.chdir('.users')
  44.         if username in os.listdir():
  45.             client.sendall(b'Username already taken!')
  46.         else:
  47.             username = '.' + username
  48.             os.mkdir(username)
  49.             hashed_password = pbkdf2_sha256.hash(password)
  50.             os.chdir(username)
  51.             with open('.info', 'wb') as doc:
  52.                 pickle.dump(hashed_password, doc)
  53.             os.mkdir('.messages')
  54.             os.mkdir('.outgoing requests')
  55.             os.mkdir('.incoming requests')
  56.             with open('.friends', 'x') as doc:
  57.                 pass
  58.             client.sendall(b'Account has been made!')
  59.             client.close()
  60.             os.chdir(self.starting_dir)
  61.             self.listen()
  62.  
  63.     def verify_account_details(self, username, password, client):  # Verifies the username and password the user has entered is correct
  64.         os.chdir('.users')
  65.         username = '.' + username
  66.         print(username)
  67.         print(os.listdir())
  68.         if username in os.listdir():
  69.             print('Account was found!')
  70.             os.chdir(username)
  71.             with open('.info', 'rb') as doc:
  72.                 hashed_p = pickle.load(doc)
  73.             verification = pbkdf2_sha256.verify(password, hashed_p)
  74.             print(verification)
  75.             if verification is True:
  76.                 client.sendall(b'Password Confirmed!')
  77.             elif verification is False:
  78.                 client.sendall(b'Credential Error!')
  79.             os.chdir(self.starting_dir)
  80.             client.close()
  81.             self.listen()
  82.         else:
  83.             print('Account not found!')
  84.             client.sendall(b'Account not found!')
  85.             client.close()
  86.             os.chdir(self.starting_dir)
  87.             self.listen()
  88.  
  89.     def send_message(self, to_user, from_user, message, client):  # Sends a message to another user and saves it.
  90.         '''This function is responsible for sending messages
  91.        from one user to another. to_user is the recipient for the message,
  92.        from_user is the sender of the message.'''
  93.         message = '{}: {}'.format(from_user, message)
  94.         to_user = '.' + to_user
  95.         from_user = '.' + from_user
  96.         os.chdir('.users')
  97.         if to_user in os.listdir():
  98.             '''
  99.            This runs when to_user was found in the .users folder.
  100.            The message sent by from_user is stored in a log in both their folders.
  101.            '''
  102.             os.chdir(to_user)
  103.             os.chdir('.messages')
  104.             file_name = '{} DM LOG'.format(from_user)
  105.             if file_name in os.listdir():
  106.                 with open(file_name, 'r') as doc:
  107.                     chat_logs = doc.read()
  108.                 with open(file_name, 'w') as doc:
  109.                     doc.write(chat_logs)
  110.                     doc.write('\n')
  111.                     doc.write(message)
  112.             else:
  113.                 with open(file_name, 'w') as doc:
  114.                     doc.write(message)
  115.             os.chdir(self.starting_dir)
  116.             os.chdir('.users')
  117.             os.chdir(from_user)
  118.             os.chdir('.messages')
  119.             new_file_name = '{} DM LOG'.format(to_user)
  120.             if new_file_name in os.listdir():
  121.                 with open(new_file_name, 'r') as doc:
  122.                     file_content = doc.read()
  123.                 with open(new_file_name, 'w') as doc:
  124.                     doc.write(file_content)
  125.                     doc.write('\n')
  126.                     doc.write(message)
  127.             else:
  128.                 with open(new_file_name, 'w') as doc:
  129.                     doc.write(message)
  130.             client.sendall(b'Message has been sent!')
  131.             client.close()
  132.             os.chdir(self.starting_dir)
  133.             self.listen()
  134.  
  135.         else:
  136.             print('User was not found!')
  137.             client.sendall(b'User not found!')
  138.             client.close()
  139.             os.chdir(self.starting_dir)
  140.             self.listen()
  141.  
  142.     def get_dm_list(self, username, client):  # Returns the people that the user has messaged.
  143.         username = '.' + username
  144.         try:
  145.             os.chdir('.users')
  146.             os.chdir(username)
  147.             os.chdir('.messages')
  148.             chat_log_items = os.listdir()
  149.             if len(chat_log_items) == 0:
  150.                 client.sendall(b'You have no chat logs!')
  151.                 sleep(1)
  152.                 client.sendall( b'FINISH')
  153.             else:
  154.                 for item in os.listdir():
  155.                     print(item)
  156.                     client.sendall(str.encode(item))
  157.                     sleep(1)
  158.                 sleep(1)
  159.                 client.sendall(b'FINISH')
  160.                 client.close()
  161.                 os.chdir(self.starting_dir)
  162.                 self.listen()
  163.         except FileNotFoundError:
  164.             print('One of the files was not found!')
  165.             client.sendall(b'Error.')
  166.             client.close()
  167.             os.chdir(self.starting_dir)
  168.             self.listen()
  169.  
  170.     def get_chat_history(self, username, chat_log, client):  #Gets the DM history between two user's
  171.         try:
  172.             os.chdir('.users')
  173.             os.chdir(username)
  174.             os.chdir('.messages')
  175.             chat_log = '.' + chat_log
  176.             found = 0
  177.             for item in os.listdir():
  178.                 if chat_log in item:
  179.                     found += 1
  180.                     with open(item, 'r') as doc:
  181.                         file_content = doc.read()
  182.             if found == 0:
  183.                 client.sendall(b'User not found')
  184.                 client.close()
  185.                 os.chdir(self.starting_dir)
  186.                 self.listen()
  187.             else:
  188.                 print(file_content)
  189.                 client.sendall(str.encode(file_content))
  190.                 client.close()
  191.                 os.chdir(self.starting_dir)
  192.                 self.listen()
  193.         except FileNotFoundError:
  194.             client.sendall(b'Error.')
  195.             client.close()
  196.             os.chdir(self.starting_dir)
  197.             self.listen()
  198.  
  199.     def send_friend_request(self, username, friend_username, client_obj):  # Sends a friend request from one user to the other.
  200.         '''
  201.        Sends a friend request from user1 to user2.
  202.        '''
  203.  
  204.         username = '.' + username
  205.         friend_username = '.' + friend_username
  206.         os.chdir('.users')
  207.         if username in os.listdir():
  208.             user_dir = os.getcwd()
  209.             os.chdir(username)
  210.             with open('.friends', 'r') as doc:
  211.                 content = doc.read()
  212.             if friend_username in content:
  213.                 client_obj.sendall(b'That user is already your friend!')
  214.                 client_obj.close()
  215.                 os.chdir(self.starting_dir)
  216.                 self.listen()
  217.             else:
  218.                 os.chdir(user_dir)
  219.                 if friend_username in os.listdir():
  220.                     os.chdir(username)
  221.                     os.chdir('.outgoing requests')
  222.                     incoming_requests_file_name = friend_username
  223.                     with open(incoming_requests_file_name, 'w') as doc:
  224.                         doc.write('Pending')
  225.                     os.chdir(user_dir)
  226.                     os.chdir(friend_username)
  227.                     os.chdir('.incoming requests')
  228.                     file_name = username
  229.                     with open(file_name, 'w') as doc:
  230.                         doc.write('Not Accepted')
  231.                     os.chdir(self.starting_dir)
  232.                     response = 'Friend request sent to {}'.format(friend_username)
  233.                     client_obj.sendall(str.encode(response))
  234.                     client_obj.close()
  235.                     self.listen()
  236.         else:
  237.             client_obj.sendall(b'The user that you entered was not found!')
  238.  
  239.     def get_friends_list(self, client_username, client_obj):  # Returns the user's friendlist
  240.         client_username = '.' + client_username
  241.         os.chdir('.users')
  242.         os.chdir(client_username)
  243.         with open('.friends', 'r') as doc:
  244.             content = doc.read()
  245.         if len(content) == 0:
  246.             client_obj.sendall(b'No friends...')
  247.             client_obj.close()
  248.             os.chdir(self.starting_dir)
  249.             self.listen()
  250.         else:
  251.             client_obj.sendall(str.encode(content))
  252.             os.chdir(self.starting_dir)
  253.             client_obj.close()
  254.             self.listen()
  255.  
  256.     def view_incoming_requests(self, username, client_obj):  # Allows the user to see all incoming requests from the '.incoming requests' directory
  257.         username = '.' + username
  258.         os.chdir('.users')
  259.         if username in os.listdir():
  260.             os.chdir(username)
  261.             os.chdir('.incoming requests')
  262.             items = os.listdir()
  263.             if len(items) == 0:
  264.                 client_obj.sendall(b'You have no incoming friend requests!')
  265.                 sleep(1)
  266.                 client_obj.sendall(b'FINISH')
  267.                 client_obj.close()
  268.                 os.chdir(self.starting_dir)
  269.                 self.listen()
  270.             else:
  271.                 for item in os.listdir():
  272.                     info = 'Friend request from {}'.format(item)
  273.                     client_obj.sendall(str.encode(info))
  274.                     sleep(1)
  275.                 sleep(1)
  276.                 client_obj.sendall(b'FINISH')
  277.                 client_obj.close()
  278.                 os.chdir(self.starting_dir)
  279.                 self.listen()
  280.         else:
  281.             client_obj.sendall(b'Your username was not found! Make sure that your username is valid.')
  282.  
  283.     def view_outgoing_requests(self, username, client_obj):  #Views all requests in the '.outgoing requests directory'
  284.         os.chdir('.users')
  285.         username = '.' + username
  286.         if username in os.listdir():
  287.             os.chdir(username)
  288.             os.chdir('.outgoing requests')
  289.             items = os.listdir()
  290.             if len(items) == 0:
  291.                 client_obj.sendall(b'You have no outgoing requests!')
  292.                 sleep(1)
  293.                 client_obj.sendall(b'FINISH')
  294.                 client_obj.close()
  295.                 os.chdir(self.starting_dir)
  296.                 self.listen()
  297.             else:
  298.                 for item in os.listdir():
  299.                     info = 'Friend request to {}'.format(item)
  300.                     client_obj.sendall(str.encode(info))
  301.                     sleep(1)
  302.                 sleep(1)
  303.                 client_obj.sendall(b'FINISH')
  304.                 client_obj.close()
  305.                 os.chdir(self.starting_dir)
  306.                 self.listen()
  307.         else:
  308.             client_obj.sendall(b'Your username was not found! Make sure that your username is valid.')
  309.             client_obj.close()
  310.             os.chdir(self.starting_dir)
  311.             self.listen()
  312.  
  313.     def accept_friend_request(self, username, user_to_accept, client_obj):  # Accepts a friend request from another user.
  314.         username = '.' + username
  315.         user_to_accept = '.' + user_to_accept
  316.         os.chdir('.users')
  317.         os.chdir(username)
  318.         user_direc = os.getcwd()
  319.         os.chdir('.incoming requests')
  320.         if user_to_accept in os.listdir():
  321.             os.remove(user_to_accept)
  322.             os.chdir(user_direc)
  323.             with open('.friends', 'r') as doc:
  324.                 content = doc.read()
  325.             with open('.friends', 'w') as doc:
  326.                 doc.write(content)
  327.                 doc.write('\n')
  328.                 doc.write(user_to_accept)
  329.             os.chdir(self.starting_dir)
  330.             os.chdir('.users')
  331.             os.chdir(user_to_accept)
  332.             user_direc = os.getcwd()
  333.             os.chdir('.outgoing requests')
  334.             os.remove(username)
  335.             os.chdir(user_direc)
  336.             with open('.friends', 'r') as doc:
  337.                 content = doc.read()
  338.             with open('.friends', 'w') as doc:
  339.                 doc.write(content)
  340.                 doc.write('\n')
  341.                 doc.write(username)
  342.             os.chdir(self.starting_dir)
  343.             information_to_send_back = '{} is now your friend'.format(user_to_accept)
  344.             client_obj.sendall(str.encode(information_to_send_back))
  345.             client_obj.close()
  346.             self.listen()
  347.  
  348.         else:
  349.             client_obj.sendall(b'User did not send you a friend request!')
  350.             client_obj.close()
  351.             os.chdir(self.starting_dir)
  352.             self.listen()
  353.  
  354.     def remove_user(self, username, user_to_remove, client):  # Removes user from friend list
  355.         username = '.' + username
  356.         user_to_remove = '.' + user_to_remove
  357.         os.chdir('.users')
  358.         if user_to_remove in os.listdir():
  359.             os.chdir(username)
  360.             with open('.friends', 'r') as doc:
  361.                 content = doc.readlines()
  362.             for item in content:
  363.                 print(item)
  364.         else:
  365.             client.sendall(b'That user was not found!')
  366.  
  367.     def handle_client(self, client):
  368.         '''
  369.        This function is run in a separate thread to the listening() function.
  370.        This thread retrieves the user request, then listens for necessary information to complete the user's request,
  371.        then does the necessary things to complete the user request and sends a response to the client.
  372.        '''
  373.         threading.Thread(target=self.listen).start()
  374.         while True:
  375.             user_choice = client.recv(1024)
  376.             print(user_choice)
  377.             if user_choice:
  378.                 if user_choice.decode() == 'SENDMESSAGE': # If the user sends' SENDMESSAGE' then the server knows the user wants to send a message to another user!
  379.                     print('User wants to send a message to another user!')
  380.                     while True:
  381.                         client_username = client.recv(1024) # Gets the username of the sender!
  382.                         if client_username:
  383.                             client_username = client_username.decode()
  384.                             print(client_username)
  385.                             while True:
  386.                                 to_user = client.recv(1024) # Gets the username of the recipient
  387.                                 if to_user:
  388.                                     to_user = to_user.decode()
  389.                                     print(to_user)
  390.                                     while True:
  391.                                         message_to_send = client.recv(1024)
  392.                                         if message_to_send:
  393.                                             message_to_send = message_to_send.decode()
  394.                                             print(message_to_send)
  395.                                             self.send_message(to_user, client_username, message_to_send, client)
  396.  
  397.                 elif user_choice.decode() == 'CRTACC':  # This executes when the user wants to create a new account.
  398.                     print('User wants to create account!')
  399.                     while True:
  400.                         new_username = client.recv(1024)
  401.                         if new_username:
  402.                             new_username = new_username.decode()
  403.                             print(new_username)
  404.                             while True:
  405.                                 new_password = client.recv(1024)
  406.                                 if new_password:
  407.                                     new_password = new_password.decode()
  408.                                     print(new_password)
  409.                                     self.create_new_account(new_username, new_password, client)
  410.                 elif user_choice.decode() == 'SIGNIN':  # The following code executs when  the user sends 'SIGNIN' to the server. This means the user is wanting to sign into their account.
  411.                     print('User wants to sign into an existing account!')
  412.                     while True:
  413.                         username = client.recv(1024)
  414.                         if username:
  415.                             username = username.decode()
  416.                             print(username)
  417.                             while True:
  418.                                 password = client.recv(1024)
  419.                                 if password:
  420.                                     password = password.decode()
  421.                                     print(password)
  422.                                     self.verify_account_details(username, password, client)
  423.                 elif user_choice.decode() == 'GETCHATLIST':
  424.                     print('User wants to check chat log!')
  425.                     while True:
  426.                         username = client.recv(1024)
  427.                         if username:
  428.                             username = username.decode()
  429.                             print(username)
  430.                             self.get_dm_list(username, client)
  431.                 elif user_choice.decode() == 'GETCHATHISTORY':
  432.                     print('User wants to check their chat history!')
  433.                     while True:
  434.                         username = client.recv(1024)
  435.                         if username:
  436.                             username = username.decode()
  437.                             username = '.' + username
  438.                             while True:
  439.                                 chat_log_to_check = client.recv(1024)  # This should get a username of the chat log the user is wanting to check.
  440.                                 if chat_log_to_check:
  441.                                     chat_log_to_check = chat_log_to_check.decode()
  442.                                     print(chat_log_to_check)
  443.                                     self.get_chat_history(username, chat_log_to_check, client)
  444.  
  445.                 elif user_choice.decode() == 'ADDFRIEND':  # Sends friend request to the other user!
  446.                     print('User wants to add a new friend!')
  447.                     while True:
  448.                         client_username = client.recv(1024)
  449.                         if client_username:
  450.                             client_username = client_username.decode()
  451.                             print(client_username)
  452.                             while True:
  453.                                 friend_username = client.recv(1024)
  454.                                 if friend_username:
  455.                                     friend_username = friend_username.decode()
  456.                                     print(friend_username)
  457.                                     self.send_friend_request(client_username, friend_username, client)
  458.  
  459.                 elif user_choice.decode() == 'REMOVEFRIEND':  # Removes friend from users friend file
  460.                     while True:
  461.                         username = client.recv(1024)
  462.                         if username:
  463.                             username = username.decode()
  464.                             print(username)
  465.                             while True:
  466.                                 user_to_remove = client.recv(1024)
  467.                                 if user_to_remove:
  468.                                     user_to_remove = user_to_remove.decode()
  469.                                     self.remove_user(username, user_to_remove, client)
  470.  
  471.                 elif user_choice.decode() == 'GETFRIENDS':  # Retrieves friend list from user and returns it to them.
  472.                     print('User wants to get their friends list!')
  473.                     while True:
  474.                         client_username = client.recv(1024)
  475.                         if client_username:
  476.                             client_username = client_username.decode()
  477.                             print(client_username)
  478.                             self.get_friends_list(client_username, client)
  479.  
  480.                 elif user_choice.decode() == 'ACCEPTREQUEST':  # Allows the user to accept a friend request.
  481.                     print('User wants to accept a friend request!')
  482.                     while True:
  483.                         client_username = client.recv(1024)
  484.                         if client_username:
  485.                             client_username = client_username.decode()
  486.                             print(client_username)
  487.                             while True:
  488.                                 user_to_accept = client.recv(1024)
  489.                                 if user_to_accept:
  490.                                     user_to_accept = user_to_accept.decode()
  491.                                     print(user_to_accept)
  492.                                     self.accept_friend_request(client_username, user_to_accept, client)
  493.  
  494.                 elif user_choice.decode() == 'VIEWREQUESTS':  # Lets the user review their current friend requests.
  495.                     print('User wants to see their pending friend requests!')
  496.                     while True:
  497.                         username = client.recv(1024)
  498.                         if username:
  499.                             username = username.decode()
  500.                             print(username)
  501.                             self.view_incoming_requests(username, client)
  502.  
  503.                 elif user_choice.decode() == 'VIEWOUTGOING':
  504.                     print('User wants to see their outgoing friend requests!')
  505.                     username = client.recv(1024)
  506.                     if username:
  507.                         username = username.decode()
  508.                         self.view_outgoing_requests(username, client)
  509.  
  510.  
  511. server = ChatServer()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement