This repository has been archived by the owner on Feb 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathexample-server.py
498 lines (430 loc) · 15.8 KB
/
example-server.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
import logging
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from typing import Set, Dict
from datetime import datetime, timedelta
import asyncio
import json
import sys
import random
app = FastAPI()
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s", handlers=[logging.StreamHandler(sys.stdout)])
logger = logging.getLogger(__name__)
html = """
<!DOCTYPE html>
<html>
<head>
<title>Global Capslock Key</title>
<link rel="icon" type="image/png" href="/favicon.png">
<meta name="viewport" content="width=device-width" />
<meta property="og:title" content="The Global Capslock Key" />
<meta property="og:url" content="https://globalcapslock.com" />
<meta property="og:type" content="website" />
<meta name="description" content="a synchronized global capslock key" />
<meta property="og:description" content="a synchronized global capslock key" />
<meta name="twitter:description" content="a synchronized global capslock key" />
<meta property="og:image" content="https://globalcapslock.com/social.png" />
<meta property="twitter:image" content="https://globalcapslock.com/social.png" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@itseieio" />
<meta name="twitter:creator" content="@itseieio" />
<meta name="twitter:title" content="The Global Capslock Key" />
<style>
* {
margin: 0;
}
:root {
--color-slate-100: #F1F5F9;
--color-slate-200: #E2E8F0;
--color-slate-300: #cbd5e1;
--color-slate-400: #94A3B8;
--color-slate-600: #475569;
--color-slate-800: #1e293b;
--color-yellow-400: #facc15;
--color-sky-100: #e0f2fe;
--color-blue-400: #60a5fa;
--color-green-500: #22C55E;
}
body {
line-height: 1.5;
-webkit-font-smoothing: antialiased;
font-family: monospace;
color: var(--color-slate-800);
background-color: var(--color-slate-300);
}
p,
h1,
h2,
h3,
h4,
h5,
h6 {
overflow-wrap: break-word;
}
.wrapper {
max-width: 1200px;
margin: 0 auto;
}
.all-upper {
text-transform: uppercase;
}
.all-lower {
text-transform: lowercase;
}
#status {
font-family: inherit;
color: inherit;
border: none;
font-size: 3rem;
padding: 1.5rem 1.25rem;
margin: 1rem;
border-radius: 8px;
margin: 0 auto;
min-width: 16ch;
gap: 2.5rem;
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
@media (max-width: 950px) {
font-size: 2.5rem;
}
@media (max-width: 700px) {
font-size: 2rem;
}
@media (max-width: 600px) {
font-size: 1.5rem;
}
transition: background-color ease 50ms;
}
#led {
border-radius: 50%;
width: 1rem;
height: 1rem;
}
.led-off {
background-color: var(--color-slate-800);
}
.led-on {
background-color: var(--color-green-500);
}
.enabled {
background-color: var(--color-yellow-400);
text-transform: uppercase;
}
.disabled {
background-color: var(--color-sky-100);
text-transform: lowercase;
}
.site-header-title {
font-size: 4rem;
text-align: center;
@media (max-width: 950px) {
font-size: 3rem;
}
@media (max-width: 700px) {
font-size: 2rem;
}
@media (max-width: 600px) {
font-size: 1.5rem;
}
}
.wrapper {
display: flex;
flex-direction: column;
padding: 1rem;
gap: 2rem;
}
.self-promo-outer {
display: flex;
flex-direction: column;
align-self: flex-end;
align-items: flex-end;
}
.self-promo-links {
display: flex;
flex-direction: row;
gap: 1rem;
}
#connected {
font-size: 0.75rem;
transition: opacity 0.5s ease;
text-align: center;
}
.not-visible {
opacity: 0;
}
a {
color: var(--color-blue-400);
}
#explainer {
display: flex;
flex-direction: column;
max-width: min(40ch, 80vw);
margin: 0 auto;
font-size: 1.125rem;
gap: 1.25rem;
@media (max-width: 950px) {
font-size: 1rem;
gap 0.5rem;
}
}
#caps-input {
font-size: 1.125rem;
padding: 0.5rem;
background-color: var(--color-slate-300);
border: 1px solid var(--color-slate-400);
border-radius: 4px;
max-width: min(40ch, 80vw);
width: 100%;
margin: 0 auto;
font-family: monospace;
height: 200px;
color: var(--color-slate-600);
}
#caps-input:focus {
outline: none;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="self-promo-outer">
<div class="self-promo-links">
<a href="https://x.com/itseieio">twitter</a>
<a href="https://bsky.app/profile/itseieio.bsky.social">bsky</a>
<a href="https://eieio.substack.com/">substack</a>
<a href="https://eieio.games/blog/the-global-capslock-key">?</a>
<a href="https://buymeacoffee.com/eieio">$</a>
</div>
<p>a utility from <a href="https://eieio.games">eieio</a></p>
</div>
<!--<h1 class="site-header-title">Global Caps Lock Status</h1>-->
<button id="status" class="disabled" onclick='alert("Not so fast!!\n\nIf you want to toggle the caps lock key, download the client.\n\nThen other people can toggle caps lock for you too :)")'>
<div id="led" class="led-off"></div>
<p id="status-text">caps lock is off</p>
</button>
<div id="explainer">
<p id="connected" class="not-visible">hey there</p>
<p>
the world shares this caps lock key
</p>
<p>
whenever anyone running <a href="https://github.com/nolenroyalty/global-capslock">the client</a> presses caps lock, it presses it for everyone else
</p>
<p>
finally we can all agree on when it's polite to use caps lock!
</p>
<p>
to join, <a href="https://github.com/nolenroyalty/global-capslock">download the client</a>
</p>
</div>
<textarea id="caps-input" name="caps-input" rows="5" cols="40">if you're not ready to run the client, you can type some text here if you'd like...</textarea>
</div>
<script>
const status = document.getElementById('status');
const statusText = document.getElementById('status-text');
const led = document.getElementById('led');
const connected = document.getElementById('connected');
let reconnectAttempts = 0;
let capsOn = false;
const maxDelay = 10000;
function connect() {
const ws = new WebSocket(`wss://${window.location.host}/status`);
ws.onmessage = function(event) {
data = event.data;
console.log(data);
if (data.startsWith('c')) {
count = data.split(" ")[1];
if (count !== undefined) {
const word = count === "1" ? 'person is' : 'people are';
connected.innerText = `${count} ${word} syncing their capslock key`;
connected.classList.remove('not-visible');
}
}
else if (data === "1") {
statusText.textContent = "CAPS LOCK IS ON!";
capsOn = true;
document.title = "GLOBAL CAPSLOCK KEY";
status.className = "enabled"
led.className = "led-on";
} else if (data === "0") {
statusText.textContent = "caps lock is off";
capsOn = false;
document.title = "global capslock key";
status.className = "disabled";
led.className = "led-off";
}
};
ws.onclose = function () {
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), maxDelay);
reconnectAttempts++;
setTimeout(connect, delay);
};
ws.onopen = function () {
reconnectAttempts = 0;
};
ws.onerror = function (error) {
console.error(`websocket error: ${error}`);
};
}
const capsInput = document.getElementById("caps-input");
capsInput.addEventListener("keydown", (event) => {
if (event.ctrlKey || event.altKey || event.metaKey || event.key.length > 1) {
return;
}
event.preventDefault();
const shift = event.shiftKey;
let char = event.key;
if (capsOn) {
char = shift ? char.toLowerCase() : char.toUpperCase();
} else {
char = shift ? char.toUpperCase() : char.toLowerCase();
}
capsInput.value += char;
});
connect();
</script>
</body>
</html>
"""
# there are some memory leaks here because it was the easiest way to prevent someone reconnecting to
# reset their rate limit. don't think about it too hard.
capslock_enabled = False
listening_clients = set()
connected_clients = {} # websocket -> IP
last_websocket_update: Dict[str, datetime] = {} # websocket rate limit
token_buckets = {} # per-ip token bucket limit
RATE_LIMIT_SECONDS = 0.33
MAX_TOKENS = 10
REFILL_TOKENS_PER_SECOND = 1.5
SPECIAL_RATE_LIMITS = {}
def refill_tokens(bucket):
now = datetime.now()
elapsed = (now - bucket["last_refill"]).total_seconds()
if elapsed > 0:
tokens = min(MAX_TOKENS, bucket["tokens"] + elapsed * REFILL_TOKENS_PER_SECOND)
bucket["tokens"] = tokens
bucket["last_refill"] = now
def _can_update_token_bucket(ip):
if ip not in token_buckets:
token_buckets[ip] = { "tokens": MAX_TOKENS, "last_refill": datetime.now() }
bucket = token_buckets[ip]
refill_tokens(bucket)
if bucket["tokens"] >= 1:
bucket["tokens"] -= 1
return True
return False
def _can_update_websocket_ratelimit(websocket, ip):
if ip is None:
logger.error(f"NO CLIENT IP?")
return True
now = datetime.now()
if websocket in last_websocket_update:
limit_seconds = SPECIAL_RATE_LIMITS.get(ip, RATE_LIMIT_SECONDS)
if now - last_websocket_update[websocket] < timedelta(seconds=limit_seconds):
return False
last_websocket_update[websocket] = now
return True
def can_update(websocket):
ip = connected_clients.get(websocket)
has_tokens = _can_update_token_bucket(ip)
limit_ok = _can_update_websocket_ratelimit(websocket, ip)
return has_tokens and limit_ok
def client_ip_of_websocket(websocket):
headers = dict(websocket.headers)
client_ip = websocket.client.host
if headers.get("cf-connecting-ip"):
return headers.get("cf-connecting-ip")
elif headers.get("x-forwarded-for"):
s = headers.get("x-forwarded-for", "").split(",")
return s[-1]
logger.error(f"USING RAW CLIENT IP? {client_ip}")
return client_ip
@app.get("/")
async def get():
return HTMLResponse(html)
def message_for_state():
return "1" if capslock_enabled else "0"
async def broadcast_state(message):
"""Send current state to all connected clients"""
if connected_clients:
for websocket in connected_clients.copy(): # Copy to avoid modification during iteration
try:
ip = connected_clients.get(websocket, "")
await websocket.send_text(message)
except:
ip = connected_clients.get(websocket)
connected_clients.pop(websocket, None)
last_websocket_update.pop(websocket, None)
#token_buckets.pop(ip, None)
if listening_clients:
for websocket in listening_clients.copy():
try:
await websocket.send_text(message)
except:
try:
listening_clients.remove(websocket)
except KeyError:
pass
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global capslock_enabled
await websocket.accept()
client_ip = client_ip_of_websocket(websocket)
connected_clients[websocket] = client_ip
logger.info(f"{client_ip} CONNECTED")
try:
await websocket.send_text(message_for_state())
while True:
try:
data = await websocket.receive_text()
if not can_update(websocket):
continue
if len(data) > 1:
logger.info(f"received invalid data (length: {len(data)} | client: {client_ip})")
elif data == "1" and capslock_enabled != True:
capslock_enabled = True
elif data == "0" and capslock_enabled != False:
capslock_enabled = False
except json.JSONDecodeError:
pass
except WebSocketDisconnect:
try:
#ip = connected_clients.get(websocket)
#if ip and ip in token_buckets:
#token_buckets.pop(ip)
connected_clients.pop(websocket)
except KeyError:
return
def connected_client_count():
return f"c {len(connected_clients)}"
@app.websocket("/status")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
listening_clients.add(websocket)
try:
await websocket.send_text(connected_client_count())
await websocket.send_text(message_for_state())
while True:
await asyncio.sleep(5)
await websocket.send_text(connected_client_count())
except:
try:
listening_clients.remove(websocket)
except KeyError:
pass
@app.on_event("startup")
async def startup_event():
async def periodic_broadcast():
last_message = None
while True:
message = message_for_state()
if last_message is None or last_message != message:
last_message = message
await broadcast_state(message)
await asyncio.sleep(0.05)
asyncio.create_task(periodic_broadcast())
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)