6 Commits

Author SHA1 Message Date
Flowseal
8bcbcd2787 media dc fix on mobiles 2026-03-13 13:34:22 +03:00
Flowseal
f744e93de6 Mobiles media fix, optimizations 2026-03-12 19:36:02 +03:00
Flowseal
6147cda356 unknown behavior on mobiles with media dcs 2026-03-10 14:21:31 +03:00
Flowseal
3cf12467a7 Host configuration 2026-03-07 21:52:59 +03:00
Flowseal
48282a63d4 code cleaning 2026-03-07 21:14:17 +03:00
Flowseal
39dd71be14 Lock recode, bind error notify, clipboard cross-platform 2026-03-07 21:10:35 +03:00
4 changed files with 221 additions and 82 deletions

View File

@@ -32,24 +32,34 @@ _TG_RANGES = [
struct.unpack('!I', _socket.inet_aton('91.108.255.255'))[0]), struct.unpack('!I', _socket.inet_aton('91.108.255.255'))[0]),
] ]
_IP_TO_DC: Dict[str, int] = { # IP -> (dc_id, is_media)
_IP_TO_DC: Dict[str, Tuple[int, bool]] = {
# DC1 # DC1
'149.154.175.50': 1, '149.154.175.51': 1, '149.154.175.54': 1, '149.154.175.50': (1, False), '149.154.175.51': (1, False),
'149.154.175.53': (1, False), '149.154.175.54': (1, False),
'149.154.175.52': (1, True),
# DC2 # DC2
'149.154.167.41': 2, '149.154.167.41': (2, False), '149.154.167.50': (2, False),
'149.154.167.50': 2, '149.154.167.51': 2, '149.154.167.220': 2, '149.154.167.51': (2, False), '149.154.167.220': (2, False),
'95.161.76.100': (2, False),
'149.154.167.151': (2, True), '149.154.167.222': (2, True),
'149.154.167.223': (2, True),
# DC3 # DC3
'149.154.175.100': 3, '149.154.175.101': 3, '149.154.175.100': (3, False), '149.154.175.101': (3, False),
'149.154.175.102': (3, True),
# DC4 # DC4
'149.154.167.91': 4, '149.154.167.92': 4, '149.154.167.91': (4, False), '149.154.167.92': (4, False),
'149.154.164.250': (4, True), '149.154.166.120': (4, True),
'149.154.166.121': (4, True), '149.154.167.118': (4, True),
'149.154.165.111': (4, True),
# DC5 # DC5
'91.108.56.100': 5, '91.108.56.100': (5, False), '91.108.56.101': (5, False),
'91.108.56.126': 5, '91.108.56.101': 5, '91.108.56.116': 5, '91.108.56.116': (5, False), '91.108.56.126': (5, False),
'149.154.171.5': (5, False),
'91.108.56.102': (5, True), '91.108.56.128': (5, True),
'91.108.56.151': (5, True),
# DC203 # DC203
'91.105.192.100': 203, '91.105.192.100': (203, False),
# Media DCs
'149.154.167.151': 2, '149.154.167.223': 2,
'149.154.166.120': 4, '149.154.166.121': 4,
} }
_dc_opt: Dict[int, Optional[str]] = {} _dc_opt: Dict[int, Optional[str]] = {}
@@ -86,10 +96,9 @@ class WsHandshakeError(Exception):
def _xor_mask(data: bytes, mask: bytes) -> bytes: def _xor_mask(data: bytes, mask: bytes) -> bytes:
if not data: if not data:
return data return data
a = bytearray(data) n = len(data)
for i in range(len(a)): mask_rep = (mask * (n // 4 + 1))[:n]
a[i] ^= mask[i & 3] return (int.from_bytes(data, 'big') ^ int.from_bytes(mask_rep, 'big')).to_bytes(n, 'big')
return bytes(a)
class RawWebSocket: class RawWebSocket:
@@ -193,6 +202,15 @@ class RawWebSocket:
self.writer.write(frame) self.writer.write(frame)
await self.writer.drain() await self.writer.drain()
async def send_batch(self, parts: List[bytes]):
"""Send multiple binary frames with a single drain (less overhead)."""
if self._closed:
raise ConnectionError("WebSocket closed")
for part in parts:
frame = self._build_frame(self.OP_BINARY, part, mask=True)
self.writer.write(frame)
await self.writer.drain()
async def recv(self) -> Optional[bytes]: async def recv(self) -> Optional[bytes]:
""" """
Receive the next data frame. Handles ping/pong/close Receive the next data frame. Handles ping/pong/close
@@ -343,6 +361,85 @@ def _dc_from_init(data: bytes) -> Tuple[Optional[int], bool]:
return None, False return None, False
def _patch_init_dc(data: bytes, dc: int) -> bytes:
"""
Patch dc_id in the 64-byte MTProto init packet.
Mobile clients with useSecret=0 leave bytes 60-61 as random.
The WS relay needs a valid dc_id to route correctly.
"""
if len(data) < 64:
return data
new_dc = struct.pack('<h', dc)
try:
key_raw = bytes(data[8:40])
iv = bytes(data[40:56])
cipher = Cipher(algorithms.AES(key_raw), modes.CTR(iv))
enc = cipher.encryptor()
ks = enc.update(b'\x00' * 64) + enc.finalize()
patched = bytearray(data[:64])
patched[60] = ks[60] ^ new_dc[0]
patched[61] = ks[61] ^ new_dc[1]
log.debug("init patched: dc_id -> %d", dc)
if len(data) > 64:
return bytes(patched) + data[64:]
return bytes(patched)
except Exception:
return data
class _MsgSplitter:
"""
Splits client TCP data into individual MTProto abridged-protocol
messages so each can be sent as a separate WebSocket frame.
The Telegram WS relay processes one MTProto message per WS frame.
Mobile clients batches multiple messages in a single TCP write (e.g.
msgs_ack + req_DH_params). If sent as one WS frame, the relay
only processes the first message — DH handshake never completes.
"""
def __init__(self, init_data: bytes):
key_raw = bytes(init_data[8:40])
iv = bytes(init_data[40:56])
cipher = Cipher(algorithms.AES(key_raw), modes.CTR(iv))
self._dec = cipher.encryptor()
self._dec.update(b'\x00' * 64) # skip init packet
def split(self, chunk: bytes) -> List[bytes]:
"""Decrypt to find message boundaries, return split ciphertext."""
plain = self._dec.update(chunk)
boundaries = []
pos = 0
while pos < len(plain):
first = plain[pos]
if first == 0x7f:
if pos + 4 > len(plain):
break
msg_len = (
struct.unpack_from('<I', plain, pos + 1)[0] & 0xFFFFFF
) * 4
pos += 4
else:
msg_len = first * 4
pos += 1
if msg_len == 0 or pos + msg_len > len(plain):
break
pos += msg_len
boundaries.append(pos)
if len(boundaries) <= 1:
return [chunk]
parts = []
prev = 0
for b in boundaries:
parts.append(chunk[prev:b])
prev = b
if prev < len(chunk):
parts.append(chunk[prev:])
return parts
def _ws_domains(dc: int, is_media) -> List[str]: def _ws_domains(dc: int, is_media) -> List[str]:
""" """
Return domain names to try for WebSocket connection to a DC. Return domain names to try for WebSocket connection to a DC.
@@ -381,7 +478,8 @@ _stats = Stats()
async def _bridge_ws(reader, writer, ws: RawWebSocket, label, async def _bridge_ws(reader, writer, ws: RawWebSocket, label,
dc=None, dst=None, port=None, is_media=False): dc=None, dst=None, port=None, is_media=False,
splitter: _MsgSplitter = None):
"""Bidirectional TCP <-> WebSocket forwarding.""" """Bidirectional TCP <-> WebSocket forwarding."""
dc_tag = f"DC{dc}{'m' if is_media else ''}" if dc else "DC?" dc_tag = f"DC{dc}{'m' if is_media else ''}" if dc else "DC?"
dst_tag = f"{dst}:{port}" if dst else "?" dst_tag = f"{dst}:{port}" if dst else "?"
@@ -396,13 +494,20 @@ async def _bridge_ws(reader, writer, ws: RawWebSocket, label,
nonlocal up_bytes, up_packets nonlocal up_bytes, up_packets
try: try:
while True: while True:
chunk = await reader.read(65536) chunk = await reader.read(131072)
if not chunk: if not chunk:
break break
_stats.bytes_up += len(chunk) _stats.bytes_up += len(chunk)
up_bytes += len(chunk) up_bytes += len(chunk)
up_packets += 1 up_packets += 1
await ws.send(chunk) if splitter:
parts = splitter.split(chunk)
if len(parts) > 1:
await ws.send_batch(parts)
else:
await ws.send(parts[0])
else:
await ws.send(chunk)
except (asyncio.CancelledError, ConnectionError, OSError): except (asyncio.CancelledError, ConnectionError, OSError):
return return
except Exception as e: except Exception as e:
@@ -419,7 +524,10 @@ async def _bridge_ws(reader, writer, ws: RawWebSocket, label,
down_bytes += len(data) down_bytes += len(data)
down_packets += 1 down_packets += 1
writer.write(data) writer.write(data)
await writer.drain() # drain only when kernel buffer is filling up
buf = writer.transport.get_write_buffer_size()
if buf > 262144:
await writer.drain()
except (asyncio.CancelledError, ConnectionError, OSError): except (asyncio.CancelledError, ConnectionError, OSError):
return return
except Exception as e: except Exception as e:
@@ -596,7 +704,7 @@ async def _handle_client(reader, writer):
rr, rw = await asyncio.wait_for( rr, rw = await asyncio.wait_for(
asyncio.open_connection(dst, port), timeout=10) asyncio.open_connection(dst, port), timeout=10)
except Exception as exc: except Exception as exc:
log.warning("[%s] passthrough failed to %s: %s", label, dst, exc) log.warning("[%s] passthrough failed to %s: %s: %s", label, dst, type(exc).__name__, str(exc) or "(no message)")
writer.write(_socks5_reply(0x05)) writer.write(_socks5_reply(0x05))
await writer.drain() await writer.drain()
writer.close() writer.close()
@@ -639,8 +747,14 @@ async def _handle_client(reader, writer):
# -- Extract DC ID -- # -- Extract DC ID --
dc, is_media = _dc_from_init(init) dc, is_media = _dc_from_init(init)
init_patched = False
# Android (may be ios too) with useSecret=0 has random dc_id bytes — patch it
if dc is None and dst in _IP_TO_DC: if dc is None and dst in _IP_TO_DC:
dc = _IP_TO_DC.get(dst) dc, is_media = _IP_TO_DC.get(dst)
if dc in _dc_opt:
init = _patch_init_dc(init, dc if is_media else -dc)
init_patched = True
if dc is None or dc not in _dc_opt: if dc is None or dc not in _dc_opt:
log.warning("[%s] unknown DC%s for %s:%d -> TCP passthrough", log.warning("[%s] unknown DC%s for %s:%d -> TCP passthrough",
@@ -745,12 +859,20 @@ async def _handle_client(reader, writer):
_dc_fail_until.pop(dc_key, None) _dc_fail_until.pop(dc_key, None)
_stats.connections_ws += 1 _stats.connections_ws += 1
splitter = None
if init_patched:
try:
splitter = _MsgSplitter(init)
except Exception:
pass
# Send the buffered init packet # Send the buffered init packet
await ws.send(init) await ws.send(init)
# Bidirectional bridge # Bidirectional bridge
await _bridge_ws(reader, writer, ws, label, await _bridge_ws(reader, writer, ws, label,
dc=dc, dst=dst, port=port, is_media=is_media) dc=dc, dst=dst, port=port, is_media=is_media,
splitter=splitter)
except asyncio.TimeoutError: except asyncio.TimeoutError:
log.warning("[%s] timeout during SOCKS5 handshake", label) log.warning("[%s] timeout during SOCKS5 handshake", label)
@@ -774,25 +896,26 @@ _server_stop_event = None
async def _run(port: int, dc_opt: Dict[int, Optional[str]], async def _run(port: int, dc_opt: Dict[int, Optional[str]],
stop_event: Optional[asyncio.Event] = None): stop_event: Optional[asyncio.Event] = None,
host: str = '127.0.0.1'):
global _dc_opt, _server_instance, _server_stop_event global _dc_opt, _server_instance, _server_stop_event
_dc_opt = dc_opt _dc_opt = dc_opt
_server_stop_event = stop_event _server_stop_event = stop_event
server = await asyncio.start_server( server = await asyncio.start_server(
_handle_client, '127.0.0.1', port) _handle_client, host, port)
_server_instance = server _server_instance = server
log.info("=" * 60) log.info("=" * 60)
log.info(" Telegram WS Bridge Proxy") log.info(" Telegram WS Bridge Proxy")
log.info(" Listening on 127.0.0.1:%d", port) log.info(" Listening on %s:%d", host, port)
log.info(" Target DC IPs:") log.info(" Target DC IPs:")
for dc in dc_opt.keys(): for dc in dc_opt.keys():
ip = dc_opt.get(dc) ip = dc_opt.get(dc)
log.info(" DC%d: %s", dc, ip) log.info(" DC%d: %s", dc, ip)
log.info("=" * 60) log.info("=" * 60)
log.info(" Configure Telegram Desktop:") log.info(" Configure Telegram Desktop:")
log.info(" SOCKS5 proxy -> 127.0.0.1:%d (no user/pass)", port) log.info(" SOCKS5 proxy -> %s:%d (no user/pass)", host, port)
log.info("=" * 60) log.info("=" * 60)
async def log_stats(): async def log_stats():
@@ -844,9 +967,10 @@ def parse_dc_ip_list(dc_ip_list: List[str]) -> Dict[int, str]:
def run_proxy(port: int, dc_opt: Dict[int, str], def run_proxy(port: int, dc_opt: Dict[int, str],
stop_event: Optional[asyncio.Event] = None): stop_event: Optional[asyncio.Event] = None,
host: str = '127.0.0.1'):
"""Run the proxy (blocking). Can be called from threads.""" """Run the proxy (blocking). Can be called from threads."""
asyncio.run(_run(port, dc_opt, stop_event)) asyncio.run(_run(port, dc_opt, stop_event, host))
def main(): def main():
@@ -854,6 +978,8 @@ def main():
description='Telegram Desktop WebSocket Bridge Proxy') description='Telegram Desktop WebSocket Bridge Proxy')
ap.add_argument('--port', type=int, default=DEFAULT_PORT, ap.add_argument('--port', type=int, default=DEFAULT_PORT,
help=f'Listen port (default {DEFAULT_PORT})') help=f'Listen port (default {DEFAULT_PORT})')
ap.add_argument('--host', type=str, default='127.0.0.1',
help='Listen host (default 127.0.0.1)')
ap.add_argument('--dc-ip', metavar='DC:IP', action='append', ap.add_argument('--dc-ip', metavar='DC:IP', action='append',
default=['2:149.154.167.220', '4:149.154.167.220'], default=['2:149.154.167.220', '4:149.154.167.220'],
help='Target IP for a DC, e.g. --dc-ip 1:149.154.175.205' help='Target IP for a DC, e.g. --dc-ip 1:149.154.175.205'
@@ -875,7 +1001,7 @@ def main():
) )
try: try:
asyncio.run(_run(args.port, dc_opt)) asyncio.run(_run(args.port, dc_opt, host=args.host))
except KeyboardInterrupt: except KeyboardInterrupt:
log.info("Shutting down. Final stats: %s", _stats.summary()) log.info("Shutting down. Final stats: %s", _stats.summary())

View File

@@ -3,3 +3,4 @@ customtkinter==5.2.2
Pillow==10.4.0 Pillow==10.4.0
psutil==5.9.8 psutil==5.9.8
pystray==0.19.5 pystray==0.19.5
pyperclip==1.9.0

View File

@@ -3,3 +3,4 @@ customtkinter==5.2.2
Pillow==12.1.1 Pillow==12.1.1
psutil==7.0.0 psutil==7.0.0
pystray==0.19.5 pystray==0.19.5
pyperclip==1.9.0

View File

@@ -10,6 +10,7 @@ import threading
import time import time
import webbrowser import webbrowser
import pystray import pystray
import pyperclip
import asyncio as _asyncio import asyncio as _asyncio
import customtkinter as ctk import customtkinter as ctk
from pathlib import Path from pathlib import Path
@@ -28,6 +29,7 @@ FIRST_RUN_MARKER = APP_DIR / ".first_run_done"
DEFAULT_CONFIG = { DEFAULT_CONFIG = {
"port": 1080, "port": 1080,
"host": "127.0.0.1",
"dc_ip": ["2:149.154.167.220", "4:149.154.167.220"], "dc_ip": ["2:149.154.167.220", "4:149.154.167.220"],
"verbose": False, "verbose": False,
} }
@@ -42,13 +44,27 @@ _exiting: bool = False
log = logging.getLogger("tg-ws-tray") log = logging.getLogger("tg-ws-tray")
def is_already_running(): def _acquire_lock() -> bool:
current_proc = os.path.basename(sys.argv[0]) _ensure_dirs()
count = 0 lock_files = list(APP_DIR.glob("*.lock"))
for process in psutil.process_iter(['name']):
if process.info['name'] == current_proc: for f in lock_files:
count += 1 try:
return count > 2 pid = int(f.stem)
if psutil.pid_exists(pid):
try:
psutil.Process(pid).status()
return False
except (psutil.NoSuchProcess, psutil.ZombieProcess):
pass
except Exception:
pass
f.unlink(missing_ok=True)
lock_file = APP_DIR / f"{os.getpid()}.lock"
lock_file.touch()
return True
def _ensure_dirs(): def _ensure_dirs():
@@ -61,7 +77,6 @@ def load_config() -> dict:
try: try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f: with open(CONFIG_FILE, "r", encoding="utf-8") as f:
data = json.load(f) data = json.load(f)
# Merge with defaults for missing keys
for k, v in DEFAULT_CONFIG.items(): for k, v in DEFAULT_CONFIG.items():
data.setdefault(k, v) data.setdefault(k, v)
return data return data
@@ -98,18 +113,15 @@ def setup_logging(verbose: bool = False):
def _make_icon_image(size: int = 64): def _make_icon_image(size: int = 64):
"""Create a simple tray icon: blue circle with a white 'T' letter."""
if Image is None: if Image is None:
raise RuntimeError("Pillow is required for tray icon") raise RuntimeError("Pillow is required for tray icon")
img = Image.new("RGBA", (size, size), (0, 0, 0, 0)) img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img) draw = ImageDraw.Draw(img)
# Blue circle
margin = 2 margin = 2
draw.ellipse([margin, margin, size - margin, size - margin], draw.ellipse([margin, margin, size - margin, size - margin],
fill=(0, 136, 204, 255)) fill=(0, 136, 204, 255))
# White "T"
try: try:
font = ImageFont.truetype("arial.ttf", size=int(size * 0.55)) font = ImageFont.truetype("arial.ttf", size=int(size * 0.55))
except Exception: except Exception:
@@ -124,7 +136,6 @@ def _make_icon_image(size: int = 64):
def _load_icon(): def _load_icon():
"""Load icon from file or generate one."""
icon_path = Path(__file__).parent / "icon.ico" icon_path = Path(__file__).parent / "icon.ico"
if icon_path.exists() and Image: if icon_path.exists() and Image:
try: try:
@@ -135,8 +146,8 @@ def _load_icon():
def _run_proxy_thread(port: int, dc_opt: Dict[int, str], verbose: bool): def _run_proxy_thread(port: int, dc_opt: Dict[int, str], verbose: bool,
"""Target for the proxy thread — runs asyncio event loop.""" host: str = '127.0.0.1'):
global _async_stop global _async_stop
loop = _asyncio.new_event_loop() loop = _asyncio.new_event_loop()
_asyncio.set_event_loop(loop) _asyncio.set_event_loop(loop)
@@ -145,9 +156,11 @@ def _run_proxy_thread(port: int, dc_opt: Dict[int, str], verbose: bool):
try: try:
loop.run_until_complete( loop.run_until_complete(
tg_ws_proxy._run(port, dc_opt, stop_event=stop_ev)) tg_ws_proxy._run(port, dc_opt, stop_event=stop_ev, host=host))
except Exception as exc: except Exception as exc:
log.error("Proxy thread crashed: %s", exc) log.error("Proxy thread crashed: %s", exc)
if "10048" in str(exc) or "Address already in use" in str(exc):
_show_error("Не удалось запустить прокси:\nПорт уже используется другим приложением.\n\nЗакройте приложение, использующее этот порт, или измените порт в настройках прокси и перезапустите.")
finally: finally:
loop.close() loop.close()
_async_stop = None _async_stop = None
@@ -161,6 +174,7 @@ def start_proxy():
cfg = _config cfg = _config
port = cfg.get("port", DEFAULT_CONFIG["port"]) port = cfg.get("port", DEFAULT_CONFIG["port"])
host = cfg.get("host", DEFAULT_CONFIG["host"])
dc_ip_list = cfg.get("dc_ip", DEFAULT_CONFIG["dc_ip"]) dc_ip_list = cfg.get("dc_ip", DEFAULT_CONFIG["dc_ip"])
verbose = cfg.get("verbose", False) verbose = cfg.get("verbose", False)
@@ -171,10 +185,10 @@ def start_proxy():
_show_error(f"Ошибка конфигурации:\n{e}") _show_error(f"Ошибка конфигурации:\n{e}")
return return
log.info("Starting proxy on port %d ...", port) log.info("Starting proxy on %s:%d ...", host, port)
_proxy_thread = threading.Thread( _proxy_thread = threading.Thread(
target=_run_proxy_thread, target=_run_proxy_thread,
args=(port, dc_opt, verbose), args=(port, dc_opt, verbose, host),
daemon=True, name="proxy") daemon=True, name="proxy")
_proxy_thread.start() _proxy_thread.start()
@@ -206,8 +220,9 @@ def _show_info(text: str, title: str = "TG WS Proxy"):
def _on_open_in_telegram(icon=None, item=None): def _on_open_in_telegram(icon=None, item=None):
host = _config.get("host", DEFAULT_CONFIG["host"])
port = _config.get("port", DEFAULT_CONFIG["port"]) port = _config.get("port", DEFAULT_CONFIG["port"])
url = f"tg://socks?server=127.0.0.1&port={port}" url = f"tg://socks?server={host}&port={port}"
log.info("Opening %s", url) log.info("Opening %s", url)
try: try:
result = webbrowser.open(url) result = webbrowser.open(url)
@@ -216,7 +231,7 @@ def _on_open_in_telegram(icon=None, item=None):
except Exception: except Exception:
log.info("Browser open failed, copying to clipboard") log.info("Browser open failed, copying to clipboard")
try: try:
_copy_to_clipboard(url) pyperclip.copy(url)
_show_info( _show_info(
f"Не удалось открыть Telegram автоматически.\n\n" f"Не удалось открыть Telegram автоматически.\n\n"
f"Ссылка скопирована в буфер обмена, отправьте её в телеграмм и нажмите по ней ЛКМ:\n{url}", f"Ссылка скопирована в буфер обмена, отправьте её в телеграмм и нажмите по ней ЛКМ:\n{url}",
@@ -226,31 +241,11 @@ def _on_open_in_telegram(icon=None, item=None):
_show_error(f"Не удалось скопировать ссылку:\n{exc}") _show_error(f"Не удалось скопировать ссылку:\n{exc}")
def _copy_to_clipboard(text: str):
"""Copy text to Windows clipboard using ctypes."""
import ctypes.wintypes
CF_UNICODETEXT = 13
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32
user32.OpenClipboard(0)
user32.EmptyClipboard()
encoded = text.encode("utf-16-le") + b"\x00\x00"
h = kernel32.GlobalAlloc(0x0042, len(encoded)) # GMEM_MOVEABLE | GMEM_ZEROINIT
p = kernel32.GlobalLock(h)
ctypes.memmove(p, encoded, len(encoded))
kernel32.GlobalUnlock(h)
user32.SetClipboardData(CF_UNICODETEXT, h)
user32.CloseClipboard()
def _on_restart(icon=None, item=None): def _on_restart(icon=None, item=None):
threading.Thread(target=restart_proxy, daemon=True).start() threading.Thread(target=restart_proxy, daemon=True).start()
def _on_edit_config(icon=None, item=None): def _on_edit_config(icon=None, item=None):
"""Open a simple dialog to edit config."""
threading.Thread(target=_edit_config_dialog, daemon=True).start() threading.Thread(target=_edit_config_dialog, daemon=True).start()
@@ -278,7 +273,7 @@ def _edit_config_dialog():
TEXT_SECONDARY = "#707579" TEXT_SECONDARY = "#707579"
FONT_FAMILY = "Segoe UI" FONT_FAMILY = "Segoe UI"
w, h = 420, 400 w, h = 420, 480
sw = root.winfo_screenwidth() sw = root.winfo_screenwidth()
sh = root.winfo_screenheight() sh = root.winfo_screenheight()
root.geometry(f"{w}x{h}+{(sw-w)//2}+{(sh-h)//2}") root.geometry(f"{w}x{h}+{(sw-w)//2}+{(sh-h)//2}")
@@ -287,6 +282,17 @@ def _edit_config_dialog():
frame = ctk.CTkFrame(root, fg_color=BG, corner_radius=0) frame = ctk.CTkFrame(root, fg_color=BG, corner_radius=0)
frame.pack(fill="both", expand=True, padx=24, pady=20) frame.pack(fill="both", expand=True, padx=24, pady=20)
# Host
ctk.CTkLabel(frame, text="IP-адрес прокси",
font=(FONT_FAMILY, 13), text_color=TEXT_PRIMARY,
anchor="w").pack(anchor="w", pady=(0, 4))
host_var = ctk.StringVar(value=cfg.get("host", "127.0.0.1"))
host_entry = ctk.CTkEntry(frame, textvariable=host_var, width=200, height=36,
font=(FONT_FAMILY, 13), corner_radius=10,
fg_color=FIELD_BG, border_color=FIELD_BORDER,
border_width=1, text_color=TEXT_PRIMARY)
host_entry.pack(anchor="w", pady=(0, 12))
# Port # Port
ctk.CTkLabel(frame, text="Порт прокси", ctk.CTkLabel(frame, text="Порт прокси",
font=(FONT_FAMILY, 13), text_color=TEXT_PRIMARY, font=(FONT_FAMILY, 13), text_color=TEXT_PRIMARY,
@@ -324,6 +330,14 @@ def _edit_config_dialog():
anchor="w").pack(anchor="w", pady=(0, 16)) anchor="w").pack(anchor="w", pady=(0, 16))
def on_save(): def on_save():
import socket as _sock
host_val = host_var.get().strip()
try:
_sock.inet_aton(host_val)
except OSError:
_show_error("Некорректный IP-адрес.")
return
try: try:
port_val = int(port_var.get().strip()) port_val = int(port_var.get().strip())
if not (1 <= port_val <= 65535): if not (1 <= port_val <= 65535):
@@ -341,6 +355,7 @@ def _edit_config_dialog():
return return
new_cfg = { new_cfg = {
"host": host_val,
"port": port_val, "port": port_val,
"dc_ip": lines, "dc_ip": lines,
"verbose": verbose_var.get(), "verbose": verbose_var.get(),
@@ -349,6 +364,8 @@ def _edit_config_dialog():
_config.update(new_cfg) _config.update(new_cfg)
log.info("Config saved: %s", new_cfg) log.info("Config saved: %s", new_cfg)
_tray_icon.menu = _build_menu()
from tkinter import messagebox from tkinter import messagebox
if messagebox.askyesno("Перезапустить?", if messagebox.askyesno("Перезапустить?",
"Настройки сохранены.\n\n" "Настройки сохранены.\n\n"
@@ -410,8 +427,9 @@ def _show_first_run():
if FIRST_RUN_MARKER.exists(): if FIRST_RUN_MARKER.exists():
return return
host = _config.get("host", DEFAULT_CONFIG["host"])
port = _config.get("port", DEFAULT_CONFIG["port"]) port = _config.get("port", DEFAULT_CONFIG["port"])
tg_url = f"tg://socks?server=127.0.0.1&port={port}" tg_url = f"tg://socks?server={host}&port={port}"
if ctk is None: if ctk is None:
FIRST_RUN_MARKER.touch() FIRST_RUN_MARKER.touch()
@@ -463,7 +481,7 @@ def _show_first_run():
(f" Или ссылка: {tg_url}", False), (f" Или ссылка: {tg_url}", False),
("\n Вручную:", True), ("\n Вручную:", True),
(" Настройки → Продвинутые → Тип подключения → Прокси", False), (" Настройки → Продвинутые → Тип подключения → Прокси", False),
(f" SOCKS5 → 127.0.0.1 : {port} (без логина/пароля)", False), (f" SOCKS5 → {host} : {port} (без логина/пароля)", False),
] ]
for text, bold in sections: for text, bold in sections:
@@ -509,10 +527,11 @@ def _show_first_run():
def _build_menu(): def _build_menu():
if pystray is None: if pystray is None:
return None return None
host = _config.get("host", DEFAULT_CONFIG["host"])
port = _config.get("port", DEFAULT_CONFIG["port"]) port = _config.get("port", DEFAULT_CONFIG["port"])
return pystray.Menu( return pystray.Menu(
pystray.MenuItem( pystray.MenuItem(
f"Открыть в Telegram (:{port})", f"Открыть в Telegram ({host}:{port})",
_on_open_in_telegram, _on_open_in_telegram,
default=True), default=True),
pystray.Menu.SEPARATOR, pystray.Menu.SEPARATOR,
@@ -571,18 +590,10 @@ def run_tray():
def main(): def main():
if is_already_running(): if not _acquire_lock():
_show_info("Приложение уже запущено.", os.path.basename(sys.argv[0])) _show_info("Приложение уже запущено.", os.path.basename(sys.argv[0]))
return return
# Hide console window if running as frozen exe
if getattr(sys, "frozen", False):
try:
ctypes.windll.user32.ShowWindow(
ctypes.windll.kernel32.GetConsoleWindow(), 0)
except Exception:
pass
run_tray() run_tray()