-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice.py
executable file
·1809 lines (1383 loc) · 56.4 KB
/
service.py
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# RFDATA service
# https://aprs.rfdata.org/
# (c) 2020 Andy Smith, VE6LY <[email protected]>
# Released under the MIT License
# Imports
import asyncio
import aiohttp
import logging
import re
import json
import click
import yaml
import sys
import maidenhead
from aprspy import APRS
from aprspy.packets.position import PositionPacket
from aprspy.packets.message import MessagePacket
from aprspy.exceptions import ParseError, UnsupportedError
from asgiref.sync import sync_to_async
from datetime import datetime
from textwrap import wrap
from rfdata.qrz import QRZ
from rfdata.aprsfi import APRSFI
from rfdata.checkwx import CheckWX
from rfdata.darksky import DarkSky
from rfdata.dxwatch import DXWatch
from rfdata.sun import Sun
from rfdata.pskreporter import PSKReporter
# Set up logging
logging.basicConfig(
level=logging.INFO,
filename="aprs-service.log",
format='%(asctime)s %(levelname)-8s %(name)-12s/%(funcName)-16s\n-> %(message)s'
)
logger = logging.getLogger('aprs-service')
# Import Django and models used for backend storage
import django #noqa
django.setup()
from data.models import Station, Chat, ChatMessage, ChatSubscription, Command
class APRSClient(asyncio.Protocol):
"""
APRS client protocol handler
"""
aprsfi = None
checkwx = None
darksky = None
def __init__(self, *args, loop=None, callsign=None, ssid=None, passcode=None, filter=None,
**kwargs):
if not loop:
loop = asyncio.get_event_loop()
self._args = args
self._kwargs = kwargs
self._loop = loop
self._callsign = callsign
self._ssid = ssid
# If an SSID is given, append it to the source
if self._ssid:
self._source = self._callsign + "-" + self._ssid
else:
self._source = self._callsign
self._passcode = passcode
self._filter = filter
self._stopping = False
self._connector = None
self._transport = None
self._login_attempted = False
self._logged_in = False
self._data_queue = asyncio.Queue()
self._send_queue = asyncio.Queue()
self._buffer = None
# Build pounce list
self._pounce_list = [
s.station for s in Station.objects.filter(pounce=True).filter(mailbox__unread=True)
]
# Start up the main processing task
self._loop.create_task(self.process_data())
def connection_made(self, transport):
"""Called when a connection is made to the APRS-IS server."""
logger.info("Connection made!")
self._transport = transport
def data_received(self, data):
"""Called when data is received from the APRS-IS server."""
# For incoming data, we buffer it and then split it based on newlines.
# Usually incoming data consists of complete lines, but if there's a lot of data some
# might be split in the middle - so this handles that
decoded_data = data.decode('UTF-8', 'replace')
logger.debug(decoded_data)
if self._buffer:
# There's data already in the buffer, so prepend it to the new data
decoded_data = self._buffer + decoded_data
self._buffer = None
logger.debug("Cleared buffer")
# Split at newlines
lines = decoded_data.split('\r\n')
if decoded_data[-1] != "\n":
# Last character of the incoming data isn't a newline, so buffer it
logger.debug("Adding partial packet to buffer")
self._buffer = lines.pop()
for line in lines:
# For each line, put it on the queue to be processed
if len(line) > 0:
self._data_queue.put_nowait(line)
async def process_data(self):
"""Process incoming data."""
# Process incoming data
while not self._stopping:
logger.debug("Items in data queue: {}".format(self._data_queue.qsize()))
# Get a line from the data queue
item = await self._data_queue.get()
if item is None:
# No data waiting, sleep momentarily
logger.debug("No data in queue.")
await asyncio.sleep(0.1)
logger.debug("Got from data queue: {}".format(item))
try:
# Decode as UTF-8, strip the newline
decoded_data = item
# Lines beginning with a '#' are status lines from the APRS-IS server
if re.match('^#', decoded_data):
self.parse_server(decoded_data)
else:
# This is a packet, so decode it
await self.parse_packet(decoded_data)
except Exception as e:
# Something went wrong while parsing
logger.error(e)
logger.error("Failed to parse message from APRS-IS: {}".format(decoded_data))
self._data_queue.task_done()
logger.info("Stopping data handler...")
async def parse_packet(self, line):
"""Parse incoming packets."""
logger.debug("Got packet: {}".format(line))
try:
# Parse the packet
packet = APRS.parse(line)
# We use position packets to trigger pounce notifications, if the station has them
# enabled
if issubclass(type(packet), PositionPacket):
if packet.source in self._pounce_list:
logger.info("{} is on the pounce list".format(packet.source))
# Send the number of messages waiting to the station
await self.handle_list_messages(packet.source)
# Check for message packets
elif type(packet) is MessagePacket and packet.addressee == self._source:
# This message is addressed to us
logger.info("Message for us: {}".format(packet.raw))
# Log the message
await self.log_command(packet.source, packet.message)
# If the message has a message ID, cknowledge it
if packet.message_id:
self.send_message(
packet.source, "ack{}".format(packet.message_id), log=False
)
# Convert to lower case for the command
parts = packet.message.lower().split(' ')
logger.info(parts)
if len(parts) >= 1:
cmd = parts[0]
else:
cmd = None
# Check what the command is
if cmd == "?APRS?" or cmd == "?help" or cmd == "?he" or cmd == "?h":
# Respond to help
self.send_message(
packet.source,
"L R S D E Y C J P PN T A M MH MT W WX Q QRZ DX SOL"
)
self.send_message(
packet.source,
"Send ?<cmd> for help"
)
self.send_message(
packet.source, "Visit https://aprs.rfdata.org/ for more information!"
)
elif cmd == "?aprst" or cmd == "?ping?":
# Return the path the message took to us
logger.info("{} requested {}".format(packet.source, cmd.upper()))
self.send_message(packet.source, packet.path.path)
elif cmd == "?aprsv":
# Return the current version
logger.info("{} requested {}".format(packet.source, cmd.upper()))
self.send_message(
packet.source, "aprs-service v0.1 by Andy Smith VE6LY [email protected]"
)
# Prefixing commands with ? sends help for that command
elif cmd == "?l":
# List number of waiting messages
self.send_message(
packet.source, "L: List messages waiting for your callsign-ssid"
)
elif cmd == "?r":
# Read a message
self.send_message(
packet.source, "R <number>: Read message <number> for your callsign-ssid"
)
elif cmd == "?d":
# Delete a message
self.send_message(
packet.source, "D <number>: Delete message <number> for your callsign-ssid"
)
elif cmd == "?e":
# Delete all messages
self.send_message(
packet.source, "E: Empty the mailbox for your callsign-ssid"
)
elif cmd == "?i":
# Show message info
self.send_message(
packet.source, "I <number>: Show info for message <number>"
)
elif cmd == "?s":
# Send a message
self.send_message(
packet.source, "S <callsign> <message>: Send <message> to <callsign>"
)
elif cmd == "?c":
# Create a chat
self.send_message(
packet.source, "C <name>: Create chat <name>"
)
elif cmd == "?j":
# Join a chat
self.send_message(
packet.source, "J <name>: Join chat <name>"
)
elif cmd == "?p":
# Leave (part) a chat
self.send_message(
packet.source, "P <name>: Leave (part) chat <name>"
)
elif cmd == "?pn":
# Toggle pounce mode
self.send_message(
packet.source, "PN: Toggle notifications for messages"
)
elif cmd == "?t":
# Send a message to a chat
self.send_message(
packet.source, "T <name> <message>: Send <message> to chat <name>"
)
elif cmd == "?m":
# Show which chats the station is a member of
self.send_message(
packet.source, "M: Show chats your callsign-ssid is a member of"
)
elif cmd == "?mh":
# Show current Maidenhead grid square
self.send_message(
packet.source, "MH: Show your current Maidenhead grid square"
)
elif cmd == "?mt":
# Show METAR data for an airport
self.send_message(
packet.source, "MT <airport>: METAR for airport <airport>"
)
elif cmd == "?a":
# Set topic for a chat
self.send_message(
packet.source, "A <chat> <topic>: Set the topic for a chat you own"
)
elif cmd == "?qrz":
# QRZ lookup
self.send_message(
packet.source, "QRZ <callsign>: Look up callsign in QRZ"
)
elif cmd == "?dx":
# DX cluster lookup
self.send_message(
packet.source, "DX <callsign>: Look up callsign on DX cluster"
)
elif cmd == "?sol":
# Solar data lookup
self.send_message(
packet.source, "SOL <callsign>: Look up solar data"
)
elif cmd == "?sun":
# Solar data lookup
self.send_message(
packet.source, "SUN: Sunrise/sunset times for your location"
)
elif cmd == "?pskr":
# Solar data lookup
self.send_message(
packet.source, "PSKR: Get best freqs for your grid from pskreporter.info"
)
elif cmd == "?q":
# APRS position lookup
self.send_message(
packet.source, "Q <callsign>: Look up APRS position for callsign"
)
elif cmd == "?wx":
# Weather lookup
self.send_message(
packet.source, "WX: Get weather at your current location"
)
elif cmd == "qrz":
# Handle QRZ lookups
await self.handle_qrz(packet.source, parts)
elif cmd == "s":
# Handle sending messages
await self.handle_send_message(packet)
elif cmd == "l":
# Handle listing waiting messages
await self.handle_list_messages(packet.source)
elif cmd == "r":
# Handle reading messages
await self.handle_read_message(packet.source, parts)
elif cmd == "y":
# Handle replying to messages
await self.handle_reply_message(packet)
elif cmd == "i":
# Handle message info
await self.handle_info_message(packet.source, parts)
elif cmd == "d":
# Handle deleting messages
await self.handle_delete_message(packet.source, parts)
elif cmd == "e":
# Handle deleting all messages
await self.handle_delete_all_messages(packet.source)
elif cmd == "c":
# Handle creating chats
await self.handle_create_chat(packet.source, parts)
elif cmd == "j":
# Handle joining chats
await self.handle_join_chat(packet.source, parts)
elif cmd == "p":
# Handle leaving chats
await self.handle_leave_chat(packet.source, parts)
elif cmd == "pn":
# Handle pounce mode
await self.handle_pounce(packet.source, parts)
elif cmd == "w":
# Handle showing chat membership
await self.handle_show_all_chats(packet.source)
elif cmd == "t" or cmd[0] == ".":
# Handle chat messages
await self.handle_chat_message(packet)
elif cmd == "a":
# Handle chat topic
await self.handle_chat_topic(packet)
elif cmd == "m":
# Handle showing all chats
chats = await self.list_chats(packet.source)
self.send_message(packet.source, "Chats: {}".format(" ".join(chats)))
elif cmd == "dx":
# Handle DX cluster lookup
await self.handle_dx(packet.source, parts)
elif cmd == "sol" or cmd == "solar":
# Handle solar data
await self.handle_solar(packet.source)
elif cmd == "sun":
# Handle sunrise/sunset
await self.handle_sunrise_sunset(packet.source)
elif cmd == "pskr":
# Handle pskreporter best frequencies
await self.handle_pskr_freq(packet.source)
elif cmd == "q" or cmd == "seen":
# Handle APRS position lookup
await self.handle_seen(packet.source, parts)
elif cmd == "mh" or cmd == "grid":
# Handle Maidenhead grid square lookup
await self.handle_mh(packet.source)
elif cmd == "mt" or cmd == "metar":
# Handle METAR lookup
await self.handle_metar(packet.source, parts)
elif cmd == "wx" or cmd == "weather":
# Handle weather lookup
await self.handle_wx(packet.source)
except ParseError:
logger.debug("Failed to parse packet: {}".format(line))
except UnsupportedError:
logger.debug("Unsupported packet: {}".format(line))
async def handle_qrz(self, source, args):
"""Handle QRZ lookups."""
# If no callsign is given, send help
if len(args) < 2:
self.send_message(
source, "Usage: QRZ <callsign>"
)
else:
logger.info("{} querying QRZ for {}".format(
source, args[1].upper()
))
# Query QRZ
response = await self.get_qrz(args[1])
# Send response
self.send_message(
source, response
)
async def handle_dx(self, source, args):
"""Handle DX cluster lookups."""
# If no callsign is given, send help
if len(args) < 2:
self.send_message(
source, "Usage: DX <callsign>"
)
else:
logger.info("{} querying DX cluster for {}".format(
source, args[1].upper()
))
# Uppercase the callsign, and query the DX cluster
callsign = args[1].upper()
message = await self.get_dx(callsign)
# Send response
self.send_message(
source, message
)
async def handle_solar(self, source):
"""Handle solar data lookup."""
logger.info("{} querying for solar data".format(
source
))
# Get solar data
response = await self.get_solar()
try:
# Format the response
data = json.loads(response)
message = "F:{} A:{} K:{} S:{} @{}".format(
data['flux'], data['a'], data['k'], data['ssn'], data['date']
)
except Exception as e:
logger.error(e)
message = "Could not query solar data"
# Send response
self.send_message(
source, message
)
async def handle_seen(self, source, args):
"""Handle APRS position lookup."""
# If no callsign is given, send help
if len(args) < 2:
self.send_message(
source, "Usage: Q <callsign>"
)
else:
logger.info("{} querying aprs.fi for {}".format(
source, args[1].upper()
))
# Uppercase the callsign, and query aprs.fi
callsign = args[1].upper()
response = await self.aprsfi.station(callsign)
if response:
# Format response
timestamp = datetime.fromtimestamp(int(response['lasttime']))
message = "{}: {},{} @{}: {}".format(
callsign,
round(float(response['lat']), 2),
round(float(response['lng']), 2),
timestamp,
response['comment'] if 'comment' in response else ""
)
# Send response
self.send_message(
source, message
)
else:
self.send_message(
source, "Could not find {}".format(callsign)
)
async def handle_metar(self, source, args):
"""Handle METAR lookups."""
# If no airport is given, send help
if len(args) < 2:
self.send_message(
source, "Usage: MT <ICAO code>"
)
else:
logger.info("{} querying CheckWX for {}".format(
source, args[1].upper()
))
# Uppercase the airport code and query CheckWX
icao = args[1].upper()
response = await self.checkwx.metar(icao)
if response:
# Send response
self.send_message(
source, response
)
else:
self.send_message(
source, "Could not find {}".format(icao)
)
async def handle_mh(self, source):
"""Handle Maidenhead grid square lookup."""
logger.info("Querying aprs.fi for {}".format(
source
))
# Query aprs.fi for current position
response = await self.aprsfi.station(source)
if response:
# Format response
timestamp = datetime.fromtimestamp(int(response['lasttime']))
locator = maidenhead.toMaiden(
float(response['lat']), float(response['lng'])
)
message = "{} ({}, {}) @ {}".format(
locator,
round(float(response['lat']), 2),
round(float(response['lng']), 2),
timestamp
)
# Send response
self.send_message(
source, message
)
else:
self.send_message(
source, "Could not find {}".format(source)
)
async def handle_wx(self, source):
logger.info("Querying aprs.fi for {}".format(
source
))
# Query aprs.fi for current position
response = await self.aprsfi.station(source)
if response:
# Query Darksky for weather
wx = await self.darksky.wx(response['lat'], response['lng'])
# Send response
self.send_message(
source, wx
)
else:
self.send_message(
source, "Could not find {}".format(source)
)
async def handle_sunrise_sunset(self, source):
logger.info("Querying aprs.fi for {}".format(
source
))
# Query aprs.fi for current position
response = await self.aprsfi.station(source)
if response:
# Query for sunrise/sunset
sunrise_sunset = await self.sun.sunrise_sunset(response['lat'], response['lng'])
# Send response
self.send_message(
source, sunrise_sunset
)
else:
self.send_message(
source, "Could not find {}".format(source)
)
async def handle_pskr_freq(self, source):
logger.info("Querying aprs.fi for {}".format(
source
))
# Query aprs.fi for current position
response = await self.aprsfi.station(source)
if response:
# Query for sunrise/sunset
best_freqs = await self.pskr.psk_freq(response['lat'], response['lng'])
# Send response
self.send_message(
source, best_freqs
)
else:
self.send_message(
source, "Could not find {}".format(source)
)
async def handle_send_message(self, packet):
"""Handle sending a message to another station."""
# If there's not enough arguments, send help
if len(packet.message.split(' ')) < 3:
self.send_message(
packet.source, "Usage: S <callsign> <message>"
)
else:
# Split the arguments, get the addressee and the message
args = packet.message.split(' ')
addressee = args[1].upper()
message = " ".join(args[2:])
# Put the message in the addressee's mailbox
sent = await self.add_mailbox_message(
packet.source, addressee, message
)
if sent:
self.send_message(packet.source, "Message to {} sent".format(
addressee
))
async def handle_reply_message(self, packet):
"""Handle replying to a message."""
# Split the parts of the message
parts = packet.message.split(' ')
# If there's not enough arguments, or the message number isn't a number, send help
if len(parts) < 3:
self.send_message(
packet.source, "Usage: Y <message number> <message>"
)
elif not re.match("[0-9]+", parts[1]):
self.send_message(
packet.source, "Usage: Y <message number> <message>"
)
else:
# Get the message number and the reply
number = int(parts[1])
reply = " ".join(parts[2:])
# Get the message by the given message number
message = await self.get_message_by_number(packet.source, number)
if message:
# Get the addressee from the message
addressee = message.source.station
# Put the message in the addressee's mailbox
sent = await self.add_mailbox_message(
packet.source, addressee, reply
)
if sent:
self.send_message(packet.source, "Reply to {} sent".format(
addressee
))
else:
# No matching message number found
self.send_message(packet.source, "Reply #{} not found".format(
number
))
async def handle_read_message(self, source, args):
"""Handle reading messages."""
# If there's not enough arguments, or if the message number is not a number, send help
if len(args) < 2:
self.send_message(
source, "Usage: R <message number>"
)
elif not re.match("[0-9]+", args[1]):
self.send_message(
source, "Usage: R <message number>"
)
else:
# Get the message
number = int(args[1])
message = await self.get_message_by_number(source, number)
if message:
# Send response
self.send_message(source, "{}:{}".format(
message.source.station, message.message
))
else:
# No matching message number found
self.send_message(source, "Message #{} not found".format(
number
))
async def handle_list_messages(self, source):
"""Handle listing number of messages."""
# Get number of messages waiting
count = await self.get_mailbox_count(source)
# Send response
self.send_message(source, "You have {} message(s) waiting".format(count))
async def handle_info_message(self, source, args):
"""Handle message info."""
# If no message number given, or message number is not a number, send help
if len(args) < 2:
self.send_message(
source, "Usage: I <message number>"
)
elif not re.match("[0-9]+", args[1]):
self.send_message(
source, "Usage: I <message number>"
)
else:
# Get message
number = int(args[1])
message = await self.get_message_by_number(source, number)
if message:
# Send response
self.send_message(source, "From: {} On: {}".format(
message.source.station, message.timestamp.strftime(
"%Y-%m-%d %H:%M:%S"
)
))
else:
# No matching message number found
self.send_message(source, "Message #{} not found".format(
number
))
async def handle_delete_message(self, source, args):
"""Handle deleting messages."""
# If no message number given or message number is not a number, send help
if len(args) < 2:
self.send_message(
source, "Usage: D <message number>"
)
elif not re.match("[0-9]+", args[1]):
self.send_message(
source, "Usage: D <message number>"
)
else:
# Get message
number = int(args[1])
# Delete it
# NOTE: Messages aren't actually deleted, just made invisible
deleted = await self.delete_message_by_number(source, number)
if deleted:
# Message deleted
self.send_message(source, "Message #{} deleted".format(
number
))
else:
# No matching message number found
self.send_message(source, "Message #{} not found".format(
number
))
async def handle_delete_all_messages(self, source):
"""Handle deleting all messages."""
# Delete them
# NOTE: Messages aren't actually deleted, just made invisible
deleted = await self.delete_all_messages(source)
if deleted:
# Message deleted
self.send_message(source, "Messages deleted")
else:
# No matching message number found
self.send_message(source, "Messages not deleted")
async def handle_create_chat(self, source, args):
"""Handle creating chats."""
# If there's no arguments, send help
if len(args) < 2:
self.send_message(source, "Usage: C <chat>")
return
# Uppercase the chat name
name = args[1].upper()
# Create the chat
created = await self.create_chat(name, source)
if created:
# Chat created
self.send_message(source, "Chat {} created".format(name))
else:
# Chat not created
self.send_message(source, "Chat {} exists".format(name))
async def handle_show_all_chats(self, source):
"""Handle showing all available chats."""
# Get chats
chats = await self.show_all_chats()
# Send response
self.send_message(source, "Chats: {}".format(" ".join(chats)))
async def handle_join_chat(self, source, args):
"""Handle joining a chat."""
# If there's no arguments, send help
if len(args) < 2:
self.send_message(source, "Usage: J <chat>")
return
# Uppercase the chat name
name = args[1].upper()
# Join the chat
joined = await self.join_chat(name, source)
if joined == 0:
# Chat joined
self.send_message(source, "Chat {} joined".format(name))
elif joined == 1:
# Chat does not exist
self.send_message(source, "Chat {} does not exist".format(name))
elif joined == 2:
# Station already in the chat
self.send_message(source, "Already in chat {}".format(name))
async def handle_leave_chat(self, source, args):
"""Handle leaving a chat."""
# If there's no arguments, send help
if len(args) < 2:
self.send_message(source, "Usage: P <chat>")
return
# Uppercase the chat name
name = args[1].upper()
# Leave the chat
left = await self.leave_chat(name, source)
if left == 0:
# Chat left
self.send_message(source, "Chat {} left".format(name))
elif left == 1:
# Chat does not exist
self.send_message(source, "Chat {} does not exist".format(name))
elif left == 2:
# Station is not in chat
self.send_message(source, "Not in chat {}".format(name))
async def handle_chat_message(self, packet):
"""Handle chat messages."""
# If there's missing arguments, send help. Otherwise, parse the chat name and message
if packet.message[0].lower() == "t":
if len(packet.message.split(' ')) < 3:
self.send_message(packet.source, "Usage: T <chat> <message>")
return
chat_name = packet.message.split(' ')[1].upper()
message = ' '.join(packet.message.split(' ')[2:])
else:
if len(packet.message.split(' ')) < 2:
self.send_message(packet.source, "Usage: .<chat> <message>")
return