proxy_finder: tach loai/chat luong dung Save-As (dat ten file), nhap nhieu file 1 lan
1bde0a3 verified | #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Agapia Proxy Finder — TIM proxy free tren internet (cang nhieu cang tot) + CHECK + PHAN LOAI | |
| chi tiet theo tung loai (HTTP / SOCKS5 / SOCKS4). Stdlib thuan (tu bat tay SOCKS, khong cai gi). | |
| Tool ĐỘC LẬP — khong phu thuoc file khac, khong dinh gi toi mail. | |
| Chay: python proxy_finder.py (console den -> doi duoi .pyw) | |
| """ | |
| import os, sys, re, time, json, socket, struct, base64, threading, queue, ssl | |
| import urllib.request | |
| # VPS Windows hay thieu CA root -> urllib verify SSL that bai (du curl/pip van chay). | |
| # List proxy la du lieu CONG KHAI nen cho phep tai lai khong verify khi gap loi SSL. | |
| _UNVERIFIED = ssl._create_unverified_context() | |
| from concurrent.futures import ThreadPoolExecutor | |
| try: | |
| import tkinter as tk | |
| from tkinter import ttk, filedialog, messagebox | |
| HAVE_TK = True | |
| except Exception: | |
| HAVE_TK = False | |
| # ─────────── test endpoint: IP thoat + quoc gia + ISP + co datacenter/proxy/mobile ─────────── | |
| T_HOST, T_PORT = "ip-api.com", 80 | |
| T_PATH = "/json/?fields=status,query,country,countryCode,city,isp,org,proxy,hosting,mobile" | |
| SCHEME_MAP = {"http": "http", "https": "http", "socks5": "socks5", "socks5h": "socks5", | |
| "socks4": "socks4", "socks4a": "socks4", "socks": "socks5"} | |
| # Nguon proxy free (da verify song). "big" = nguon hang chuc-tram nghin (bat khi muon TOI DA). | |
| 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", | |
| ], | |
| } | |
| SOURCES_BIG = { | |
| "http": ["https://raw.githubusercontent.com/MuRongPIG/Proxy-Master/main/http.txt"], | |
| "socks4": ["https://raw.githubusercontent.com/MuRongPIG/Proxy-Master/main/socks4.txt"], | |
| "socks5": ["https://raw.githubusercontent.com/MuRongPIG/Proxy-Master/main/socks5.txt"], | |
| } | |
| # ─────────── parse + tunnel (HTTP / SOCKS5 / SOCKS4) ─────────── | |
| def parse_line(line): | |
| 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 | |
| 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("closed") | |
| buf += c | |
| return buf | |
| def _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, to): | |
| s = socket.create_connection((host, port), to); s.settimeout(to) | |
| try: | |
| req = "GET http://%s%s HTTP/1.0\r\nHost: %s\r\n" % (T_HOST, T_PATH, T_HOST) | |
| if user: | |
| req += "Proxy-Authorization: Basic %s\r\n" % base64.b64encode(("%s:%s" % (user, pwd)).encode()).decode() | |
| 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, to): | |
| s = socket.create_connection((host, port), to); s.settimeout(to) | |
| try: | |
| 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("auth") | |
| s.sendall(b"\x01" + bytes([len(user)]) + user.encode() + bytes([len(pwd)]) + pwd.encode()) | |
| if _recvn(s, 2)[1] != 0: raise RuntimeError("badauth") | |
| elif method != 0: raise RuntimeError("nomethod") | |
| dh = T_HOST.encode() | |
| s.sendall(b"\x05\x01\x00\x03" + bytes([len(dh)]) + dh + struct.pack(">H", T_PORT)) | |
| rep = _recvn(s, 4) | |
| if rep[1] != 0: raise RuntimeError("rep%d" % rep[1]) | |
| a = rep[3] | |
| if a == 1: _recvn(s, 6) | |
| elif a == 3: _recvn(s, _recvn(s, 1)[0] + 2) | |
| elif a == 4: _recvn(s, 18) | |
| code, body = _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, to): | |
| s = socket.create_connection((host, port), to); s.settimeout(to) | |
| try: | |
| uid = (user or "").encode() | |
| s.sendall(b"\x04\x01" + struct.pack(">H", T_PORT) + b"\x00\x00\x00\x01" + uid + b"\x00" + T_HOST.encode() + b"\x00") | |
| if _recvn(s, 8)[1] != 0x5A: raise RuntimeError("reject") | |
| code, body = _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"] | |
| def check(raw, to): | |
| p = parse_line(raw) | |
| if not p: | |
| return {"raw": (raw or "").strip(), "ok": False, "err": "format"} | |
| 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), to).close() | |
| except Exception as e: | |
| return {"raw": norm, "ok": False, "err": "connect", "ms": int((time.time() - t0) * 1000)} | |
| order = [scheme] if scheme else TRY_ORDER | |
| for t in order: | |
| ts = time.time() | |
| try: | |
| d = json.loads(CHECKERS[t](host, port, user, pwd, to)) | |
| if d.get("status") != "success": continue | |
| ms = int((time.time() - ts) * 1000) | |
| host_dc = bool(d.get("hosting")); flg = bool(d.get("proxy")); mob = bool(d.get("mobile")) | |
| iptype = "Mobile" if mob else ("Datacenter" if host_dc else "Residential") | |
| if flg: iptype += " ⚑" | |
| qk, qr = quality(ms, host_dc, flg, mob) | |
| return {"raw": norm, "ok": True, "type": t, "ms": ms, | |
| "ip": d.get("query", "?"), "cc": d.get("countryCode", ""), | |
| "country": d.get("country", "?"), "isp": (d.get("isp") or d.get("org") or "")[:26], | |
| "iptype": iptype, "q": qk, "qreason": qr} | |
| except Exception: | |
| pass | |
| return {"raw": norm, "ok": False, "err": "dead", "ms": int((time.time() - t0) * 1000)} | |
| def quality(ms, dc, flg, mob): | |
| """Cham CHAT LUONG CHUNG (khong dinh dich vu nao): latency + residential/datacenter + co proxy. | |
| Tra (key, ly_do). key: rattot/tot/tb/kem.""" | |
| if flg: # IP bi gan co proxy/VPN | |
| return ("tb", "IP gắn cờ proxy/VPN") if ms < 2500 else ("kem", "gắn cờ proxy + chậm") | |
| if ms > 6000: | |
| return "kem", "rất chậm (%dms)" % ms | |
| if mob: # mobile = sach nhat | |
| return ("rattot", "mobile, nhanh") if ms < 2500 else ("tot", "mobile") | |
| if not dc: # residential | |
| if ms < 1500: return "rattot", "residential, nhanh" | |
| if ms < 3500: return "tot", "residential" | |
| return "tb", "residential, hơi chậm" | |
| # datacenter, khong co | |
| if ms < 1500: return "tot", "datacenter, nhanh" | |
| if ms < 4000: return "tb", "datacenter" | |
| return "kem", "datacenter, chậm" | |
| def fetch_free(types, big=False, log=lambda s: None): | |
| seen, out = set(), [] | |
| for typ in types: | |
| urls = list(SOURCES.get(typ, [])) | |
| if big: urls += SOURCES_BIG.get(typ, []) | |
| for url in urls: | |
| req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) | |
| txt = None; last = "" | |
| for ctx in (None, _UNVERIFIED): # thu verify truoc, loi -> bo verify | |
| try: | |
| txt = urllib.request.urlopen(req, timeout=20, context=ctx).read().decode("utf-8", "ignore") | |
| break | |
| except Exception as e: | |
| last = str(e)[:30] | |
| if txt is None: | |
| log(" ✗ %s (%s)" % (url.split("/")[2], last)); 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"; TXT = "#e7e9ee"; MUT = "#8b90a0" | |
| GOLD = "#e8b04b"; GREEN = "#46d39a"; BLUE = "#5cc8ff"; VIOLET = "#b08cff"; ORANGE = "#f0a843" | |
| TCOL = {"http": BLUE, "socks5": GREEN, "socks4": VIOLET} | |
| # danh gia chat luong CHUNG: key -> (nhan, mau) | |
| QMETA = {"rattot": ("★ Rất tốt", GREEN), "tot": ("● Tốt", BLUE), | |
| "tb": ("▲ Trung bình", ORANGE), "kem": ("✗ Kém", MUT)} | |
| QFILTER = {"rất tốt": "rattot", "tốt": "tot", "trung bình": "tb", "kém": "kem"} | |
| COLS = [("#", 44), ("Proxy", 172), ("Loại", 58), ("IP thoát", 116), ("Quốc gia", 90), | |
| ("ISP", 150), ("Kiểu IP", 116), ("ms", 56), ("Đánh giá", 232)] | |
| class App: | |
| def __init__(self, root): | |
| self.root = root | |
| self.q = queue.Queue(); self.stop = threading.Event() | |
| self.running = False; self.rows = []; self.input = [] | |
| root.title("Agapia Proxy Finder"); root.configure(bg=BG) | |
| root.geometry("1200x720"); root.minsize(980, 560) | |
| 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("TLabel", background=BG, foreground=TXT, font=("Segoe UI", 10)) | |
| s.configure("TCheckbutton", background=PANEL, foreground=TXT, font=("Segoe UI", 9)) | |
| s.map("TCheckbutton", background=[("active", PANEL)]) | |
| s.configure("TSpinbox", fieldbackground=CARD, foreground=TXT, background=CARD, arrowsize=12) | |
| s.configure("TCombobox", fieldbackground=CARD, background=CARD, foreground=TXT) | |
| s.configure("Tool.TButton", background=CARD, foreground=TXT, font=("Segoe UI Semibold", 9), | |
| borderwidth=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")]) | |
| 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) | |
| 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) | |
| head = tk.Frame(self.root, bg=BG); head.pack(fill="x", pady=(12, 6), **pad) | |
| tk.Label(head, text="◆ Agapia Proxy Finder", bg=BG, fg=GOLD, font=("Segoe UI Semibold", 16)).pack(side="left") | |
| tk.Label(head, text=" Gom proxy free trên internet · check · phân loại từng loại", | |
| bg=BG, fg=MUT, font=("Segoe UI", 10)).pack(side="left", pady=(6, 0)) | |
| bar = tk.Frame(self.root, 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", 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", 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", 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) | |
| self.b_split = ttk.Button(bar, text="💾 Tách loại", style="Tool.TButton", command=self.on_save_split) | |
| self.b_split.pack(side="left", padx=3) | |
| self.b_splitq = ttk.Button(bar, text="💾 Tách chất lượng", style="Tool.TButton", command=self.on_save_split_q) | |
| self.b_splitq.pack(side="left", padx=3) | |
| opt = tk.Frame(self.root, bg=PANEL); opt.pack(fill="x", pady=4, **pad) | |
| inn = tk.Frame(opt, bg=PANEL); inn.pack(fill="x", padx=12, pady=8) | |
| tk.Label(inn, text="Luồng", bg=PANEL, fg=MUT, font=("Segoe UI", 9)).pack(side="left") | |
| self.v_threads = tk.IntVar(value=120) | |
| ttk.Spinbox(inn, from_=10, to=500, increment=10, width=5, textvariable=self.v_threads).pack(side="left", padx=(4, 14)) | |
| tk.Label(inn, text="Timeout(s)", bg=PANEL, fg=MUT, font=("Segoe UI", 9)).pack(side="left") | |
| self.v_to = tk.IntVar(value=8) | |
| ttk.Spinbox(inn, from_=3, to=30, width=4, textvariable=self.v_to).pack(side="left", padx=(4, 14)) | |
| tk.Label(inn, 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 t_, v_ in (("HTTP", self.v_http), ("SOCKS4", self.v_s4), ("SOCKS5", self.v_s5)): | |
| ttk.Checkbutton(inn, text=t_, variable=v_).pack(side="left", padx=4) | |
| self.v_big = tk.BooleanVar(value=False) | |
| ttk.Checkbutton(inn, text="Tối đa (nguồn lớn, chậm)", variable=self.v_big).pack(side="left", padx=(10, 0)) | |
| tk.Label(inn, text=" Hiện:", bg=PANEL, fg=MUT, font=("Segoe UI", 9)).pack(side="left") | |
| self.v_filter = tk.StringVar(value="tất cả") | |
| cb = ttk.Combobox(inn, textvariable=self.v_filter, width=8, state="readonly", | |
| values=["tất cả", "http", "socks5", "socks4"]) | |
| cb.pack(side="left", padx=4); cb.bind("<<ComboboxSelected>>", lambda e: self._refilter()) | |
| tk.Label(inn, text="Chất lượng:", bg=PANEL, fg=MUT, font=("Segoe UI", 9)).pack(side="left", padx=(6, 0)) | |
| self.v_qual = tk.StringVar(value="tất cả") | |
| cbq = ttk.Combobox(inn, textvariable=self.v_qual, width=11, state="readonly", | |
| values=["tất cả", "rất tốt", "tốt", "trung bình", "kém"]) | |
| cbq.pack(side="left", padx=4); cbq.bind("<<ComboboxSelected>>", lambda e: self._refilter()) | |
| wrap = tk.Frame(self.root, 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") | |
| 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") else "w"), | |
| stretch=(name == "ISP")) | |
| 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") | |
| for qk, (lbl, col) in QMETA.items(): # mau HANG theo CHAT LUONG | |
| self.tree.tag_configure(qk, foreground=col) | |
| self.tree.tag_configure("odd", background="#191d28") | |
| bot = tk.Frame(self.root, 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 để gom + kiểm tra.") | |
| tk.Label(bot, textvariable=self.v_status, bg=BG, fg=TXT, font=("Segoe UI", 9), anchor="w").pack(fill="x") | |
| tk.Label(bot, text="Màu hàng theo chất lượng: ★ Rất tốt (xanh lá) · ● Tốt (xanh dương) · ▲ Trung bình (cam) · " | |
| "✗ Kém (xám). ⚑ = IP gắn cờ proxy/VPN. Cột Loại = http/socks5/socks4.", | |
| bg=BG, fg=MUT, font=("Segoe UI", 8), anchor="w").pack(fill="x", pady=(0, 8)) | |
| # ── actions ── | |
| def _set_busy(self, b): | |
| self.running = b | |
| for x in (self.b_find, self.b_imp, self.b_run, self.b_copy, self.b_save, self.b_split, self.b_splitq): | |
| x.state(["disabled"] if b else ["!disabled"]) | |
| self.b_stop.state(["!disabled"] if b else ["disabled"]) | |
| 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 loại nguồn."); return | |
| self._clear(); self._set_busy(True); self.v_status.set("Đang gom proxy…") | |
| threading.Thread(target=self._find_worker, args=(types, self.v_big.get()), daemon=True).start() | |
| def _find_worker(self, types, big): | |
| got = fetch_free(types, big=big, log=lambda s: self.q.put(("status", s))) | |
| self.input = got; self.q.put(("found", len(got))) | |
| if 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 | |
| paths = filedialog.askopenfilenames(title="Chọn 1 hoặc nhiều file proxy", | |
| filetypes=[("Text", "*.txt"), ("All", "*.*")]) | |
| if not paths: return | |
| lines = []; nf = 0 | |
| for p in paths: | |
| try: | |
| data = open(p, encoding="utf-8", errors="ignore").read().splitlines() | |
| lines += [l for l in data if l.strip() and not l.strip().startswith("#")] | |
| nf += 1 | |
| except Exception as e: | |
| messagebox.showerror("Lỗi", "%s: %s" % (p, str(e)[:60])) | |
| self.input = lines | |
| self.v_status.set("Đã nạp %d proxy từ %d file. Bấm ▶ Kiểm tra." % (len(lines), nf)) | |
| def on_run(self): | |
| if self.running: return | |
| if not self.input: | |
| messagebox.showinfo("Chưa có", "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()) | |
| self.q.put(("begin", len(items))) | |
| with ThreadPoolExecutor(max_workers=th) as ex: | |
| futs = [ex.submit(check, it, to) for it in items] | |
| done = 0 | |
| 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 _passes(self, r): | |
| f = self.v_filter.get(); q = self.v_qual.get() | |
| if f != "tất cả" and r.get("type") != f: | |
| return False | |
| if q != "tất cả" and r.get("q") != QFILTER.get(q): | |
| return False | |
| return True | |
| def _selected_alive(self): | |
| return [r for r in self.rows if r.get("ok") and self._passes(r)] | |
| def on_copy(self): | |
| rows = self._selected_alive() | |
| if not rows: | |
| messagebox.showinfo("Chưa có", "Chưa có proxy để copy."); return | |
| self.root.clipboard_clear() | |
| self.root.clipboard_append("\n".join("%s://%s" % (r["type"], r["raw"]) for r in rows)) | |
| self.v_status.set("📋 Đã copy %d proxy (%s) vào clipboard." % (len(rows), self.v_filter.get())) | |
| def on_save(self): | |
| rows = self._selected_alive() | |
| if not rows: | |
| messagebox.showinfo("Chưa có", "Chưa có proxy để lưu."); return | |
| path = filedialog.asksaveasfilename(defaultextension=".txt", | |
| initialfile="proxy_%s.txt" % self.v_filter.get().replace("ấ", "a").replace(" ", "_"), | |
| filetypes=[("Text", "*.txt")]) | |
| if not path: return | |
| with open(path, "w", encoding="utf-8") as f: | |
| for r in sorted(rows, key=lambda x: (x["type"], x["ms"])): | |
| f.write("%s://%s\n" % (r["type"], r["raw"])) | |
| self.v_status.set("💾 Đã lưu %d proxy vào %s" % (len(rows), path)) | |
| def on_save_split(self): | |
| alive = [r for r in self.rows if r.get("ok")] | |
| qf = self.v_qual.get() # ton trong loc chat luong dang chon | |
| if qf != "tất cả": | |
| alive = [r for r in alive if r.get("q") == QFILTER.get(qf)] | |
| if not alive: | |
| messagebox.showinfo("Chưa có", "Chưa có proxy để lưu."); return | |
| path = filedialog.asksaveasfilename(defaultextension=".txt", initialfile="proxy.txt", | |
| filetypes=[("Text", "*.txt")], title="Đặt tên file (tự thêm _http / _socks5 / _socks4)") | |
| if not path: | |
| return | |
| base, ext = os.path.splitext(path); ext = ext or ".txt" | |
| c = {} | |
| for typ in ("http", "socks5", "socks4"): | |
| rows = sorted([r for r in alive if r["type"] == typ], key=lambda x: x["ms"]) | |
| c[typ] = len(rows) | |
| if not rows: | |
| continue | |
| with open("%s_%s%s" % (base, typ, ext), "w", encoding="utf-8") as f: | |
| for r in rows: | |
| f.write("%s://%s\n" % (r["type"], r["raw"])) | |
| self.v_status.set("💾 Đã tách: http %d · socks5 %d · socks4 %d → %s_*%s" | |
| % (c["http"], c["socks5"], c["socks4"], os.path.basename(base), ext)) | |
| def on_save_split_q(self): | |
| alive = [r for r in self.rows if r.get("ok")] | |
| tf = self.v_filter.get() # ton trong loc LOAI dang chon | |
| if tf != "tất cả": | |
| alive = [r for r in alive if r["type"] == tf] | |
| if not alive: | |
| messagebox.showinfo("Chưa có", "Chưa có proxy để lưu."); return | |
| path = filedialog.asksaveasfilename(defaultextension=".txt", initialfile="proxy.txt", | |
| filetypes=[("Text", "*.txt")], title="Đặt tên file (tự thêm _rattot / _tot / _trungbinh / _kem)") | |
| if not path: | |
| return | |
| base, ext = os.path.splitext(path); ext = ext or ".txt" | |
| names = {"rattot": "rattot", "tot": "tot", "tb": "trungbinh", "kem": "kem"} | |
| c = {} | |
| for qk, fn in names.items(): | |
| rows = sorted([r for r in alive if r.get("q") == qk], key=lambda x: (x["type"], x["ms"])) | |
| c[qk] = len(rows) | |
| if not rows: | |
| continue | |
| with open("%s_%s%s" % (base, fn, ext), "w", encoding="utf-8") as f: | |
| for r in rows: | |
| f.write("%s://%s\n" % (r["type"], r["raw"])) | |
| self.v_status.set("💾 Tách chất lượng: ★%d ●%d ▲%d ✗%d → %s_*%s" | |
| % (c["rattot"], c["tot"], c["tb"], c["kem"], os.path.basename(base), ext)) | |
| def _clear(self): | |
| self.tree.delete(*self.tree.get_children()); self.rows = []; self.pb["value"] = 0; self._checked = 0 | |
| def _refilter(self): | |
| self.tree.delete(*self.tree.get_children()) | |
| i = 0 | |
| for r in self._selected_alive(): | |
| i += 1; self._insert(i, r) | |
| self._count() | |
| def _insert(self, i, r): | |
| tags = [r.get("q", "tb")] # mau hang theo chat luong | |
| if i % 2 == 0: tags.append("odd") | |
| verdict = "%s — %s" % (QMETA[r["q"]][0], r.get("qreason", "")) | |
| self.tree.insert("", "end", tags=tuple(tags), values=( | |
| i, r["raw"], r["type"], r["ip"], "%s %s" % (r["cc"], r["country"]), | |
| r["isp"], r["iptype"], r["ms"], verdict)) | |
| # ── pump ── | |
| def _pump(self): | |
| try: | |
| while True: | |
| k, d = self.q.get_nowait() | |
| if k == "status": self.v_status.set(d) | |
| elif k == "found": | |
| if d == 0: | |
| self.v_status.set("⚠ Không tải được proxy từ internet — VPS chặn mạng ra / lỗi SSL.") | |
| messagebox.showwarning("Không gom được proxy", | |
| "Không tải được danh sách proxy từ các nguồn trên internet.\n\n" | |
| "Thường do VPS CHẶN KẾT NỐI RA (firewall) hoặc lỗi mạng/SSL.\n" | |
| "Kiểm tra VPS có vào internet được không.") | |
| else: | |
| self.v_status.set("Đã gom %d proxy (dedup). Đang kiểm tra…" % d) | |
| elif k == "begin": | |
| self.pb["maximum"] = d; self.pb["value"] = 0; self._checked = d | |
| self._alive = self._cnt = 0; self._by = {"http": 0, "socks5": 0, "socks4": 0} | |
| elif k == "row": | |
| self._row(*d) | |
| elif k == "done": | |
| self._set_busy(False); self._count(final=True) | |
| if getattr(self, "_checked", 0) > 0 and not self.rows: | |
| messagebox.showwarning("0 proxy sống", | |
| "Đã gom %d proxy nhưng KHÔNG con nào sống.\n\n" | |
| "Thường do VPS CHẶN KẾT NỐI RA (outbound firewall) tới proxy, " | |
| "hoặc proxy free đều chết lúc này.\n" | |
| "Thử bấm lại, hoặc kiểm tra firewall outbound của VPS." % self._checked) | |
| except queue.Empty: | |
| pass | |
| self.root.after(80, self._pump) | |
| def _row(self, idx, r): | |
| self.pb["value"] = idx | |
| if r.get("ok"): | |
| self.rows.append(r); self._alive += 1 | |
| if self._passes(r): | |
| self._cnt += 1; self._insert(self._cnt, r) | |
| if idx % 13 == 0: | |
| q = {"rattot": 0, "tot": 0, "tb": 0, "kem": 0} | |
| for x in self.rows: q[x["q"]] = q.get(x["q"], 0) + 1 | |
| self.v_status.set("Đang quét %d/%d · sống %d ★%d ●%d ▲%d ✗%d" | |
| % (idx, int(self.pb["maximum"]), self._alive, | |
| q["rattot"], q["tot"], q["tb"], q["kem"])) | |
| def _count(self, final=False): | |
| by = {"http": 0, "socks5": 0, "socks4": 0}; q = {"rattot": 0, "tot": 0, "tb": 0, "kem": 0} | |
| for r in self.rows: | |
| by[r["type"]] = by.get(r["type"], 0) + 1; q[r["q"]] = q.get(r["q"], 0) + 1 | |
| tag = "✔ Xong" if final else "Hiện" | |
| self.v_status.set("%s · Sống %d → ★Rất tốt %d · ●Tốt %d · ▲TB %d · ✗Kém %d | " | |
| "HTTP %d · S5 %d · S4 %d (xem: %s / %s)" | |
| % (tag, len(self.rows), q["rattot"], q["tot"], q["tb"], q["kem"], | |
| by["http"], by["socks5"], by["socks4"], | |
| self.v_filter.get(), self.v_qual.get())) | |
| def main(): | |
| if not HAVE_TK: | |
| print("Khong co tkinter. Cai Python python.org (co tkinter) de mo GUI."); return | |
| root = tk.Tk(); App(root); root.mainloop() | |
| if __name__ == "__main__": | |
| main() | |