-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient_noGUI.py
More file actions
169 lines (131 loc) · 4.07 KB
/
Client_noGUI.py
File metadata and controls
169 lines (131 loc) · 4.07 KB
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
"""
Version 1.0.2
Write and receive messages (terminal only)
Author:
Nilusink
"""
from sys import platform, exit as s_exit
from core.client import Connection
from traceback import format_exc
from core import InvalidSecret
from threading import Thread
from time import sleep
import signal
import json
import os
CONNECTED: bool = False
class Colors:
"""
for better looks
"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def fail(error_msg: str) -> None:
"""
print a error message in red
"""
print(f"{Colors.FAIL}{error_msg}{Colors.ENDC}")
def success(success_msg: str) -> None:
"""
print a success message in green
"""
print(f"{Colors.OKGREEN}{success_msg}{Colors.ENDC}")
class MessageUpdater:
def __init__(self, c: Connection, update_delay: float = 0.2) -> None:
self.__connection = c
self.update_delay = update_delay
self.running: bool = True
# later used variables
self.__done_messages: list = []
def run(self) -> None:
"""
receive messages while self.running
"""
while self.running:
for message in self.__connection.new_messages:
if message not in self.__done_messages:
print(f"\r{message['user']}>> {message['message']}", end="\n>> ")
self.__done_messages.append(message)
sleep(self.update_delay)
def run_thread(self) -> None:
"""
run self.run in a thread
"""
Thread(target=self.run).start()
def main() -> int:
"""
main program, all the code runs here
"""
global CONNECTED, C, MU
try:
print(f"Starting client Headless...")
# load keys from file
secrets = json.load(open("config.json", "r"))
# getting user input and trying to connect to the server
while not CONNECTED:
try:
# get connection data from user
ip = input(f"\n{Colors.HEADER}Server IP: {Colors.OKCYAN}")
port = int(input(f"{Colors.HEADER}Server PORT: {Colors.OKCYAN}"))
username = input(f"{Colors.HEADER}Username: {Colors.OKBLUE}")
# connect to the server
C = Connection(ip, port, username, secrets["server_secret"], secrets["client_secret"])
# catching all the errors
except ValueError:
fail("Invalid port. Please enter numbers only!")
continue
except NameError:
fail("User already logged in")
continue
except ConnectionRefusedError:
fail("Wrong IP / Server (program) down")
continue
except (ConnectionError, TimeoutError):
fail("Invalid IP / Server (computer) down")
continue
except InvalidSecret:
fail("Server-Secret Wrong!")
continue
CONNECTED = True
# actual code that runs the program
success("Successfully connected to server, loading messages...\n")
MU = MessageUpdater(C)
MU.run_thread()
while CONNECTED:
# get message input
mes = input("")
C.send_message(mes)
except (Exception,):
print(f"{Colors.FAIL}{format_exc()}\n\nexiting!!{Colors.ENDC}\n")
return 1
finally:
return 0
def end(*signals) -> None:
"""
called if the program ends (errors and normal exit)
"""
global CONNECTED
CONNECTED = False
if C is not ...:
C.end()
if MU is not ...:
MU.running = False
print(Colors.ENDC)
s_exit(signals[0])
if platform == "win32":
os.system("color") # only for windows
MU: MessageUpdater = ...
C: Connection = ...
if __name__ == '__main__':
# in case of termination
signal.signal(signal.SIGINT, end)
signal.signal(signal.SIGTERM, end)
# run main program
end(main())