-
Notifications
You must be signed in to change notification settings - Fork 0
/
celestenet_chat_minimal.py
255 lines (208 loc) · 9.2 KB
/
celestenet_chat_minimal.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
import os
import asyncio
import traceback
import json
import time
from enum import Enum, auto
import websockets
import requests
import dotenv
class State(Enum):
Invalid = -1
WaitForType = auto()
WaitForCMDID = auto()
WaitForCMDPayload = auto()
WaitForData = auto()
dotenv.load_dotenv()
ws_commands = {}
class CelesteNetChat:
cookies = {}
def __init__(self):
self.cookies = os.getenv("CNET_COOKIE")
#self.cookies = '{"celestenet-key":"0218d174e60c4bd4", "celestenet-discordauth":"xjBDRETFq2aK83bDcr1GxL2u1tyPKv", "celestenet-session": "214c3291-ad8f-4cef-b1ad-5b2fe40dcb15"}'
if isinstance(self.cookies, str):
self.cookies = json.loads(self.cookies)
self.command_state = State.WaitForType
self.command_current = None
#self.ws_uri: str = 'wss://celestenet.0x0a.de/api/ws'
#self.origin: str = 'https://celestenet.0x0a.de'
#self.server: str = 'DESKTOP-BMPV2QM.fritz.box:3800'
#self.server: str = '192.168.178.31:3800'
self.server: str = 'celestenet.0x0a.de:17240'
self.origin: str = 'http://' + self.server
self.api_base: str = self.origin + '/api'
self.ws_uri: str = 'ws://' + self.server + '/api/ws'
self.players: dict[int, str] = {}
self.channels: dict[int, str] = {}
self.player_in_channel: dict[int, int] = {}
def status_message(self, prefix="INFO", message=""):
print(f"[{prefix}] {message}")
def api_fetch(self, endpoint: str, requests_method=requests.get, requests_data: str = None, raw: bool = False):
"""Perform HTTP requests to Celestenet api
Parameters
----------
endpoint: str
Something like '/auth' that gets tacked onto the api base URI
requests_method
Just a lazy way so that this function can "wrap" requests.get, requests.post and whatever else
requests_data: str, optional
Content to send with the request, e.g. for POST
raw: bool
Function tries to parse successful responses as JSON unless this is set to True
"""
response = requests_method(self.api_base + endpoint, data=requests_data, cookies=self.cookies)
if response.status_code != 200:
self.status_message("WARN", f"Failed api call {requests_method} to {endpoint} with status {response.status_code}")
self.status_message("WARN", f">> {response.text}")
return None
if raw:
return response.text
try:
return response.json()
except json.decoder.JSONDecodeError:
self.status_message("WARN", f"Error decoding {endpoint} response: {response.text}")
return None
def get_players(self):
"""Wrapper logic around /api/players
"""
players = self.api_fetch("/players")
if isinstance(players, list):
for pdict in players:
pid = pdict['ID']
self.players[pid] = pdict['FullName']
if pid not in self.player_in_channel:
self.player_in_channel[pid] = 0
def get_status(self):
"""Wrapper logic around /api/status
"""
self.status_message(str(self.api_fetch("/status")))
def get_channels(self):
"""Wrapper logic around /api/channels
"""
channels = self.api_fetch("/channels")
if isinstance(channels, list):
for cdict in channels:
cid = cdict['ID']
self.channels[cid] = cdict['Name']
for pid in cdict['Players']:
if pid in self.players:
self.player_in_channel[pid] = cid
@staticmethod
def command_handler(cmd_fn):
ws_commands[cmd_fn.__name__] = cmd_fn
@command_handler
def chat(self, data: str):
try:
message = json.loads(data)
except json.JSONDecodeError:
self.status_message("ERROR", f"Failed to parse chat payload: {data}")
return
print(f"{message}")
# idk do stuff here lol I'm getting tired of copying from celestenet.py
print(data.replace('\n',' ').replace('\r',' '))
@command_handler
def chan_create(self, data: str):
print(data.replace('\n',' ').replace('\r',' '))
@command_handler
def chan_move(self, data: str):
print(data.replace('\n',' ').replace('\r',' '))
@command_handler
def chan_remove(self, data: str):
print(data.replace('\n',' ').replace('\r',' '))
@command_handler
def sess_join(self, data: str):
print(data.replace('\n',' ').replace('\r',' '))
@command_handler
def sess_leave(self, data: str):
print(data.replace('\n',' ').replace('\r',' '))
@command_handler
def update(self, data: str):
try:
data = json.loads(data)
except json.decoder.JSONDecodeError:
self.status_message("WARN", f"Failed to parse update cmd payload: {data}.")
return
print(f"cmd update: {data}")
match data:
case str(s) if s.endswith("/players"):
self.get_players()
case str(s) if s.endswith("/status"):
self.get_status()
case str(s) if s.endswith("/channels"):
self.get_channels()
case _:
print(f"cmd update: {data} not implemented.")
async def socket_relay(self):
"""
- tries to auth with cookies and such
- opens and re-opens websocket connection with an endless loop
- attempts auth against WS too
- handles the various WS commands
"""
print(f"Fetching /auth ...")
auth = self.api_fetch("/auth", requests.get)
if isinstance(auth, dict) and 'Key' in auth:
self.cookies['celestenet-session'] = auth['Key']
self.status_message(f"Auth: {auth['Info']}")
else:
self.cookies.pop('celestenet-session', None)
self.status_message(f"Key not in reauth: {auth}")
print(f"Getting status, players, channels ...")
self.get_status()
self.get_players()
self.get_channels()
print(f"Starting websocket ...")
async for ws in websockets.connect(self.ws_uri, origin=self.origin):
if 'celestenet-session' in self.cookies:
await ws.send("cmd")
await ws.send("reauth")
await ws.send(json.dumps(self.cookies['celestenet-session']))
print(f"Going into main loop ...")
while True:
try:
ws_data = await ws.recv()
match self.command_state:
case State.WaitForType:
match ws_data:
case "cmd":
self.command_state = State.WaitForCMDID
case "data":
self.command_state = State.WaitForData
case _:
print(f"Unknown ws 'type': {ws_data}")
break
case State.WaitForCMDID:
ws_cmd = None
if ws_data in ws_commands:
ws_cmd = ws_commands[ws_data]
if ws_cmd is None:
print(f"Unknown ws command: {ws_data}")
print(f" Unknown ws command: {ws_data}")
print(f" Unknown ws command: {ws_data}")
self.command_state = State.WaitForType
self.command_current = None
else:
self.command_current = ws_cmd
self.command_state = State.WaitForCMDPayload
case State.WaitForCMDPayload:
if self.command_current:
self.command_current(self, ws_data)
self.command_state = State.WaitForType
self.command_current = None
else:
print(f"Got payload but no current command: {ws_data}")
self.command_state = State.WaitForType
self.command_current = None
case State.WaitForData:
print(f"Got ws 'data' which isn't properly implemented: {ws_data}")
self.command_state = State.WaitForType
self.command_current = None
case _:
print(f"Unknown ws state: {command_state}")
self.command_state = State.WaitForType
self.command_current = None
except websockets.ConnectionClosed:
self.status_message("WARN", "websocket died.")
break
celery = CelesteNetChat()
asyncio.get_event_loop().run_until_complete(celery.socket_relay())