forked from Special-K-s-Flightsim-Bots/DCSServerBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.py
More file actions
368 lines (324 loc) · 14.1 KB
/
player.py
File metadata and controls
368 lines (324 loc) · 14.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
from __future__ import annotations
import asyncio
import discord
from core import utils
from core.data.dataobject import DataObject, DataObjectFactory
from core.data.const import Side, Coalition
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, AsyncGenerator
from typing_extensions import override
from core.services.registry import ServiceRegistry
if TYPE_CHECKING:
from .server import Server
from services.bot import DCSServerBot
__all__ = ["Player"]
@dataclass
@DataObjectFactory.register()
class Player(DataObject):
server: Server = field(compare=False)
id: int = field(compare=False)
active: bool = field(compare=False)
side: Side = field(compare=False)
ucid: str
ipaddr: str
connected: bool = field(compare=False, default=True, init=False)
banned: bool = field(compare=False, default=False, init=False)
slot: int = field(compare=False, default=0)
sub_slot: int = field(compare=False, default=0)
unit_callsign: str = field(compare=False, default='')
unit_id: int = field(compare=False, default=0)
unit_name: str = field(compare=False, default='')
unit_display_name: str = field(compare=False, default='')
unit_type: str = field(compare=False, default='')
group_id: int = field(compare=False, default=0)
group_name: str = field(compare=False, default='')
_member: discord.Member = field(compare=False, repr=False, default=None, init=False)
_verified: bool = field(compare=False, default=False)
coalition: Coalition = field(compare=False, default=None)
_watchlist: bool = field(compare=False, default=False)
_vip: bool = field(compare=False, default=False)
bot: DCSServerBot = field(compare=False, init=False)
pending: bool = field(compare=False, default=False)
@override
def __post_init__(self):
from services.bot import BotService
super().__post_init__()
self.bot = ServiceRegistry.get(BotService).bot
if self.id == 1:
self.active = False
return
lock_time = self.server.locals.get('coalitions', {}).get('lock_time', '1 day')
with self.pool.connection() as conn:
with conn.transaction():
# add new players to the database
conn.execute("""
INSERT INTO players (ucid, discord_id, name, last_seen)
VALUES (%s, -1, %s, (now() AT TIME ZONE 'utc'))
ON CONFLICT (ucid) DO UPDATE SET name=excluded.name, last_seen=excluded.last_seen
""", (self.ucid, self.name))
# get the player information
cursor = conn.execute(f"""
SELECT DISTINCT p.discord_id, CASE WHEN b.ucid IS NOT NULL THEN TRUE ELSE FALSE END AS banned,
p.manual, c.coalition,
CASE WHEN w.player_ucid IS NOT NULL THEN TRUE ELSE FALSE END AS watchlict, p.vip
FROM players p LEFT OUTER JOIN bans b ON p.ucid = b.ucid
LEFT OUTER JOIN coalitions c
ON p.ucid = c.player_ucid
AND c.server_name = %s
AND c.coalition_join > (NOW() AT TIME ZONE 'UTC' - interval '{lock_time}')
LEFT OUTER JOIN watchlist w ON p.ucid = w.player_ucid
WHERE p.ucid = %s
AND COALESCE(b.banned_until, (now() AT TIME ZONE 'utc')) >= (now() AT TIME ZONE 'utc')
""", (self.server.name, self.ucid))
# existing member found?
if cursor.rowcount == 1:
row = cursor.fetchone()
self._member = self.bot.get_member_by_ucid(self.ucid)
if self._member:
# special handling for discord-less bots
if isinstance(self._member, discord.Member):
self._verified = row[2]
else:
self._verified = True
self.banned = row[1]
if row[3]:
self.coalition = Coalition(row[3])
self._watchlist = row[4]
self._vip = row[5]
else:
rules = self.server.locals.get('rules')
if rules:
cursor.execute("""
INSERT INTO messages (sender, player_ucid, message, ack)
VALUES (%s, %s, %s, %s)
""", (self.server.locals.get('server_user', 'Admin'), self.ucid, rules,
self.server.locals.get('accept_rules_on_join', False)))
# if automatch is enabled, try to match the user
if not self.member and self.bot.locals.get('automatch', False):
discord_user = self.bot.match_user({"ucid": self.ucid, "name": self.name})
if discord_user:
self.member = discord_user
def is_active(self) -> bool:
return self.active
def is_connected(self) -> bool:
return self.connected
def is_multicrew(self) -> bool:
return self.sub_slot != 0
def is_banned(self) -> bool:
return self.banned
@property
def member(self) -> discord.Member:
return self._member
@member.setter
def member(self, member: discord.Member) -> None:
if member != self._member:
self.update_member(member)
self._member = member
def update_member(self, member: discord.Member) -> None:
with self.pool.connection() as conn:
with conn.transaction():
conn.execute('UPDATE players SET discord_id = %s WHERE ucid = %s',
(member.id if member else -1, self.ucid))
@property
def verified(self) -> bool:
return self._verified
@verified.setter
def verified(self, verified: bool) -> None:
if verified == self._verified:
return
self.update_verified(verified)
self._verified = verified
def update_verified(self, verified: bool) -> None:
with self.pool.connection() as conn:
with conn.transaction():
conn.execute('UPDATE players SET manual = %s WHERE ucid = %s', (verified, self.ucid))
if verified:
# delete all old automated links (this will delete the token also)
conn.execute("DELETE FROM players WHERE ucid = %s AND manual = FALSE", (self.ucid,))
conn.execute("DELETE FROM players WHERE discord_id = %s AND length(ucid) = 4",
(self.member.id,))
conn.execute("UPDATE players SET discord_id = -1 WHERE discord_id = %s AND manual = FALSE",
(self.member.id,))
@property
def watchlist(self) -> bool:
return self._watchlist
@property
def vip(self) -> bool:
return self._vip
@vip.setter
def vip(self, vip: bool):
self.update_vip(vip)
self._vip = vip
def update_vip(self, vip: bool) -> None:
with self.pool.connection() as conn:
with conn.transaction():
conn.execute('UPDATE players SET vip = %s WHERE ucid = %s', (vip, self.ucid))
@property
def display_name(self) -> str:
return utils.escape_string(self.name)
async def update(self, data: dict):
async with self.apool.connection() as conn:
if 'id' in data:
# if the ID has changed (due to reconnect), we need to update the server list
if self.id != data['id']:
self.id = data['id']
self.server.players_by_id[self.id] = self
if 'active' in data:
self.active = data['active']
if 'name' in data and self.name != data['name']:
self.name = data['name']
await conn.execute('UPDATE players SET name = %s WHERE ucid = %s', (self.name, self.ucid))
if 'side' in data:
self.side = Side(data['side'])
if 'slot' in data:
self.slot = int(data['slot'])
if 'sub_slot' in data:
self.sub_slot = data['sub_slot']
if 'unit_callsign' in data:
self.unit_callsign = data['unit_callsign']
if 'unit_id' in data:
self.unit_id = data['unit_id']
if 'unit_name' in data:
self.unit_name = data['unit_name']
if 'unit_type' in data and data['unit_type'] != self.unit_type:
self.unit_type = data['unit_type']
# we changed the slot in the slot menu, but we are not in the plane yet
self.pending = True
if 'group_name' in data:
self.group_name = data['group_name']
if 'group_id' in data:
self.group_id = data['group_id']
if 'unit_display_name' in data:
self.unit_display_name = data['unit_display_name']
if 'ipaddr' in data:
self.ipaddr = data['ipaddr']
await conn.execute("""
UPDATE players SET last_seen = (now() AT TIME ZONE 'utc')
WHERE ucid = %s
""", (self.ucid, ))
def has_discord_roles(self, roles: list[str | int]) -> bool:
valid_roles = []
for role in roles:
valid_roles.extend(self.bot.roles[role])
return self.verified and self._member is not None and utils.check_roles(set(valid_roles), self._member)
async def sendChatMessage(self, message: str, sender: str = None):
async def message_lines(m: str) -> AsyncGenerator[str, None]:
for line in m.splitlines():
yield line
async for msg in message_lines(message):
await self.server.send_to_dcs({
"command": "sendChatMessage",
"to": self.id,
"from": sender,
"message": msg
})
async def sendUserMessage(self, message: str, timeout: int | None = -1):
asyncio.create_task(self.sendPopupMessage(message, timeout))
asyncio.create_task(self.sendChatMessage(message))
async def sendPopupMessage(self, message: str, timeout: int | None = -1, sender: str = None):
if timeout == -1:
timeout = self.server.locals.get('message_timeout', 10)
await self.server.send_to_dcs({
"command": "sendPopupMessage",
"from": sender,
"to": "unit",
"id": self.unit_name,
"message": message,
"time": timeout
})
async def playSound(self, sound: str):
await self.server.send_to_dcs({
"command": "playSound",
"to": "unit",
"id": self.unit_name,
"sound": sound
})
async def add_role(self, role: str | int):
if not self.member or not role:
return
try:
_role = self.bot.get_role(role)
if not _role:
self.log.error(f'Role {role} not found!')
return
await self.member.add_roles(_role)
except discord.Forbidden:
await self.bot.audit('permission "Manage Roles" missing.', user=self.bot.member)
except discord.DiscordException as ex:
self.log.error(f"Error while adding role {role}: {ex}")
async def remove_role(self, role: str | int):
if not self.member or not role:
return
try:
_role = self.bot.get_role(role)
if not _role:
self.log.error(f'Role {role} not found!')
return
await self.member.remove_roles(_role)
except discord.Forbidden:
await self.bot.audit('permission "Manage Roles" missing.', user=self.bot.member)
except discord.DiscordException as ex:
self.log.error(f"Error while removing role {role}: {ex}")
def check_exemptions(self, exemptions: dict | list) -> bool:
def _check_exemption(exemption: dict) -> bool:
if 'ucid' in exemption:
if not isinstance(exemption['ucid'], list):
ucids = [exemption['ucid']]
else:
ucids = exemption['ucid']
if self.ucid in ucids:
return True
if 'discord' in exemption:
if not self.member:
return False
if not isinstance(exemption['discord'], list):
roles = [exemption['discord']]
else:
roles = exemption['discord']
if utils.check_roles(roles, self.member):
return True
return False
if isinstance(exemptions, list):
ret = False
for exemption in exemptions:
ret = _check_exemption(exemption) | ret
else:
ret = _check_exemption(exemptions)
return ret
async def makeScreenshot(self) -> None:
await self.server.send_to_dcs({
"command": "makeScreenshot",
"id": self.id
})
async def getScreenshots(self) -> list[str]:
data = await self.server.send_to_dcs_sync({
"command": "getScreenshots",
"id": self.id
})
return data.get('screens', [])
async def deleteScreenshot(self, key: str) -> None:
await self.server.send_to_dcs({
"command": "deleteScreenshot",
"id": self.id,
"key": key
})
async def lock(self) -> None:
await self.server.send_to_dcs({
"command": "lock_player",
"ucid": self.ucid
})
async def unlock(self) -> None:
await self.server.send_to_dcs({
"command": "unlock_player",
"ucid": self.ucid
})
async def mute(self) -> None:
await self.server.send_to_dcs({
"command": "mute_player",
"ucid": self.ucid
})
async def unmute(self) -> None:
await self.server.send_to_dcs({
"command": "unmute_player",
"ucid": self.ucid
})