-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlisten.py
More file actions
148 lines (121 loc) · 4.69 KB
/
listen.py
File metadata and controls
148 lines (121 loc) · 4.69 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
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import base64
import hashlib
from datetime import datetime
from datetime import time
import socket
import threading
import tkinter as tk
import requests
# Encryption key
frase = "(Password for encryption same as in the Android app)" # Change this to your desired password
clave = hashlib.sha256(frase.encode()).digest() # 32 bytes for AES-256
# Create root window hidden for background operations
root = tk.Tk()
root.withdraw() # Hide the main window
# Configuration of Gist
GIST_ID = "(Your Gist ID)" # Gist ID
FILENAME = "(Your Gist file name with extension (Like, .txt))" # name of the file in the gist
TOKEN = "(Your Gist Token)" # Your GitHub token with Gist permissions
# Get local IP address with retry mechanism
def get_ip():
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
if ip: # if an IP is obtained, return it
return ip
except:
pass
finally:
s.close()
print("❌ No se pudo obtener la IP. Reintentando en 1 minuto...")
time.sleep(60) # wait 1 minute before retrying
pc_ip = get_ip()
print("IP de la PC:", pc_ip)
# Refresh Gist with current IP
url = f"https://api.github.com/gists/{GIST_ID}"
headers = {"Authorization": f"token {TOKEN}"}
data = {
"files": {
FILENAME: {
"content": pc_ip
}
}
}
response = requests.patch(url, json=data, headers=headers)
if response.status_code == 200:
print("Gist actualizado correctamente.")
print("URL raw para Android:")
print(f"https://gist.githubusercontent.com/raw/{GIST_ID}/{FILENAME}")
else:
print("Error al actualizar gist:", response.status_code, response.text)
# Show notification window
def mostrar_notificacion(texto):
def cerrar():
ventana.destroy()
ventana = tk.Toplevel(root)
ventana.overrideredirect(True)
ventana.attributes("-topmost", True)
ventana.configure(bg="black")
frame = tk.Frame(ventana, bg="black", bd=0)
frame.pack(expand=True, fill="both", padx=8, pady=8)
label = tk.Label(frame, text=texto, bg="black", fg="white", font=("Segoe UI", 10), justify="left", wraplength=280)
label.pack(padx=10, pady=10, side="left")
btn_cerrar = tk.Button(frame, text="✘", command=cerrar, font=("Segoe UI", 18), bg="black", fg="white", borderwidth=0, relief="flat", cursor="hand2")
btn_cerrar.pack(padx=10, pady=0, side="right")
# Put the window at the bottom left of the screen
ventana.geometry(f"370x100+10+-100")
def animar():
for y in range(-100, 20, 5):
ventana.geometry(f"370x120+10+{y}")
ventana.update()
ventana.after(10)
threading.Thread(target=animar, daemon=True).start()
# Server to listen for incoming messages
def escuchar():
servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
servidor.bind(("0.0.0.0", 5000))
servidor.listen(5)
print("OK")
threading.Thread(target=mostrar_notificacion, args=("OK",), daemon=True).start()
while True:
cliente, direccion = servidor.accept()
datos = cliente.recv(1024)
try:
datos = base64.b64decode(datos)
iv = datos[:16]
cifrado = datos[16:]
cipher = AES.new(clave, AES.MODE_CBC, iv)
mensaje_descifrado = unpad(cipher.decrypt(cifrado), AES.block_size).decode()
except Exception as e:
error = f"❌ Mensaje inválido de {direccion[0]}: {e}"
print(error)
threading.Thread(target=mostrar_notificacion, args=(error,), daemon=True).start()
cliente.close()
continue
fecha_hora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
mensaje = f"{mensaje_descifrado}\n[{fecha_hora}] => {direccion}"
print(mensaje)
threading.Thread(target=mostrar_notificacion, args=(mensaje,), daemon=True).start()
cliente.close()
# Thread to close the program at 10:00 p.m.
def cerrar_programa():
while True:
threading.Event().wait(1)
# Check hour every minute
hora_actual = datetime.now().time()
print("⏰ Hora actual:", hora_actual)
if hora_actual >= time(22, 0): # 22:00 equivale a 10:00 p.m.
print(f"⏰ Son las {hora_actual.strftime('%H:%M')}, cerrando el programa.")
root.quit()
root.destroy()
# Start listening thread
threading.Thread(target=escuchar, daemon=True).start()
# Start program closing thread
threading.Thread(target=cerrar_programa, daemon=True).start()
# Main loop of the hidden root window
root.mainloop()