summaryrefslogtreecommitdiff
path: root/main.py
blob: caf506a40cbdd99ab34f8b87a023b6d596e8f202 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#
#  Copyright (C) 2023 littleblack111 <https://github.com/littleblack111/>

import socket
from os import path
from sys import exit
import threading

HOST = '0.0.0.0'  # listen on both loopback and local IP address
PORT = 8000

VERSOIN = "1.1" # Implemented blocking swear/curse words and removed invalid/inapropriate names

HOME = path.expanduser('~')

swearList = ['fuck', 'shit', 'bitch', 'ass', 'nigg']
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
print(f"Server binded on {HOST} with port {PORT}")
server_socket.listen()

clients = []
names = []

def broadcast(message):
    for client in clients:
        client.send(message)
    with open(f"{HOME}/scripts/logs/chat.log", "a") as log_file:
        log_file.write(message.decode())
    #with open("chat.log", "a") as log_file:
        #log_file.write(message.decode())


def handle_client(client_socket, client_address):
    print(f'New connection from {client_address}')
    if client_address[0] in [c.getpeername()[0] for c in clients]:
        print(f'{client_address} is attempting to connect twice')
        client_socket.send("Your already connected\n".encode())
        client_socket.close()
        return
    clients.append(client_socket)
    client_socket.send("Name: ".encode())
    try:
        name = client_socket.recv(1024).decode().replace("\n", "")
        if name:
            if name == "" or " " in name or SwearOrNot(name):
                for c in clients:
                    c.send("Your name have problems\n".encode())
                    clients.remove(c)
                    c.close()
                    return
            for n in names:
                if n == name: # need test
                    for c in clients:
                        snames = " ".join(names)
                        c.send(f"Username taken, use an unused name, current names: {snames}\n".encode())
                        clients.remove(c)
                        c.close()
                    return
        else:
            raise Exception('Client disconnected without registering')
    except Exception as e:
        print(e)
        clients.remove(client_socket)
        print(f'{client_address} has left the chat without registering')
        #broadcast(f'{client_address} has left the chat\n'.encode())
        broadcast(f'{client_address} has left the chat without even registering\n'.encode())
        client_socket.close()
        return

    names.append(name)
    #broadcast(f'{client_address} has joined the chat\n'.encode())
    broadcast(f'{name} has joined the chat\n'.encode())
    with open(f"{HOME}/scripts/logs/chat.log", "r") as log_file:
        log_contents = log_file.read()
        client_socket.send(log_contents.encode())
    #with open("chat.log", "r") as log_file:
    #    log_contents = log_file.read()
    #    client_socket.send(log_contents.encode())

    while True:
        try:
            message = client_socket.recv(1024)
            if message:
                rmsg = message.decode()
                if client_address[0] == "127.0.0.1" and rmsg.startswith("$") or client_address[0] == "192.168.1.16" and rmsg.startswith("$"):
                    command = rmsg[1:].strip()
                    #command_parts = message[1:].strip().split()
                    print(f"Command spawned: {command}")
                    if command == "list":
                        client_socket.send("Connected clients:\n".encode())
                        for c in clients:
                            c_address = c.getpeername()[0]
                            client_socket.send(f"{c_address}\n".encode())
                    elif "kick" in command and len(command.split()) == 2:
                        kick_address = command.split()[1]
                        if kick_address != "127.0.0.1":# and client_address[0] != "192.168.1.16":
                            for c in clients:
                                c_address = c.getpeername()[0]
                                if c_address == kick_address:
                                    c.send("You have been kicked\n".encode())
                                    clients.remove(c)
                                    c.close()
                                    client_socket.send(f"Kicked client at {kick_address} Succefully\n".encode())
                                    break
                                else:
                                    client_socket.send(f"No client found at {kick_address}".encode())
                    else:
                        client_socket.send("Unknown command or syntax \n".encode())

                if message.decode() != "":
                    #broadcast(f'{client_address}: {message.decode()}'.encode())
                    if SwearOrNot(message.decode()):
                        broadcast(f'{name}: {len(message.decode())*"#"}\n'.encode())
                    else:
                        broadcast(f'{name}: {message.decode()}'.encode())
                    print(f'{client_address}({name}): {message.decode()}')
            else:
                raise Exception('Client disconnected')
        except Exception as e:
            print(e)
            clients.remove(client_socket)
            print(f'{client_address} has left the chat')
            #broadcast(f'{client_address} has left the chat\n'.encode())
            broadcast(f'{name} has left the chat\n'.encode())
            client_socket.close()
            return

def SwearOrNot(var):
    if any(word in var for word in swearList):
        return True
    else:
        return False


def accept_connections():
    while True:
        try:
            client_socket, client_address = server_socket.accept()
            client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
            client_thread.start()
        except KeyboardInterrupt:
            print("Closing server...")
            #client_thread.join()
            exit()

try:
    if __name__ == '__main__':
        #with open("chat.log", "w") as log_file:
        #    log_file.truncate(0)
        with open(f"{HOME}/scripts/logs/chat.log", "w") as log_file:
            log_file.truncate(0)
        try:
            server_thread = threading.Thread(target=accept_connections)
            server_thread.start()
            #client_socket, client_address = server_socket.accept()
            #handle_client(client_socket, client_address)
        except KeyboardInterrupt:
            print("Closing server...")
            #client_thread.join()
            exit()

        # Handle the server's own connection
        try:
            while True:
                try:
                    message = input('> ')
                    broadcast(f'{message}\n'.encode())
                except KeyboardInterrupt:
                    print("Closing server...")
                    #client_thread.join()
                    exit()
        except KeyboardInterrupt:
            print("Closing server...")
            #client_thread.join()
            exit()
except KeyboardInterrupt:
    print("Closing server...")
    #client_thread.join()
    exit()