-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
550 lines (452 loc) · 19.7 KB
/
Copy pathproxy.py
File metadata and controls
550 lines (452 loc) · 19.7 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
"""
NEMAPI Bridge - Proxy Python (HTTP Polling)
Communication avec l'extension Firefox via polling HTTP.
"""
import asyncio
import json
import uuid
from datetime import datetime
from urllib.parse import parse_qs, urlparse
class JobsManager:
def __init__(self):
self.jobs = {}
self.pending_queue = [] # File d'attente pour l'extension
def create_job(self, question):
job_id = str(uuid.uuid4())
job = {
"id": job_id,
"status": "pending",
"question": question,
"result": None,
"timestamp": datetime.now().isoformat()
}
self.jobs[job_id] = job
self.pending_queue.append(job)
print(f"[JOB] Cree: {job_id} - \"{question[:50]}...\"")
return job_id
def get_pending_job(self):
"""Recupere le prochain job en attente (pour l'extension)"""
while self.pending_queue:
job = self.pending_queue[0]
if job["status"] == "pending":
return job
self.pending_queue.pop(0)
return None
def set_result(self, job_id, result):
if job_id in self.jobs:
self.jobs[job_id]["status"] = "completed"
self.jobs[job_id]["result"] = result
print(f"[JOB] Complete: {job_id} - \"{result[:50]}...\"")
return True
return False
def set_error(self, job_id, error):
if job_id in self.jobs:
self.jobs[job_id]["status"] = "error"
self.jobs[job_id]["result"] = error
print(f"[JOB] Erreur: {job_id} - {error}")
return True
return False
def get_job(self, job_id):
return self.jobs.get(job_id)
def cancel_all_pending(self):
for job in self.jobs.values():
if job["status"] == "pending":
job["status"] = "cancelled"
job["result"] = "Annule par l'utilisateur"
self.pending_queue.clear()
print("[JOB] Tous les jobs annules")
jobs_manager = JobsManager()
# ============================================================
# ROUTEUR HTTP
# ============================================================
def parse_path_and_body(data):
"""Parse la requete HTTP, retourne (method, path, params, files)"""
try:
text = data.decode("utf-8", errors="replace")
except:
return None, None, {}, {}
lines = text.split("\r\n")
if not lines:
return None, None, {}, {}
first_line = lines[0]
parts = first_line.split(" ")
if len(parts) < 2:
return None, None, {}, {}
method = parts[0]
full_path = parts[1]
parsed = urlparse(full_path)
path = parsed.path
params = {k: v[0] for k, v in parse_qs(parsed.query).items()}
files = {}
if method == "POST":
# Trouver le Content-Type
content_type = ""
for line in lines[1:]:
if line.lower().startswith("content-type:"):
content_type = line.split(":", 1)[1].strip()
break
body_start = text.find("\r\n\r\n")
if body_start == -1:
return method, path, params, files
body_bytes = data[body_start+4:]
if "multipart/form-data" in content_type:
# Extraire le boundary
boundary = None
for part in content_type.split(";"):
if "boundary=" in part:
boundary = part.split("boundary=", 1)[1].strip().strip('"')
break
if boundary:
boundary_bytes = ("--" + boundary).encode()
parts = body_bytes.split(boundary_bytes)
for part in parts:
if b"Content-Disposition" not in part:
continue
part_text = part.decode("utf-8", errors="replace")
part_bytes = part
# Chercher le nom du champ
name = None
filename = None
for line in part_text.split("\r\n"):
if "Content-Disposition" in line:
for chunk in line.split(";"):
chunk = chunk.strip()
if chunk.startswith("name="):
name = chunk.split("=", 1)[1].strip().strip('"')
if chunk.startswith("filename="):
filename = chunk.split("=", 1)[1].strip().strip('"')
break
if not name:
continue
# Separer headers et contenu
header_end = part_bytes.find(b"\r\n\r\n")
if header_end == -1:
continue
content = part_bytes[header_end+4:]
# Enlever le \r\n final s'il existe
if content.endswith(b"\r\n"):
content = content[:-2]
if filename:
# C'est un fichier
import tempfile
import os
tmp = tempfile.NamedTemporaryFile(delete=False, suffix="-" + filename)
tmp.write(content)
tmp.close()
files[name] = {"filename": filename, "path": tmp.name, "size": len(content)}
else:
# C'est un champ texte
params[name] = content.decode("utf-8", errors="replace")
else:
# POST classique (form-urlencoded ou texte brut)
body_text = body_bytes.decode("utf-8", errors="replace")
try:
body_params = parse_qs(body_text)
for k, v in body_params.items():
params[k] = v[0]
except:
pass
return method, path, params, files
def route(method, path, params, files=None):
"""Route la requete vers le bon handler"""
if files is None:
files = {}
# CORS preflight
if method == "OPTIONS":
return 200, "", "text/plain"
# Extension polling
if path == "/job" and method == "GET":
return handle_poll_jobs()
if path == "/job" and method == "POST":
return handle_post_result(params)
if path == "/job/stop" and method == "GET":
return handle_stop_poll()
# Click via xdotool (depuis l'extension)
if path == "/click" and method == "GET":
return handle_click(params)
# API client
if path == "/ask" and method == "GET":
return handle_ask(params)
if path == "/ask" and method == "POST":
return handle_ask(params)
if path == "/result" and method == "GET":
return handle_result(params)
if path == "/status" and method == "GET":
return handle_status()
if path == "/stop" and method == "GET":
return handle_stop_client()
# Page d'accueil
if path == "/":
return 200, get_index_html(), "text/html"
return 404, "Not Found", "text/plain"
def handle_poll_jobs():
"""GET /job - L'extension demande s'il y a du travail"""
job = jobs_manager.get_pending_job()
if job:
# Marquer comme "in_progress" pour ne pas le redonner
job["status"] = "in_progress"
return 200, json.dumps({
"action": "ask",
"jobId": job["id"],
"question": job["question"]
}), "application/json"
else:
return 200, json.dumps({"action": "idle"}), "application/json"
def handle_post_result(params):
"""POST /job - L'extension envoie le resultat d'un job"""
job_id = params.get("jobId")
action = params.get("action")
if not job_id:
return 400, "jobId manquant", "text/plain"
if action == "result":
result = params.get("result", "")
jobs_manager.set_result(job_id, result)
return 200, "OK", "text/plain"
elif action == "error":
error = params.get("error", "Erreur inconnue")
jobs_manager.set_error(job_id, error)
return 200, "OK", "text/plain"
elif action == "stopped":
jobs_manager.set_error(job_id, "ANNULÉ")
return 200, "OK", "text/plain"
return 400, "Action inconnue", "text/plain"
def handle_stop_poll():
"""GET /job/stop - L'extension verifie si on doit arreter"""
# Verifier s'il y a des jobs annules
return 200, json.dumps({"stop": False}), "application/json"
def handle_ask(params):
"""GET /ask?q=... - Le client cree un job"""
question = params.get("q") or params.get("question")
if not question:
return 400, "Parametre 'q' manquant", "text/plain"
job_id = jobs_manager.create_job(question)
return 200, job_id, "text/plain"
def handle_result(params):
"""GET /result?id=... - Le client recupere le resultat"""
job_id = params.get("id")
if not job_id:
return 400, "Parametre 'id' manquant", "text/plain"
job = jobs_manager.get_job(job_id)
if not job:
return 404, "Job introuvable", "text/plain"
if job["status"] in ("pending", "in_progress"):
return 200, "STILL_WORKING", "text/plain"
elif job["status"] == "completed":
return 200, job["result"] or "", "text/plain"
elif job["status"] == "cancelled":
return 200, "ANNULÉ", "text/plain"
else:
return 500, job["result"] or "Erreur inconnue", "text/plain"
def handle_status():
"""GET /status - Etat du service (compatible Android)"""
if websocket_manager.extension_writer or True: # Toujours pret si le proxy tourne
return 200, "Ready", "text/plain"
return 200, "Accessibility Service Disabled", "text/plain"
def handle_click(params):
"""GET /click?x=403&y=482 - Clic via xdotool (bouge la souris physiquement)"""
import subprocess
x = params.get("x")
y = params.get("y")
if not x or not y:
return 400, "Parametres x et y requis", "text/plain"
try:
x = int(x)
y = int(y)
subprocess.run(["xdotool", "mousemove", str(x), str(y)], timeout=2, capture_output=True)
subprocess.run(["xdotool", "click", "1"], timeout=2, capture_output=True)
print(f"[CLICK] xdotool a ({x},{y})")
return 200, "OK", "text/plain"
except Exception as e:
print(f"[CLICK] Erreur xdotool: {e}")
return 500, f"Erreur xdotool: {e}", "text/plain"
def handle_stop_client():
"""GET /stop - Le client annule tout"""
jobs_manager.cancel_all_pending()
return 200, "STOP_SENT", "text/plain"
def get_index_html():
return """<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NEMAPI Bridge</title>
<style>
:root { --primary: #4361ee; --bg: #f8f9fa; --text: #2b2d42; --white: #ffffff; }
body { font-family: 'Inter', system-ui, sans-serif; background: var(--bg); color: var(--text); margin: 0; display: flex; height: 100vh; overflow: hidden; }
.sidebar { width: 260px; background: #1a1c2c; color: white; display: flex; flex-direction: column; }
.sidebar-header { padding: 30px 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
.sidebar-header h2 { margin: 0; font-size: 18px; }
.sidebar-footer { padding: 20px; font-size: 10px; opacity: 0.4; text-align: center; }
.main-container { flex: 1; display: flex; flex-direction: column; }
.messages { flex: 1; padding: 20px; display: flex; flex-direction: column; gap: 15px; overflow-y: auto; background: #fdfdfd; }
.msg { max-width: 85%; padding: 12px 18px; border-radius: 18px; line-height: 1.5; font-size: 0.95rem; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
.msg.user { align-self: flex-end; background: var(--primary); color: white; border-bottom-right-radius: 4px; }
.msg.bot { align-self: flex-start; background: #ececf1; color: var(--text); border-bottom-left-radius: 4px; white-space: pre-wrap; }
.input-container { padding: 20px; background: var(--white); border-top: 1px solid #eee; }
.input-wrapper { background: #f4f4f9; border-radius: 15px; padding: 8px 15px; display: flex; align-items: center; gap: 12px; }
textarea { flex: 1; background: transparent; border: none; outline: none; padding: 10px 0; font-family: inherit; font-size: 1rem; resize: none; max-height: 150px; }
.btn { width: 42px; height: 42px; border-radius: 50%; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 16px; }
.btn-send { background: var(--primary); color: white; }
.btn-stop { background: #D32F2F; color: white; display: none; }
.debug { margin: 10px 20px; background: #ffebee; color: #b71c1c; padding: 12px; border-radius: 8px; font-family: monospace; font-size: 12px; display: none; }
</style>
</head>
<body>
<div class="sidebar">
<div class="sidebar-header"><h2>NEMAPI Bridge</h2></div>
<div style="flex:1;padding:20px;color:rgba(255,255,255,0.5);font-size:12px;">
<p>Endpoints:</p>
<p>/ask /result /status /stop</p>
</div>
<div class="sidebar-footer">Firefox Extension</div>
</div>
<div class="main-container">
<div class="messages" id="msgs"><div class="msg bot">NEMAPI Bridge pret. Posez votre question.</div></div>
<div id="debug" class="debug"></div>
<div class="input-container">
<div class="input-wrapper">
<textarea id="q" placeholder="Votre question..." rows="1" oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px'"></textarea>
<button id="btnStop" class="btn btn-stop" onclick="stopAI()">■</button>
<button id="btnSend" class="btn btn-send" onclick="send()">↑</button>
</div>
</div>
</div>
<script>
const BASE = window.location.origin;
let currentJobId = null;
let polling = false;
async function send() {
const qInput = document.getElementById('q');
const text = qInput.value.trim();
if (!text) return;
addMsg(text, 'user');
qInput.value = '';
qInput.disabled = true;
document.getElementById('btnSend').style.display = 'none';
document.getElementById('btnStop').style.display = 'flex';
document.getElementById('debug').style.display = 'none';
const loadingMsg = addMsg("Envoi en cours...", 'bot');
try {
const askResp = await fetch(BASE + '/ask?q=' + encodeURIComponent(text));
currentJobId = await askResp.text();
loadingMsg.innerText = "L'IA reflechit...";
polling = true;
while (polling) {
await new Promise(r => setTimeout(r, 2000));
const res = await fetch(BASE + '/result?id=' + currentJobId);
const out = await res.text();
if (out === 'STILL_WORKING') {
continue;
} else if (out === 'ANNULÉ') {
loadingMsg.innerText = 'Annule.';
break;
} else if (out.startsWith('Erreur')) {
loadingMsg.innerText = out;
break;
} else {
loadingMsg.innerText = out;
break;
}
}
} catch (e) {
loadingMsg.innerText = 'Echec de la requete.';
document.getElementById('debug').innerText = 'Erreur: ' + e.message;
document.getElementById('debug').style.display = 'block';
} finally {
qInput.disabled = false;
document.getElementById('btnSend').style.display = 'flex';
document.getElementById('btnStop').style.display = 'none';
polling = false;
qInput.focus();
}
}
async function stopAI() {
polling = false;
try { await fetch(BASE + '/stop'); } catch(e) {}
addMsg('Arret envoye.', 'bot');
}
function addMsg(text, type) {
const div = document.createElement('div');
div.className = 'msg ' + type;
div.innerText = text;
document.getElementById('msgs').appendChild(div);
document.getElementById('msgs').scrollTop = document.getElementById('msgs').scrollHeight;
return div;
}
document.getElementById('q').addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
});
</script>
</body>
</html>"""
def build_http_response(status_code, body, content_type):
status_messages = {
200: "OK", 400: "Bad Request", 404: "Not Found",
500: "Internal Server Error", 503: "Service Unavailable"
}
message = status_messages.get(status_code, "Unknown")
body_bytes = body.encode() if isinstance(body, str) else body
headers = f"Content-Type: {content_type}; charset=utf-8\r\n"
headers += "Access-Control-Allow-Origin: *\r\n"
headers += "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n"
headers += "Access-Control-Allow-Headers: Content-Type\r\n"
headers += f"Content-Length: {len(body_bytes)}\r\n"
headers += "Connection: close\r\n"
return f"HTTP/1.1 {status_code} {message}\r\n{headers}\r\n".encode() + body_bytes
# ============================================================
# SERVEUR TCP
# ============================================================
async def handle_request(reader, writer):
try:
data = await asyncio.wait_for(reader.read(65536), timeout=30)
if not data:
writer.close()
return
result = parse_path_and_body(data)
if result[0] is None:
writer.close()
return
method, path, params, files = result
status, body, content_type = route(method, path, params, files)
response = build_http_response(status, body, content_type)
writer.write(response)
await writer.drain()
writer.close()
except asyncio.TimeoutError:
writer.close()
except Exception as e:
try:
response = build_http_response(500, f"Erreur: {str(e)}", "text/plain")
writer.write(response)
await writer.drain()
writer.close()
except:
pass
async def main():
import socket
host = "0.0.0.0"
port = 8080
# Trouver l'IP locale
local_ip = "127.0.0.1"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
s.close()
except:
pass
server = await asyncio.start_server(handle_request, host, port)
print("=" * 55)
print(" NEMAPI Bridge - Proxy HTTP")
print("=" * 55)
print(f" Local : http://127.0.0.1:{port}")
print(f" Reseau : http://{local_ip}:{port}")
print(f" Endpoints : /ask /result /status /stop")
print(f" Extension : /job (polling)")
print("=" * 55)
print(" Ouvrez l'URL Reseau sur votre telephone.")
print("=" * 55)
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())