Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
611 lines (509 loc) · 15.1 KB
/
Copy pathclient.py
File metadata and controls
611 lines (509 loc) · 15.1 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import json
import os
from getpass import getpass
import click
import requests
import socketio
from cryptography.fernet import Fernet
URL = "https://cli-chatapp.herokuapp.com"
# Encryption Key for messages and secret
ENCRYPTION_KEY = b"r33YpSlDxWaRVYUA1quBSv8wezWfOwVt-zcJw2PvpVI="
# Secrets Storage Location
separator = os.sep
PATH = os.path.expanduser(f"~{separator}.chatapp_secret")
# SocketIO client instantiation
sio = socketio.Client()
# Encryption
f = Fernet(ENCRYPTION_KEY)
def store_secrets(jwt: str, username: str):
"""
Encrypt and JWT Token and username for use
"""
jwt = f.encrypt(jwt.encode())
username = f.encrypt(username.encode())
with open(PATH, "wb") as file:
file.write(jwt)
file.write("\n".encode())
file.write(username)
def delete_secrets():
if os.path.exists(PATH):
os.remove(PATH)
def get_secrets() -> list or None:
"""
Get stored secrets
"""
# check if path exists
if not os.path.exists(PATH):
return None
# check if file is empty
if os.path.getsize(PATH) == 0:
return None
with open(PATH, "rb") as file:
content = file.readlines()
return [f.decrypt(secret).decode("utf-8") for secret in content]
@click.group()
def chatapp():
"""
Chat App CLI.
"""
pass
@chatapp.command()
def register():
"""
Create an account on Chat App
"""
while True:
username = input("Username: ")
if len(username) < 2:
click.secho(
"・Username must be at least two characters",
err=True,
fg="red",
bold=True,
)
continue
break
while True:
password = getpass(prompt="Password: ")
if len(password) < 4:
click.secho(
"・Password must be at least four characters",
err=True,
fg="red",
bold=True,
)
continue
break
# request body
data = json.dumps(dict(username=username, password=password))
# request headers
headers = {"content-type": "application/json"}
r = requests.post(f"{URL}/registration", data=data, headers=headers, timeout=15)
if r.status_code > 201:
click.secho(f'・{r.json()["message"]}', err=True, fg="red", bold=True)
else:
click.secho(f'・{r.json()["message"]}', fg="green", bold=True)
@chatapp.command()
def login():
"""
Login to Chat App
"""
while True:
username = input("Username: ")
if len(username) < 2:
click.secho(
"・Username must be at least two characters",
err=True,
fg="red",
bold=True,
)
continue
break
while True:
password = getpass(prompt="Password: ")
if len(password) < 4:
click.secho(
"・Password must be at least four characters",
err=True,
fg="red",
bold=True,
)
continue
break
# request body
data = json.dumps(dict(username=username, password=password))
# request header
headers = {"content-type": "application/json"}
r = requests.post(f"{URL}/login", data=data, headers=headers, timeout=15)
if r.status_code > 201:
click.secho(f'・{r.json()["message"]}', err=True, fg="red", bold=True)
else:
store_secrets(r.json()["access_token"], r.json()["username"])
click.secho(f'・{r.json()["message"]}', fg="green", bold=True)
@chatapp.command()
def logout():
"""
Logout of Chat App CLI
"""
confirmation = input("Are you sure you want to logout? [y/n]: ")
if confirmation.lower() == "y":
delete_secrets()
click.secho("・You have been logged out successfully!", fg="green", bold=True)
elif confirmation.lower() == "n":
pass
else:
click.secho("・Command not recognised!", fg="red", bold=True)
@chatapp.command()
def channels():
"""
List all public channels
"""
if not get_secrets():
click.secho(
"・You need to be logged in to view all channels",
err=True,
fg="red",
bold=True,
)
else:
jwt, _ = get_secrets()
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/channels", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
# get all public channels available
data = r.json()["data"]
if len(data) < 1:
click.secho("・No channels available at the moment!", fg="blue", bold=True)
else:
click.secho("---------- AVAILABLE PUBLIC CHANNELS ----------", bold=True)
for _channel in data:
click.secho(
f'{_channel["name"]}: {len(_channel["participants"])} participant(s)',
fg="blue",
bold=True,
)
@chatapp.command()
@click.argument("name", type=click.STRING)
def channel(name):
"""
Join a public channel or create a new channel if it's non-existent
"""
if not get_secrets():
click.secho(
"・You need to be logged in to view a channel",
err=True,
fg="red",
bold=True,
)
return
jwt, username = get_secrets()
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/channels/{name}", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
data = r.json()["data"]
click.secho(
f'-------------- Welcome to {data["name"]} channel ----------------', bold=True
)
# SocketIO connection
sio.connect(URL, headers=headers, transports="polling")
for _message in data["messages"]:
if _message["sender"]["username"] == "admin":
click.secho(
f'[{_message["timestamp"]}] {_message["sender"]["username"]}: {f.decrypt(_message["content"].encode()).decode()}',
bold=True,
fg="yellow",
)
else:
click.secho(
f'[{_message["timestamp"]}] {_message["sender"]["username"]}: {f.decrypt(_message["content"].encode()).decode()}',
bold=True,
fg="green",
)
sio.sleep(10)
sio.emit("join-channel", {"username": username, "channel_name": name})
while True:
new_message = (input("Enter a message (max of 155 characters): ")).strip()
if 156 > len(new_message) > 0:
new_message = f.encrypt(new_message.encode())
sio.emit(
"new-channel-message",
{"msg": new_message, "from": username, "channel": name},
)
else:
click.secho(
"・You cannot send an empty text",
err=True,
fg="red",
bold=True,
)
sio.sleep(1)
@chatapp.command()
def privates():
"""
View all private conversations with users
"""
if not get_secrets():
click.secho(
"・You need to be logged in to view all private chats!",
err=True,
fg="red",
bold=True,
)
return
jwt, username = get_secrets()
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/privates", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
# get all private chats available
data = r.json()["data"]
if len(data) < 1:
click.secho("・No private chats available at the moment!", fg="blue", bold=True)
else:
click.secho("---------- PRIVATE CHATS ----------", bold=True)
for _channel in data:
click.secho(
f'・{_channel["name"]}',
fg="blue",
bold=True,
)
@chatapp.command()
@click.argument("username", type=click.STRING)
def private(username):
"""
Start a private chat with a user.
"""
if not get_secrets():
click.secho(
"・You need to be logged in to start/continue a private chat!",
err=True,
fg="red",
bold=True,
)
return
jwt, my_username = get_secrets()
# check if username equals to yours
if username == my_username:
click.secho(
"・You cannot have a private chat with yourself!",
err=True,
fg="red",
bold=True,
)
return
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/privates/{username}", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
data = r.json()["data"]
click.secho(
f'-------------- Private Chat -> {" and ".join(data["name"].split("-"))} ----------------',
bold=True,
)
# SocketIO connection
sio.connect(URL, headers=headers)
for _message in data["messages"]:
click.secho(
f'[{_message["timestamp"]}] {_message["sender"]["username"]}: {f.decrypt(_message["content"].encode()).decode()}',
bold=True,
fg="magenta",
)
sio.sleep(10)
sio.emit("join-private-chat", {"username": my_username, "chat_name": data["name"]})
while True:
new_message = (input("Enter a message (max of 155 characters): ")).strip()
if 156 > len(new_message) > 0:
new_message = f.encrypt(new_message.encode())
sio.emit(
"new-private-message",
{"msg": new_message, "from": my_username, "chat_name": data["name"]},
)
else:
click.secho(
"・You cannot send an empty text ",
err=True,
fg="red",
bold=True,
)
sio.sleep(1)
@chatapp.command()
def stat():
"""
View currently logged in users
"""
if not get_secrets():
click.secho(
"・You need to be logged in to view all channels",
err=True,
fg="red",
bold=True,
)
return
jwt, username = get_secrets()
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/stats", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
data = r.json()["data"]
click.secho(f"-------------- Users ----------------", bold=True)
if not data:
click.secho("No user logged in at the moment!", bold=True)
else:
for user in data:
click.secho(
f'Username: {user["username"]} -> IP Address: {user["ip_address"]}',
bold=True,
)
@chatapp.command()
@click.argument("channel_name")
def warn(channel_name):
"""
Send a warning to a public channel
"""
if not get_secrets():
click.secho(
"・You need to be logged in!",
err=True,
fg="red",
bold=True,
)
return
jwt, username = get_secrets()
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/search?q={channel_name}", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
data = r.json()["data"]
# SocketIO connection
sio.connect(URL, headers=headers, transports="polling")
while True:
warning_message = (
input(f"Enter a warning message to send to {channel_name} channel: ")
).strip()
if not len(warning_message) > 0:
click.secho(
"・You cannot send an empty text ",
err=True,
fg="red",
bold=True,
)
continue
break
sio.sleep(1)
msg = f.encrypt(warning_message.encode())
sio.emit(
"new-channel-message",
{"msg": msg, "from": username, "channel": channel_name},
)
click.secho(
f"・Warning sent to {channel_name} channel successfully!", bold=True, fg="green"
)
sio.wait()
return
@chatapp.command()
@click.argument("ip_addr")
def ban_ip(ip_addr):
"""
Ban users using IP Address
"""
if not get_secrets():
click.secho(
"・You need to be logged in!",
err=True,
fg="red",
bold=True,
)
return
jwt, username = get_secrets()
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/ban/ip/{ip_addr}", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
msg = r.json()["msg"]
click.secho(f"・{msg}", bold=True, fg="green")
@chatapp.command()
@click.argument("username")
def ban_username(username):
"""
Ban user using their username
"""
if not get_secrets():
click.secho(
"・You need to be logged in!",
err=True,
fg="red",
bold=True,
)
return
jwt, my_username = get_secrets()
headers = {"Authorization": f"Bearer {jwt}"}
r = requests.get(f"{URL}/ban/username/{username}", headers=headers)
if r.status_code > 200:
click.secho(
f"・{r.json()['msg']}",
err=True,
fg="red",
bold=True,
)
return
msg = r.json()["msg"]
click.secho(f"・{msg}", bold=True, fg="green")
@sio.on("connect")
def connect():
pass
@sio.on("disconnect")
def disconnect():
pass
@sio.on("channel-messages")
def channel_messages(data):
if data["sender"]["username"] == "admin":
click.secho(
f'[{data["timestamp"]}] {data["sender"]["username"]}: {f.decrypt(data["content"].encode()).decode()}',
bold=True,
fg="yellow",
)
else:
click.secho(
f'[{data["timestamp"]}] {data["sender"]["username"]}: {f.decrypt(data["content"].encode()).decode()}',
bold=True,
fg="green",
)
@sio.on("private-messages")
def private_messages(data):
click.secho(
f'[{data["timestamp"]}] {data["sender"]["username"]}: {f.decrypt(data["content"].encode()).decode()}',
bold=True,
fg="magenta",
)
@sio.on("joined-channel")
def joined_channel(data):
click.secho(f'{data["msg"]}', bold=True)
@sio.on("joined-private-chat")
def joined_private_chat(data):
click.secho(f'{data["msg"]}', bold=True)
if __name__ == "__main__":
chatapp()