-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
499 lines (438 loc) Β· 15.9 KB
/
app.py
File metadata and controls
499 lines (438 loc) Β· 15.9 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
# -*- coding: UTF-8 -*-
# Internet Connection Monitor daemon - nelbren@nelbren.com @ 2025-05-31
import os
import re
import time
import socket
import requests
import platform
import subprocess
from datetime import datetime, date
from canvas import getStudents
from flask_socketio import SocketIO
from flask import Flask, render_template, request, jsonify
MY_VERSION = 2.4
ICM_VERSION = 5.3
DEBUG = 0
lastAlarm = 0
secsAlarmMax = 60
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*", ssl_context=None)
def checkICM():
homeDir = os.path.expanduser("~")
cmd = os.path.join(homeDir, 'ICM', '.bin', 'nircmdc.exe')
if not os.path.exists(cmd):
print("Por favor ejecute los siguientes comandos:\n")
print(" cd..\n git clone https://github.com/nelbren/ICM.git")
exit(4)
def checkUpdate():
url = 'https://raw.githubusercontent.com/nelbren'
url += '/ICMd/refs/heads/main/app.py'
try:
response = requests.get(url)
if response.status_code == 200:
content = response.text
match = re.search(r"MY_VERSION\s*=\s*(\d+\.\d+)", content)
if match:
version = match.group(1)
version = float(version)
if version != MY_VERSION:
print(f"π» ICMd v{MY_VERSION} != π ICMd v{version}"
" -> Please update, with: git pull")
exit(1)
else:
print("No se encontrΓ³ la versiΓ³n.")
exit(2)
else:
print(f"Error al acceder a la pΓ‘gina: {response.status_code}")
exit(3)
except Exception as e:
print("No puedo verificar si hay nueva actualizaciΓ³n π’\n")
print(e, "\n")
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
def get_status_row_color(id, row, last_update, status, ignored):
elapsed = time.time() - last_update
# print(elapsed, "STATUS ->", status)
if status == "π":
if not ignored:
playSoundWithInternet(row)
# return "red", status
elif status == "π€":
if not ignored:
playSoundWithIA(row)
# return "red", status
if elapsed < 25:
return "green", status
elif elapsed < 40:
return "yellow", status
elif elapsed < 55:
if "countTimeout" not in clients_status[id]:
# print("πINICIALIZACIΓN")
clients_status[id]["countTimeout"] = 0
print('ANTES clients_status ->', clients_status)
countTimeout = clients_status[id]["countTimeout"]
countTimeout += 1
clients_status[id]["countTimeout"] = countTimeout
print('DESPUES clients_status ->', clients_status)
return "red", "βοΈ"
else:
return "red", "β"
def get_status_col_color(condition):
return "green" if condition == "βοΈ" else "red"
def get_status_emoji(status):
if status == "OK":
return "βοΈ"
if status == "INTERNET":
return "π"
if status == "IA":
return "π€"
return "β"
def get_os_emoji(OS):
if OS in ["MACOS", "DARWIN"]:
return "π"
elif OS == "LINUX":
return "π§"
elif OS == "WINDOWS":
return "πͺ"
elif OS == "RASPBERRY":
return "π"
print("OS ->", OS)
return "βοΈ"
def getOSM():
OS = platform.system().upper()
if OS == "Linux":
fileModel = '/proc/device-tree/model'
if os.path.exists(fileModel):
with open(fileModel) as f:
model = f.read()
if 'Raspberry' in model:
OS = 'Raspberry'
return OS.upper()
def getOSL():
lang = 'β'
OS = platform.system().upper()
# print("OS->", OS)
if OS in ["MACOS", "DARWIN"]:
cmd = ['osascript', '-e', 'user locale of (get system info)']
result = subprocess.run(cmd, stdout=subprocess.PIPE)
lang = result.stdout.decode('utf-8')
return lang
def addMVC(id, name, countLines, countInternet, countIA):
file = name.replace(" ", "_")
fileName = f"ICM/{id}_{file}.txt"
# print(fileName)
with open(fileName, "a") as myfile:
# currentDate = date.today()
ts = time.time()
cT = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
line = f"{cT},{countLines},{countInternet},{countIA}\n"
# print("LINE->", line)
myfile.write(line)
@app.route('/')
def index():
server_ip = get_active_ipv4()
# print(f"Server IP: {server_ip}")
OS = getOSM()
LANG = getOSL()
osEmoji = get_os_emoji(OS)
return render_template('index.html', server_ip=server_ip, osEmoji=osEmoji,
MY_VERSION=MY_VERSION, ICM_VERSION=ICM_VERSION,
osLang=LANG)
@app.route('/update', methods=['POST'])
def update():
timestamp = time.time()
data = request.json
# print('data->', data)
id = data.get("id", "")
if id and id in clients_status:
row = clients_status[id]["row"]
name = clients_status[id]["name"]
ignored = clients_status[id]["ignored"]
OS = data.get("OS", "N/A")
OS = get_os_emoji(OS)
icmVersion = data.get("icmVersion", "N/A")
icmTGZ = update_upload(id, name)
# print('icmTGZ ->', icmTGZ)
status = data.get("status", "N/A")
# print(id, status, flush=True)
status = get_status_emoji(status)
countLines = data.get("countLines", "0")
# countTimeout = data.get("countTimeout", 0)
countInternet = data.get("countInternet", 0)
countIA = data.get("countIA", 0)
mvc = data.get("MVC", 0)
if mvc == "":
mvc = 1
# print("MVC->", mvc)
if mvc == 1:
addMVC(id, name, countLines, countInternet, countIA)
# if status == 'π€':
# countIA += 1
# print(id, status, flush=True)
# print(data, flush=True)
ip = request.remote_addr
elapsed = time.time() - timestamp
color, status = get_status_row_color(
id, row, time.time(), status, ignored)
client_status = {
"row": row,
"name": name,
"last_update": time.time(),
"icmVersion": icmVersion,
"icmTGZ": icmTGZ,
"OS": OS,
"status": status,
"ip": ip,
"color": color,
# "ignored": False
"ignored": ignored,
"countLines": countLines,
# "countTimeout": countTimeout,
"countInternet": countInternet,
"countIA": countIA
}
ip_server = "127.0.0.1"
if DEBUG:
print(f"πβπ»{ip}π{id}βπ{ip_server}")
# print("client_status ->", client_status)
clients_status[id] = client_status
# countTimeout = clients_status[id]["countTimeout"]
# countInternet = clients_status[id]["countInternet"]
# countIA = clients_status[id]["countIA"]
data = {
"row": row,
"id": id,
"name": name,
"timestamp": timestamp,
"elapsed": elapsed,
"color": color,
"status": status,
"ip": ip,
"icmVersion": icmVersion,
"icmTGZ": icmTGZ,
"OS": OS,
"countLines": countLines,
# "countTimeout": countTimeout,
"countInternet": countInternet,
"countIA": countIA
}
# print(f"{id} -> {data}", flush=True)
# print('update->', data)
socketio.emit('update_status', data)
return jsonify({"message": "Updated successfully"}), 200
else:
print(f"βπ{id}βUNKNOWN")
return jsonify({"error": "Invalid data"}), 400
def get_details(uploadDst):
stat = os.stat(uploadDst)
f1 = time.ctime(stat.st_mtime)
f2 = datetime.strptime(f1, "%a %b %d %H:%M:%S %Y") \
.strftime("%Y-%m-%d %H:%M:%S")
sizeStr = sizeof_fmt(stat.st_size)
return f2, sizeStr
def update_upload(id, name):
currentDate = date.today()
uploadDir = f'ICM/{currentDate}'
name = name.replace(' ', '_')
filename = f'{id}_{name}_ICM.tgz'
uploadDst = f'{uploadDir}/{filename}'
if os.path.exists(uploadDst):
f2, sizeStr = get_details(uploadDst)
# print('π', id, 'ποΈ', sizeStr)
return f'{sizeStr}π¦'
return "N/A"
def update_uploads():
currentDate = date.today()
uploadDir = f'ICM/{currentDate}'
if os.path.exists(uploadDir):
print('π¦ Uploads:')
for filename in os.listdir(uploadDir):
id = filename.split('_')[0]
uploadDst = f'{uploadDir}/{filename}'
f2, sizeStr = get_details(uploadDst)
client_status = clients_status[id]
client_status['icmTGZ'] = f'{sizeStr}π¦'
clients_status[id] = client_status
print('π', id, 'ποΈ', client_status['icmTGZ'])
print()
def playSound(phrase):
global lastAlarm
nowAlarm = time.time()
secsAlarm = nowAlarm - lastAlarm
if secsAlarm <= secsAlarmMax:
if DEBUG:
print('Ignorar alarma! ', secsAlarm, '<=', secsAlarmMax)
return
lastAlarm = nowAlarm
if OS == "WINDOWS":
cmd = r'..\ICM\.bin\nircmdc.exe'
os.system(cmd + f' speak text "{phrase}"')
else:
listCmd = ['say', f'{phrase}']
subprocess.run(listCmd)
def playSoundAtEnd(number):
global lastAlarm
lastAlarm = 0
if OS == "WINDOWS":
phrase = 'Great. I have some good news. '
phrase += f'The good news is that player number {number} has finished.'
else:
phrase = 'Fenomenal. Tengo una noticia buena. '
phrase += f'La buena es que el jugador numero {number} ha finalizado. '
playSound(phrase)
def playSoundWithInternet(number):
if OS == "WINDOWS":
phrase = 'Terrible. I have bad news and good news. '
phrase += "The good news is that I've identified "
phrase += f'player number {number}.'
phrase += 'The bad news is that he has an internet connection.'
else:
phrase = 'Terrible. Tengo una noticia mala y una buena. '
phrase += 'La buena es que he identificado'
phrase += f'al jugador numero {number}. '
phrase += 'La mala es que cuenta con una conexiΓ³n a internet.'
playSound(phrase)
def playSoundWithIA(number):
if OS == "WINDOWS":
phrase = 'Terrible. I have bad news and good news. '
phrase += "The good news is that I've identified "
phrase += f'player number {number}.'
phrase += 'The bad news is that he has an local AI.'
else:
phrase = 'Terrible. Tengo una noticia mala y una buena. '
phrase += 'La buena es que he identificado'
phrase += f'al jugador numero {number}. '
phrase += 'La mala es que cuenta con una IA local.'
playSound(phrase)
@app.route('/upload/<id>', methods=['GET', 'POST'])
def upload(id):
if request.method == 'POST':
if id in clients_status:
currentDate = date.today()
name = clients_status[id]["name"]
name = name.replace(' ', '_')
uploadDir = f'ICM/{currentDate}'
if not os.path.exists(uploadDir):
os.makedirs(uploadDir)
uploadName = f'{id}_{name}_ICM.tgz'
uploadDst = f'{uploadDir}/{uploadName}'
file = request.files['filedata']
# print(timestamp, file)
file.save(uploadDst)
f2, sizeStr = get_details(uploadDst)
detail = f2 + ' | ' + sizeStr
client_status = clients_status[id]
client_status['icmTGZ'] = f'{sizeStr}π¦'
client_status['id'] = id
client_status['ignored'] = True
clients_status[id] = client_status
print('upload->', client_status)
socketio.emit('update_status', client_status)
number = client_status['row']
playSoundAtEnd(number)
return f'Β‘π¦ {uploadName} ({detail}) β
Upload successful π!'
else:
return f'π« Nice try {id} π!'
@socketio.on('request_status')
def send_status():
"""EnvΓa el estado actualizado de los clientes con un Γndice de fila."""
ok_count = 0
warning_count = 0
critical_count = 0
ignore_count = 0
active_count = 0
# print(clients_status)
for index, (id, info) in enumerate(clients_status.items(), start=1):
# print("send_status - info ->", id, info)
elapsed = time.time() - info["last_update"]
status = info.get("status", "N/A")
ignored = info.get("ignored", False)
color, status = get_status_row_color(
id, info['row'], info["last_update"], status, ignored)
ip = info.get("ip", "N/A")
OS = info.get("OS", "N/A")
icmVersion = info.get("icmVersion", "N/A")
icmTGZ = info.get("icmTGZ", "N/A")
if DEBUG:
print(f"πβπβπ»{ip}π{id}")
# print("request_status ->", ip)
# print(id, info)
if ignored:
ignore_count += 1
else:
# print(id, "COLOR ->", color)
active_count += 1
if color == "green":
ok_count += 1
elif color == "yellow":
warning_count += 1
elif color == "red":
critical_count += 1
countLines = info.get("countLines", "N/A")
countTimeout = info.get("countTimeout", 0)
countInternet = info.get("countInternet", "N/A")
# print('countInternet ->', countInternet)
countIA = info.get("countIA", "N/A")
data = {
"row": index,
"id": id,
"name": info["name"],
"timestamp": info["last_update"],
"elapsed": elapsed,
"color": color,
"status": status,
"ip": ip,
"icmVersion": icmVersion,
"icmTGZ": icmTGZ,
"OS": OS,
"countLines": countLines,
"countTimeout": countTimeout,
"countInternet": countInternet,
"countIA": countIA,
}
socketio.emit('update_status', data)
# Emitir los contadores al frontend
# print(ok_count, warning_count, critical_count)
socketio.emit('update_counters', {
"ok": ok_count,
"warning": warning_count,
"critical": critical_count,
"ignore": ignore_count,
"active": active_count
})
@socketio.on('update_ignore_status')
def update_ignore_status(data):
user_id = data.get("id")
ignored = data.get("ignored")
if user_id in clients_status:
clients_status[user_id]["ignored"] = ignored
# print('update_ignore_status', user_id, ignored)
def get_active_ipv4():
try:
# Crear un socket UDP y conectarse a un servidor pΓΊblico (Google DNS)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0] # Obtener la IP de la interfaz activa
except Exception as e:
print(f"Error obteniendo la IP: {e}")
return "127.0.0.1" # Retorno seguro en caso de fallo
@socketio.on('ping_server')
def handle_ping():
""" Responde a los pings del frontend """
socketio.emit('pong_client', {'timestamp': time.time()})
OS = getOSM()
checkICM()
checkUpdate()
osEmoji = get_os_emoji(OS)
currentDate = date.today()
clients_status = getStudents()
print(f'\nβ‘οΈ Energizado por π ICMd v{MY_VERSION}'
f' π ejecutandose en {osEmoji} el {currentDate}\n')
update_uploads()
if __name__ == '__main__':
socketio.run(app, debug=True)