Fffffd commited on
Commit
73b0c22
·
verified ·
1 Parent(s): e319105

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -41
app.py CHANGED
@@ -1,55 +1,171 @@
1
  import asyncio
 
2
  import threading
3
- import uuid
4
- from fastapi import FastAPI, BackgroundTasks
5
- from fastapi.responses import JSONResponse
 
 
6
  import uvicorn
7
-
8
- # Istihbarat modülünü içe aktar
9
- # !!! DİKKAT: Bu dosya 'Istihbarat.py' ile aynı klasörde olmalı !!!
10
  import Istihbarat
11
 
12
  app = FastAPI()
13
 
14
- # Çalışan işlemleri takip etmek için basit bir sözlük
15
- tasks_status = {}
16
-
17
- def run_istihbarat(task_id: str):
18
- """Istihbarat modülünü arka planda çalıştırır."""
19
- try:
20
- # Istihbarat modülünün ana fonksiyonunu çağır
21
- # Bu fonksiyon genelde sonsuz döngüye girer, bu yüzden bir thread'de çalıştırılır.
22
- Istihbarat.istihbarat_modulu()
23
- tasks_status[task_id] = "Tamamlandı"
24
- except Exception as e:
25
- tasks_status[task_id] = f"Hata: {str(e)}"
26
 
27
- @app.get("/")
28
- async def root():
29
- """Ana sayfa, sunucunun çalıştığını gösterir."""
30
- return {"message": "Dexo API Sunucusu Çalışıyor!", "status": "online"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- @app.post("/start")
33
- async def start_istihbarat(background_tasks: BackgroundTasks):
34
- """Istihbarat modülünü başlatmak için endpoint."""
35
- task_id = str(uuid.uuid4())
36
- tasks_status[task_id] = "Başlatılıyor..."
37
 
38
- # Arka planda çalıştır
39
- background_tasks.add_task(run_istihbarat, task_id)
40
-
41
- return JSONResponse(content={
42
- "message": "Istihbarat modülü başlatılıyor...",
43
- "task_id": task_id,
44
- "status_url": f"/status/{task_id}"
45
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- @app.get("/status/{task_id}")
48
- async def get_status(task_id: str):
49
- """İşlemin durumunu sorgulamak için endpoint."""
50
- status = tasks_status.get(task_id, "Bilinmeyen işlem ID'si")
51
- return {"task_id": task_id, "status": status}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # Sunucuyu başlatmak için (Docker'da CMD ile çağrılacak)
54
  if __name__ == "__main__":
55
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  import asyncio
2
+ import json
3
  import threading
4
+ import queue
5
+ import sys
6
+ import io
7
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
8
+ from fastapi.responses import HTMLResponse
9
  import uvicorn
 
 
 
10
  import Istihbarat
11
 
12
  app = FastAPI()
13
 
14
+ # Istihbarat modülünün çıktısını yakalamak için
15
+ output_queue = queue.Queue()
16
+ input_queue = queue.Queue()
 
 
 
 
 
 
 
 
 
17
 
18
+ class IstihbaratThread(threading.Thread):
19
+ def __init__(self):
20
+ super().__init__()
21
+ self.daemon = True
22
+ self.running = True
23
+
24
+ def run(self):
25
+ # stdout'u yakala
26
+ old_stdout = sys.stdout
27
+ sys.stdout = self.CaptureOutput()
28
+
29
+ try:
30
+ # Istihbarat modülünü çalıştır
31
+ Istihbarat.istihbarat_modulu()
32
+ except Exception as e:
33
+ output_queue.put(f"[HATA] {str(e)}")
34
+ finally:
35
+ sys.stdout = old_stdout
36
+
37
+ class CaptureOutput:
38
+ def write(self, text):
39
+ if text.strip():
40
+ output_queue.put(text)
41
+ def flush(self):
42
+ pass
43
 
44
+ # Istihbarat thread'ini başlat
45
+ istihbarat_thread = IstihbaratThread()
46
+ istihbarat_thread.start()
 
 
47
 
48
+ @app.websocket("/ws")
49
+ async def websocket_endpoint(websocket: WebSocket):
50
+ await websocket.accept()
51
+ print("✅ İstemci bağlandı!")
52
+
53
+ # Istihbarat'a input göndermek için
54
+ def send_input_to_istihbarat(text):
55
+ input_queue.put(text + "\n")
56
+
57
+ try:
58
+ while True:
59
+ # İstemciden mesaj bekle
60
+ try:
61
+ data = await asyncio.wait_for(websocket.receive_text(), timeout=0.1)
62
+ if data.startswith("/input"):
63
+ # Istihbarat'a input gönder
64
+ command = data[6:].strip()
65
+ send_input_to_istihbarat(command)
66
+ await websocket.send_text(f"[INPUT] Gönderildi: {command}")
67
+ elif data == "/ping":
68
+ await websocket.send_text("pong")
69
+ elif data == "/status":
70
+ await websocket.send_text(f"[STATUS] Istihbarat çalışıyor: {istihbarat_thread.is_alive()}")
71
+ except asyncio.TimeoutError:
72
+ pass
73
+ except WebSocketDisconnect:
74
+ break
75
+
76
+ # Istihbarat çıktısını kontrol et
77
+ outputs = []
78
+ while not output_queue.empty():
79
+ try:
80
+ outputs.append(output_queue.get_nowait())
81
+ except:
82
+ break
83
+
84
+ if outputs:
85
+ await websocket.send_text("".join(outputs))
86
+
87
+ await asyncio.sleep(0.1)
88
+
89
+ except WebSocketDisconnect:
90
+ print("❌ İstemci bağlantısı koptu!")
91
 
92
+ @app.get("/")
93
+ async def get():
94
+ return HTMLResponse("""
95
+ <html>
96
+ <head>
97
+ <title>Dexo API - Interaktif</title>
98
+ <style>
99
+ body { background: #1a1a2e; color: #00ff41; font-family: monospace; margin: 0; padding: 20px; }
100
+ #output { height: 70vh; overflow-y: auto; background: #0d0d1a; padding: 10px; border: 1px solid #00ff41; border-radius: 5px; white-space: pre-wrap; }
101
+ #input { width: 80%; background: #0d0d1a; color: #00ff41; border: 1px solid #00ff41; padding: 10px; border-radius: 5px; }
102
+ button { background: #00ff41; color: #0d0d1a; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; }
103
+ .status { color: #ffd700; }
104
+ </style>
105
+ </head>
106
+ <body>
107
+ <h1>🖥️ DEXO API - İnteraktif Terminal</h1>
108
+ <div id="output">Bağlantı bekleniyor...</div>
109
+ <div style="margin-top: 10px;">
110
+ <input id="input" placeholder="Komut girin..." />
111
+ <button onclick="sendCommand()">Gönder</button>
112
+ <button onclick="clearOutput()">Temizle</button>
113
+ </div>
114
+ <div style="margin-top: 5px;">
115
+ <span class="status">🟢 Çevrimiçi</span>
116
+ <span style="margin-left: 20px;">💡 İpucu: Istihbarat modülüne komut göndermek için "/input komut" yazın</span>
117
+ </div>
118
+ <script>
119
+ let ws;
120
+ let outputDiv = document.getElementById('output');
121
+ let inputField = document.getElementById('input');
122
+
123
+ function connect() {
124
+ ws = new WebSocket(`wss://${window.location.host}/ws`);
125
+
126
+ ws.onopen = function() {
127
+ outputDiv.innerHTML = '✅ Bağlantı kuruldu!\\n';
128
+ outputDiv.innerHTML += '💡 Istihbarat modülü çalışıyor...\\n';
129
+ outputDiv.innerHTML += '📝 Komut göndermek için: /input [komut]\\n';
130
+ outputDiv.innerHTML += '─────────────────────────────────\\n';
131
+ };
132
+
133
+ ws.onmessage = function(event) {
134
+ outputDiv.innerHTML += event.data + '\\n';
135
+ outputDiv.scrollTop = outputDiv.scrollHeight;
136
+ };
137
+
138
+ ws.onclose = function() {
139
+ outputDiv.innerHTML += '❌ Bağlantı koptu! Yeniden bağlanılıyor...\\n';
140
+ setTimeout(connect, 3000);
141
+ };
142
+ }
143
+
144
+ function sendCommand() {
145
+ let cmd = inputField.value;
146
+ if (cmd) {
147
+ if (ws.readyState === WebSocket.OPEN) {
148
+ ws.send(cmd);
149
+ inputField.value = '';
150
+ } else {
151
+ outputDiv.innerHTML += '⚠️ Bağlantı yok!\\n';
152
+ }
153
+ }
154
+ }
155
+
156
+ function clearOutput() {
157
+ outputDiv.innerHTML = '';
158
+ }
159
+
160
+ inputField.addEventListener('keypress', function(e) {
161
+ if (e.key === 'Enter') sendCommand();
162
+ });
163
+
164
+ connect();
165
+ </script>
166
+ </body>
167
+ </html>
168
+ """)
169
 
 
170
  if __name__ == "__main__":
171
  uvicorn.run(app, host="0.0.0.0", port=7860)