File size: 31,125 Bytes
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1079e50
 
3392270
 
 
 
 
 
 
1079e50
 
 
 
 
 
3392270
 
 
 
 
1079e50
 
 
 
3392270
 
 
 
 
1079e50
 
 
 
 
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1079e50
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eac790
 
 
3392270
2eac790
3392270
 
 
 
 
2eac790
 
 
 
 
 
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eac790
3392270
 
 
 
 
 
2eac790
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
2eac790
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854cebd
 
3392270
 
2eac790
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
2eac790
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854cebd
 
 
 
 
3392270
854cebd
3392270
854cebd
 
3392270
 
854cebd
 
3392270
 
854cebd
3392270
854cebd
 
 
 
3392270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Agapia ProxyTool — Tim + Kiem tra + Cham diem proxy (HTTP / SOCKS5 / SOCKS4).
GUI dark theme, stdlib thuan (khong can cai gi — tkinter co san trong Python Windows).

Chay:  python proxytool_gui.py
       (neu hien console den, doi duoi file thanh .pyw roi double-click)

Tinh nang:
  • 🔎 Tim proxy free tu nhieu nguon tren internet (1 nut).
  • ▶ Kiem tra + tu detect loai (HTTP/SOCKS5/SOCKS4) song song.
  • 🎯 Cham diem "dung duoc cho tool mail" (login Outlook qua proxy):
        ✅ Tot · ⚠️ Rui ro · ❌ Loai  — ghi ro ly do tung con.
  • 📋 Copy danh sach dung duoc · 💾 Luu ra file.
"""
import sys, re, time, json, socket, struct, base64, threading, queue
import urllib.request
from concurrent.futures import ThreadPoolExecutor

try:
    import tkinter as tk
    from tkinter import ttk, filedialog, messagebox
    HAVE_TK = True
except Exception:                       # cho phep test engine headless
    HAVE_TK = False

# ───────────────────────── CAU HINH ─────────────────────────
T_HOST, T_PORT = "ip-api.com", 80
T_PATH = "/json/?fields=status,query,country,countryCode,city,isp,org,proxy,hosting,mobile"
MS_HOST, MS_PORT = "login.live.com", 443      # host that tool mail phai vao (HTTPS)

SCHEME_MAP = {"http": "http", "https": "http", "socks5": "socks5", "socks5h": "socks5",
              "socks4": "socks4", "socks4a": "socks4", "socks": "socks5"}

# Nguon proxy free (txt, moi dong ip:port). Da verify song. Chi nguon protocol-specific
# (khong dung list mixed de detect khong sai loai). Bo cac nguon 404/502 va list 100k stale.
SOURCES = {
    "http": [
        "https://api.proxyscrape.com/v4/free-proxy-list/get?request=display_proxies&protocol=http&proxy_format=ipport&format=text",
        "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt",
        "https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt",
        "https://raw.githubusercontent.com/jetkai/proxy-list/main/online-proxies/txt/proxies-http.txt",
        "https://raw.githubusercontent.com/proxifly/free-proxy-list/main/proxies/protocols/http/data.txt",
        "https://raw.githubusercontent.com/mmpx12/proxy-list/master/http.txt",
        "https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt",
        "https://raw.githubusercontent.com/vakhov/fresh-proxy-list/master/http.txt",
        "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt",
        "https://raw.githubusercontent.com/roosterkid/openproxylist/main/HTTPS_RAW.txt",
        "https://proxyspace.pro/http.txt",
    ],
    "socks4": [
        "https://api.proxyscrape.com/v4/free-proxy-list/get?request=display_proxies&protocol=socks4&proxy_format=ipport&format=text",
        "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/socks4.txt",
        "https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/socks4.txt",
        "https://raw.githubusercontent.com/mmpx12/proxy-list/master/socks4.txt",
        "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/socks4.txt",
        "https://raw.githubusercontent.com/roosterkid/openproxylist/main/SOCKS4_RAW.txt",
        "https://proxyspace.pro/socks4.txt",
    ],
    "socks5": [
        "https://api.proxyscrape.com/v4/free-proxy-list/get?request=display_proxies&protocol=socks5&proxy_format=ipport&format=text",
        "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/socks5.txt",
        "https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/socks5.txt",
        "https://raw.githubusercontent.com/hookzof/socks5_list/master/proxy.txt",
        "https://raw.githubusercontent.com/mmpx12/proxy-list/master/socks5.txt",
        "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/socks5.txt",
        "https://raw.githubusercontent.com/roosterkid/openproxylist/main/SOCKS5_RAW.txt",
        "https://proxyspace.pro/socks5.txt",
    ],
}

# ───────────────────────── PARSE ─────────────────────────
def parse_line(line):
    """Tra (scheme_or_None, host, port:int, user, pwd) hoac None."""
    line = (line or "").strip()
    if not line or line.startswith("#"):
        return None
    scheme = None
    m = re.match(r"^(\w+)://(.*)$", line)
    if m:
        scheme = SCHEME_MAP.get(m.group(1).lower())
        line = m.group(2)
    tag = re.search(r"\(([^)]*)\)\s*$", line)
    if tag:
        scheme = scheme or SCHEME_MAP.get(re.sub(r"[^a-z0-9]", "", tag.group(1).lower()))
        line = line[:tag.start()].strip()
    line = line.split()[0] if " " in line else line
    if "@" in line:
        cred, hp = line.rsplit("@", 1)
        hpp = hp.split(":")
        if len(hpp) < 2:
            return None
        host, port = hpp[0], hpp[1]
        up = cred.split(":", 1)
        user, pwd = up[0], (up[1] if len(up) > 1 else "")
    else:
        parts = line.split(":")
        if len(parts) >= 4:
            host, port, user, pwd = parts[0], parts[1], parts[2], ":".join(parts[3:])
        elif len(parts) == 2:
            host, port, user, pwd = parts[0], parts[1], "", ""
        else:
            return None
    if not port.isdigit():
        return None
    return scheme, host, int(port), user, pwd


# ───────────────── doc HTTP response ─────────────────
def _read_all(s, cap=65536):
    buf = b""
    while len(buf) < cap:
        try:
            c = s.recv(4096)
        except socket.timeout:
            break
        if not c:
            break
        buf += c
    return buf


def _parse_http(raw):
    if b"\r\n\r\n" not in raw:
        return -1, ""
    head, _, body = raw.partition(b"\r\n\r\n")
    first = head.split(b"\r\n", 1)[0].decode("latin1", "ignore").split()
    code = int(first[1]) if len(first) > 1 and first[1].isdigit() else -1
    return code, body.decode("utf-8", "ignore")


def _recvn(s, n):
    buf = b""
    while len(buf) < n:
        c = s.recv(n - len(buf))
        if not c:
            raise RuntimeError("conn closed")
        buf += c
    return buf


# ───────────── tunnel toi 1 (host,port) qua tung loai proxy ─────────────
def _socks5_tunnel(s, host, port, user, pwd):
    methods = b"\x00\x02" if user else b"\x00"
    s.sendall(bytes([5, len(methods)]) + methods)
    _, method = _recvn(s, 2)
    if method == 2:
        if not user:
            raise RuntimeError("can auth")
        s.sendall(b"\x01" + bytes([len(user)]) + user.encode() + bytes([len(pwd)]) + pwd.encode())
        if _recvn(s, 2)[1] != 0:
            raise RuntimeError("sai user/pass")
    elif method != 0:
        raise RuntimeError("no method")
    dh = host.encode()
    s.sendall(b"\x05\x01\x00\x03" + bytes([len(dh)]) + dh + struct.pack(">H", port))
    rep = _recvn(s, 4)
    if rep[1] != 0:
        raise RuntimeError("rep %d" % rep[1])
    atyp = rep[3]
    if atyp == 1:
        _recvn(s, 6)
    elif atyp == 3:
        _recvn(s, _recvn(s, 1)[0] + 2)
    elif atyp == 4:
        _recvn(s, 18)


def _socks4_tunnel(s, host, port, user):
    uid = (user or "").encode()
    s.sendall(b"\x04\x01" + struct.pack(">H", port) + b"\x00\x00\x00\x01"
              + uid + b"\x00" + host.encode() + b"\x00")
    if _recvn(s, 8)[1] != 0x5A:
        raise RuntimeError("reject")


def _http_get_rel(s):
    s.sendall(("GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: Mozilla/5.0\r\n"
               "Connection: close\r\n\r\n" % (T_PATH, T_HOST)).encode())
    return _parse_http(_read_all(s))


def via_http(host, port, user, pwd, timeout):
    s = socket.create_connection((host, port), timeout); s.settimeout(timeout)
    try:
        req = "GET http://%s%s HTTP/1.0\r\nHost: %s\r\n" % (T_HOST, T_PATH, T_HOST)
        if user:
            cred = base64.b64encode(("%s:%s" % (user, pwd)).encode()).decode()
            req += "Proxy-Authorization: Basic %s\r\n" % cred
        req += "User-Agent: Mozilla/5.0\r\nConnection: close\r\n\r\n"
        s.sendall(req.encode())
        code, body = _parse_http(_read_all(s))
        if code == 200:
            return body
        raise RuntimeError("HTTP %s" % (code if code > 0 else "?"))
    finally:
        s.close()


def via_socks5(host, port, user, pwd, timeout):
    s = socket.create_connection((host, port), timeout); s.settimeout(timeout)
    try:
        _socks5_tunnel(s, T_HOST, T_PORT, user, pwd)
        code, body = _http_get_rel(s)
        if code == 200:
            return body
        raise RuntimeError("HTTP %s" % (code if code > 0 else "?"))
    finally:
        s.close()


def via_socks4(host, port, user, pwd, timeout):
    s = socket.create_connection((host, port), timeout); s.settimeout(timeout)
    try:
        _socks4_tunnel(s, T_HOST, T_PORT, user)
        code, body = _http_get_rel(s)
        if code == 200:
            return body
        raise RuntimeError("HTTP %s" % (code if code > 0 else "?"))
    finally:
        s.close()


CHECKERS = {"http": via_http, "socks5": via_socks5, "socks4": via_socks4}
TRY_ORDER = ["http", "socks5", "socks4"]


# ───────────── probe: vao duoc login.live.com:443 khong (CONNECT) ─────────────
def mail_probe(typ, host, port, user, pwd, timeout):
    """True neu tunnel duoc HTTPS toi Microsoft login (CONNECT 443)."""
    try:
        s = socket.create_connection((host, port), timeout); s.settimeout(timeout)
    except Exception:
        return False
    try:
        if typ == "http":
            req = "CONNECT %s:%d HTTP/1.1\r\nHost: %s:%d\r\n" % (MS_HOST, MS_PORT, MS_HOST, MS_PORT)
            if user:
                cred = base64.b64encode(("%s:%s" % (user, pwd)).encode()).decode()
                req += "Proxy-Authorization: Basic %s\r\n" % cred
            req += "\r\n"
            s.sendall(req.encode())
            line = s.recv(256).decode("latin1", "ignore").split("\r\n", 1)[0]
            return " 200" in line
        elif typ == "socks5":
            _socks5_tunnel(s, MS_HOST, MS_PORT, user, pwd)
            return True
        elif typ == "socks4":
            _socks4_tunnel(s, MS_HOST, MS_PORT, user)
            return True
    except Exception:
        return False
    finally:
        s.close()
    return False


# ───────────── check 1 proxy: alive + thong tin IP + cham diem ─────────────
def basic_check(raw, timeout, mail_mode=True):
    p = parse_line(raw)
    if not p:
        return {"raw": (raw or "").strip(), "ok": False, "verdict": "loai",
                "reason": "format sai", "skip": True}
    scheme, host, port, user, pwd = p
    norm = "{}:{}:{}:{}".format(host, port, user, pwd) if user else "{}:{}".format(host, port)

    t0 = time.time()
    try:
        socket.create_connection((host, port), timeout).close()
    except Exception as e:
        return {"raw": norm, "ok": False, "verdict": "loai",
                "reason": "connect: " + (str(e).split("] ")[-1][:22] or "timeout"),
                "ms": int((time.time() - t0) * 1000)}

    order = [scheme] if scheme else TRY_ORDER
    d = None; typ = None; ms = 0; last = "?"
    for t in order:
        ts = time.time()
        try:
            body = CHECKERS[t](host, port, user, pwd, timeout)
            j = json.loads(body)
            if j.get("status") != "success":
                last = "resp la"; continue
            d, typ, ms = j, t, int((time.time() - ts) * 1000)
            break
        except Exception as e:
            last = str(e)[:24]
    if not d:
        return {"raw": norm, "ok": False, "verdict": "loai", "reason": last,
                "ms": int((time.time() - t0) * 1000)}

    has_auth = bool(user)
    hosting = bool(d.get("hosting")); flagged = bool(d.get("proxy")); mobile = bool(d.get("mobile"))
    iptype = "Mobile" if mobile else ("Datacenter" if hosting else "Residential")
    r = {"raw": norm, "ok": True, "type": typ, "ms": ms,
         "ip": d.get("query", "?"), "cc": d.get("countryCode", ""),
         "country": d.get("country", "?"), "isp": (d.get("isp") or d.get("org") or "")[:26],
         "hosting": hosting, "flagged": flagged, "mobile": mobile, "iptype": iptype,
         "https": False, "ms_ok": False}

    # ── cham diem cho tool mail ──
    if not mail_mode:
        r["verdict"], r["reason"] = "tot", "sống (chưa chấm mail)"
        return r

    if typ in ("socks5", "socks4") and has_auth:
        r["verdict"], r["reason"] = "loai", "SOCKS có auth — Camoufox không hỗ trợ"
        return r

    https_ok = mail_probe(typ, host, port, user, pwd, timeout)
    r["https"] = https_ok; r["ms_ok"] = https_ok
    if not https_ok:
        r["verdict"] = "loai"
        r["reason"] = "không CONNECT 443 / không vào được login.live.com"
        return r
    if ms > 8000:
        r["verdict"], r["reason"] = "loai", "latency quá cao (>8s, login dễ timeout)"
        return r

    # qua het gate bat buoc -> tot/rui ro theo chat luong IP
    if flagged:
        r["verdict"], r["reason"] = "ruiro", "IP bị gắn cờ proxy/VPN — dễ bị Microsoft chặn"
    elif hosting:
        r["verdict"], r["reason"] = "ruiro", "datacenter — Microsoft hay challenge IP server"
    elif ms > 3000:
        r["verdict"], r["reason"] = "ruiro", "latency hơi cao (%dms)" % ms
    elif mobile:
        r["verdict"], r["reason"] = "tot", "mobile IP (rất sạch), vào được Microsoft ✓"
    else:
        r["verdict"], r["reason"] = "tot", "residential, vào được Microsoft ✓"
    return r


# ───────────── fetch proxy free ─────────────
def fetch_free(types, log=lambda s: None):
    seen, out = set(), []
    for typ in types:
        for url in SOURCES.get(typ, []):
            try:
                req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
                txt = urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "ignore")
            except Exception as e:
                log("  ✗ nguồn lỗi: %s (%s)" % (url.split("/")[2], str(e)[:30]))
                continue
            n = 0
            for line in txt.splitlines():
                m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3}):(\d{2,5})", line)
                if not m:
                    continue
                key = "%s:%s" % (m.group(1), m.group(2))
                if key in seen:
                    continue
                seen.add(key)
                out.append("%s://%s" % (typ, key))
                n += 1
            log("  ✓ %-22s +%d (%s)" % (url.split("/")[2], n, typ))
    return out


# ═══════════════════════════ GUI ═══════════════════════════
BG = "#0f1117"; PANEL = "#171a23"; CARD = "#1c2030"; LINE = "#2a2f3e"
TXT = "#e7e9ee"; MUT = "#8b90a0"; GOLD = "#e8b04b"
GREEN = "#46d39a"; ORANGE = "#f0a843"; RED = "#ef5e6a"; BLUE = "#5cc8ff"

COLS = [("#", 38), ("Proxy", 168), ("Loại", 60), ("IP thoát", 124), ("Quốc gia", 92),
        ("ISP", 168), ("ms", 56), ("443", 42), ("MS", 42), ("Kiểu IP", 88), ("Đánh giá", 300)]


class App:
    def __init__(self, root, parent=None):
        # root = toplevel (cho after/clipboard); parent = noi nhung widget (mac dinh = root).
        # Khi nhung vao 1 tab Notebook -> truyen parent = frame cua tab.
        self.root = root
        self.parent = parent if parent is not None else root
        self.q = queue.Queue()
        self.stop = threading.Event()
        self.running = False
        self.rows = []           # ket qua dung duoc/song
        self.input = []          # list proxy raw cho lan check
        if isinstance(root, (tk.Tk, tk.Toplevel)):
            root.title("Agapia ProxyTool")
            root.geometry("1180x720")
            root.minsize(980, 560)
        try: self.parent.configure(bg=BG)
        except Exception: pass
        self._style()
        self._build()
        self.root.after(80, self._pump)

    def _style(self):
        s = ttk.Style()
        try: s.theme_use("clam")
        except Exception: pass
        s.configure(".", background=BG, foreground=TXT, fieldbackground=CARD, borderwidth=0)
        s.configure("TFrame", background=BG)
        s.configure("Card.TFrame", background=PANEL)
        s.configure("TLabel", background=BG, foreground=TXT, font=("Segoe UI", 10))
        s.configure("Mut.TLabel", background=BG, foreground=MUT, font=("Segoe UI", 9))
        s.configure("Card.TLabel", background=PANEL, foreground=TXT, font=("Segoe UI", 10))
        s.configure("CardMut.TLabel", background=PANEL, foreground=MUT, font=("Segoe UI", 9))
        s.configure("TCheckbutton", background=PANEL, foreground=TXT, font=("Segoe UI", 9))
        s.map("TCheckbutton", background=[("active", PANEL)])
        s.configure("TSpinbox", arrowsize=12, fieldbackground=CARD, foreground=TXT, background=CARD)
        # buttons
        s.configure("Tool.TButton", background=CARD, foreground=TXT, font=("Segoe UI Semibold", 9),
                    borderwidth=0, focusthickness=0, padding=(12, 7))
        s.map("Tool.TButton", background=[("active", "#262c3c"), ("disabled", "#161a24")],
              foreground=[("disabled", "#555b6b")])
        s.configure("Gold.TButton", background=GOLD, foreground="#1a1200",
                    font=("Segoe UI Semibold", 9), borderwidth=0, padding=(14, 7))
        s.map("Gold.TButton", background=[("active", "#f2c160"), ("disabled", "#5a4a23")])
        # treeview
        s.configure("Treeview", background=CARD, fieldbackground=CARD, foreground=TXT,
                    rowheight=27, borderwidth=0, font=("Consolas", 9))
        s.configure("Treeview.Heading", background=PANEL, foreground=GOLD,
                    font=("Segoe UI Semibold", 9), borderwidth=0, relief="flat")
        s.map("Treeview.Heading", background=[("active", PANEL)])
        s.map("Treeview", background=[("selected", "#2d3447")], foreground=[("selected", "#fff")])
        s.configure("gold.Horizontal.TProgressbar", troughcolor=CARD, background=GOLD,
                    borderwidth=0, thickness=10)

    def _build(self):
        pad = dict(padx=14)
        # ── header ──
        head = tk.Frame(self.parent, bg=BG); head.pack(fill="x", pady=(12, 6), **pad)
        tk.Label(head, text="◆ Agapia ProxyTool", bg=BG, fg=GOLD,
                 font=("Segoe UI Semibold", 16)).pack(side="left")
        tk.Label(head, text="  Tìm · Kiểm tra · Chấm điểm proxy cho automation", bg=BG, fg=MUT,
                 font=("Segoe UI", 10)).pack(side="left", pady=(6, 0))

        # ── toolbar ──
        bar = tk.Frame(self.parent, bg=BG); bar.pack(fill="x", pady=4, **pad)
        self.b_find = ttk.Button(bar, text="🔎 Tìm proxy free", style="Gold.TButton", command=self.on_find)
        self.b_find.pack(side="left", padx=(0, 6))
        self.b_imp = ttk.Button(bar, text="📥 Nhập file / Dán", style="Tool.TButton", command=self.on_import)
        self.b_imp.pack(side="left", padx=3)
        self.b_run = ttk.Button(bar, text="▶ Kiểm tra & Chấm điểm", style="Tool.TButton", command=self.on_run)
        self.b_run.pack(side="left", padx=3)
        self.b_stop = ttk.Button(bar, text="⏹ Dừng", style="Tool.TButton", command=self.on_stop)
        self.b_stop.pack(side="left", padx=3); self.b_stop.state(["disabled"])
        self.b_copy = ttk.Button(bar, text="📋 Copy “dùng được”", style="Tool.TButton", command=self.on_copy)
        self.b_copy.pack(side="left", padx=3)
        self.b_save = ttk.Button(bar, text="💾 Lưu…", style="Tool.TButton", command=self.on_save)
        self.b_save.pack(side="left", padx=3)

        # ── options ──
        opt = tk.Frame(self.parent, bg=PANEL); opt.pack(fill="x", pady=4, **pad)
        inner = tk.Frame(opt, bg=PANEL); inner.pack(fill="x", padx=12, pady=8)
        tk.Label(inner, text="Luồng", bg=PANEL, fg=MUT, font=("Segoe UI", 9)).pack(side="left")
        self.v_threads = tk.IntVar(value=100)
        ttk.Spinbox(inner, from_=10, to=500, increment=10, width=5, textvariable=self.v_threads).pack(side="left", padx=(4, 14))
        tk.Label(inner, text="Timeout(s)", bg=PANEL, fg=MUT, font=("Segoe UI", 9)).pack(side="left")
        self.v_to = tk.IntVar(value=8)
        ttk.Spinbox(inner, from_=3, to=30, width=4, textvariable=self.v_to).pack(side="left", padx=(4, 14))
        tk.Label(inner, text="Nguồn:", bg=PANEL, fg=MUT, font=("Segoe UI", 9)).pack(side="left")
        self.v_http = tk.BooleanVar(value=True); self.v_s4 = tk.BooleanVar(value=True); self.v_s5 = tk.BooleanVar(value=True)
        for txt_, var in (("HTTP", self.v_http), ("SOCKS4", self.v_s4), ("SOCKS5", self.v_s5)):
            ttk.Checkbutton(inner, text=txt_, variable=var).pack(side="left", padx=4)
        self.v_mail = tk.BooleanVar(value=True)
        ttk.Checkbutton(inner, text="🎯 Chế độ Mail (chấm cho login Outlook)", variable=self.v_mail).pack(side="left", padx=(16, 0))
        self.v_auto = tk.BooleanVar(value=True)
        ttk.Checkbutton(inner, text="Tự chấm sau khi tìm", variable=self.v_auto).pack(side="left", padx=(12, 0))
        self.v_onlygood = tk.BooleanVar(value=False)
        ttk.Checkbutton(inner, text="📋 Copy/Lưu chỉ ✅ Tốt", variable=self.v_onlygood).pack(side="left", padx=(12, 0))

        # ── table ──
        wrap = tk.Frame(self.parent, bg=BG); wrap.pack(fill="both", expand=True, pady=6, **pad)
        self.tree = ttk.Treeview(wrap, columns=[c[0] for c in COLS], show="headings", selectmode="extended")
        for name, w in COLS:
            self.tree.heading(name, text=name)
            self.tree.column(name, width=w, anchor=("center" if name in ("#", "Loại", "ms", "443", "MS") else "w"),
                             stretch=(name in ("ISP", "Đánh giá")))
        vs = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=vs.set)
        self.tree.pack(side="left", fill="both", expand=True); vs.pack(side="right", fill="y")
        self.tree.tag_configure("tot", foreground=GREEN)
        self.tree.tag_configure("ruiro", foreground=ORANGE)
        self.tree.tag_configure("loai", foreground=MUT)
        self.tree.tag_configure("odd", background="#191d28")

        # ── progress + status ──
        bot = tk.Frame(self.parent, bg=BG); bot.pack(fill="x", **pad)
        self.pb = ttk.Progressbar(bot, style="gold.Horizontal.TProgressbar", mode="determinate")
        self.pb.pack(fill="x", pady=(2, 4))
        self.v_status = tk.StringVar(value="Sẵn sàng. Bấm 🔎 Tìm proxy free để bắt đầu.")
        tk.Label(bot, textvariable=self.v_status, bg=BG, fg=TXT, font=("Segoe UI", 9), anchor="w").pack(fill="x")
        legend = ("✅ Tốt = residential, vào được Microsoft   "
                  "⚠️ Rủi ro = datacenter/IP gắn cờ/latency cao   "
                  "❌ Loại = chết / không HTTPS / SOCKS-auth")
        tk.Label(bot, text=legend, bg=BG, fg=MUT, font=("Segoe UI", 8), anchor="w").pack(fill="x", pady=(0, 8))

    # ───────── helpers ─────────
    def log(self, s):
        self.q.put(("status", s))

    def _set_busy(self, busy):
        self.running = busy
        st = ["disabled"] if busy else ["!disabled"]
        for b in (self.b_find, self.b_imp, self.b_run, self.b_copy, self.b_save):
            b.state(st)
        self.b_stop.state(["!disabled"] if busy else ["disabled"])

    # ───────── actions ─────────
    def on_find(self):
        if self.running: return
        types = [t for t, v in (("http", self.v_http), ("socks4", self.v_s4), ("socks5", self.v_s5)) if v.get()]
        if not types:
            messagebox.showwarning("Nguồn", "Chọn ít nhất 1 nguồn (HTTP/SOCKS4/SOCKS5)."); return
        self._clear()
        self._set_busy(True)
        self.v_status.set("Đang tìm proxy free…")
        threading.Thread(target=self._find_worker, args=(types,), daemon=True).start()

    def _find_worker(self, types):
        got = fetch_free(types, log=self.log)
        self.input = got
        self.q.put(("found", len(got)))
        if self.v_auto.get() and got and not self.stop.is_set():
            self._check_worker(got)
        else:
            self.q.put(("done", None))

    def on_import(self):
        if self.running: return
        path = filedialog.askopenfilename(title="Chọn file proxy",
                                          filetypes=[("Text", "*.txt"), ("All", "*.*")])
        if not path: return
        try:
            data = open(path, encoding="utf-8", errors="ignore").read().splitlines()
        except Exception as e:
            messagebox.showerror("Lỗi", str(e)); return
        self.input = [l for l in data if l.strip() and not l.strip().startswith("#")]
        self.v_status.set("Đã nạp %d proxy từ file. Bấm ▶ để kiểm tra." % len(self.input))

    def on_run(self):
        if self.running: return
        if not self.input:
            messagebox.showinfo("Chưa có proxy", "Bấm 🔎 Tìm proxy free hoặc 📥 Nhập file trước."); return
        self._clear()
        self._set_busy(True)
        threading.Thread(target=self._check_worker, args=(list(self.input),), daemon=True).start()

    def _check_worker(self, items):
        self.stop.clear()
        to = max(3, self.v_to.get()); th = max(10, self.v_threads.get())
        mail = self.v_mail.get()
        total = len(items); done = 0
        self.q.put(("begin", total))
        with ThreadPoolExecutor(max_workers=th) as ex:
            futs = [ex.submit(basic_check, it, to, mail) for it in items]
            for f in futs:
                if self.stop.is_set():
                    break
                try: r = f.result()
                except Exception: continue
                done += 1
                self.q.put(("row", (done, r)))
        self.q.put(("done", None))

    def on_stop(self):
        self.stop.set(); self.v_status.set("Đang dừng…")

    def _picked(self):
        """Danh sach proxy chon de copy/luu theo toggle 'chi ✅ Tot'."""
        keep = ("tot",) if self.v_onlygood.get() else ("tot", "ruiro")
        return [r for r in self.rows if r.get("verdict") in keep], keep

    def on_copy(self):
        good, keep = self._picked()
        if not good:
            tip = "Chưa có con ✅ Tốt nào." if keep == ("tot",) else "Chưa có proxy dùng được."
            messagebox.showinfo("Chưa có", tip + " (bỏ tick “chỉ ✅ Tốt” để lấy cả ⚠️ Rủi ro)"); return
        text = "\n".join("%s://%s" % (r["type"], r["raw"]) for r in good)
        self.root.clipboard_clear(); self.root.clipboard_append(text)
        lbl = "✅ Tốt" if keep == ("tot",) else "dùng được (✅+⚠️)"
        self.v_status.set("📋 Đã copy %d proxy %s vào clipboard." % (len(good), lbl))

    def on_save(self):
        good, keep = self._picked()
        if not good:
            tip = "Chưa có con ✅ Tốt nào." if keep == ("tot",) else "Chưa có proxy dùng được."
            messagebox.showinfo("Chưa có", tip); return
        name = "proxy_tot.txt" if keep == ("tot",) else "proxy_dungduoc.txt"
        path = filedialog.asksaveasfilename(defaultextension=".txt", initialfile=name,
                                            filetypes=[("Text", "*.txt")])
        if not path: return
        with open(path, "w", encoding="utf-8") as f:
            for r in sorted(good, key=lambda x: (x["verdict"] != "tot", x["ms"])):
                f.write("%s://%s\n" % (r["type"], r["raw"]))
        self.v_status.set("💾 Đã lưu %d proxy vào %s" % (len(good), path))

    def _clear(self):
        self.tree.delete(*self.tree.get_children())
        self.rows = []
        self.pb["value"] = 0

    # ───────── UI pump (thread-safe) ─────────
    def _pump(self):
        try:
            while True:
                kind, data = self.q.get_nowait()
                if kind == "status":
                    self.v_status.set(data)
                elif kind == "found":
                    self.v_status.set("Đã tìm %d proxy. %s" % (
                        data, "Đang chấm điểm…" if self.v_auto.get() else "Bấm ▶ để kiểm tra."))
                elif kind == "begin":
                    self.pb["maximum"] = data; self.pb["value"] = 0
                    self._n_alive = self._n_good = self._n_risk = self._n_bad = 0
                elif kind == "row":
                    self._add_row(*data)
                elif kind == "done":
                    self._set_busy(False)
                    self._summary()
        except queue.Empty:
            pass
        self.root.after(80, self._pump)

    def _add_row(self, idx, r):
        self.pb["value"] = idx
        v = r.get("verdict", "loai")
        ico = {"tot": "✅", "ruiro": "⚠️", "loai": "❌"}.get(v, "❌")
        if r.get("ok"):
            self._n_alive += 1
            if v == "tot": self._n_good += 1
            elif v == "ruiro": self._n_risk += 1
            else: self._n_bad += 1
            self.rows.append(r)
            vals = (idx, r["raw"], r["type"], r["ip"], "%s %s" % (r["cc"], r["country"]),
                    r["isp"], r["ms"], "✓" if r["https"] else "✗", "✓" if r["ms_ok"] else "✗",
                    r["iptype"], "%s %s" % (ico, r["reason"]))
        else:
            self._n_bad += 1
            vals = (idx, r.get("raw", "")[:30], "-", "-", "-", "-", r.get("ms", ""),
                    "✗", "✗", "-", "❌ %s" % r.get("reason", ""))
        tags = [v]
        if idx % 2 == 0: tags.append("odd")
        self.tree.insert("", "end", values=vals, tags=tuple(tags))
        if idx % 7 == 0:
            self.v_status.set("Đang quét %d/%d · sống %d · ✅%d ⚠️%d ❌%d"
                              % (idx, self.pb["maximum"], self._n_alive,
                                 self._n_good, self._n_risk, self._n_bad))

    def _summary(self):
        tot = int(self.pb["maximum"]) if self.pb["maximum"] else len(self.rows)
        a = getattr(self, "_n_alive", 0); g = getattr(self, "_n_good", 0)
        rk = getattr(self, "_n_risk", 0); b = getattr(self, "_n_bad", 0)
        self.v_status.set("✔ Xong %d proxy · Sống %d · ✅ Tốt %d · ⚠️ Rủi ro %d · ❌ Loại %d  "
                          "→ dùng được (✅+⚠️): %d" % (tot, a, g, rk, b, g + rk))


def main():
    if not HAVE_TK:
        print("Khong co tkinter — chay engine headless. Cai Python ban du (python.org) co tkinter de mo GUI.")
        return
    root = tk.Tk()
    App(root)
    root.mainloop()


if __name__ == "__main__":
    main()