commit 99014efb55afedb5fdec41b0375a3bbe30a892b5 Author: upload Date: Sun Nov 29 12:57:13 2026 +0800 upload diff --git a/__pycache__/亦优新代理自选地区调换.cpython-314.pyc b/__pycache__/亦优新代理自选地区调换.cpython-314.pyc new file mode 100644 index 0000000..f9100ca Binary files /dev/null and b/__pycache__/亦优新代理自选地区调换.cpython-314.pyc differ diff --git a/__pycache__/代理列表请求.cpython-310.pyc b/__pycache__/代理列表请求.cpython-310.pyc new file mode 100644 index 0000000..1c2d039 Binary files /dev/null and b/__pycache__/代理列表请求.cpython-310.pyc differ diff --git a/__pycache__/代理列表请求.cpython-314.pyc b/__pycache__/代理列表请求.cpython-314.pyc new file mode 100644 index 0000000..3608c75 Binary files /dev/null and b/__pycache__/代理列表请求.cpython-314.pyc differ diff --git a/亦优新代理自选地区调换.py b/亦优新代理自选地区调换.py new file mode 100644 index 0000000..fa20017 --- /dev/null +++ b/亦优新代理自选地区调换.py @@ -0,0 +1,328 @@ +# -*- coding: utf-8 -*- +"""亦优自选地区调换。改下面参数后直接运行,不用打开网页。 +登录沿用同目录 代理列表请求.py。 +只调未过期、已开通的节点。套餐类型要一致。 +新长效(combo_type 3/8)不传 business_id,地区 id 用库存接口返回的 id。 +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import requests + +# ==================== 运行参数(改这里) ==================== +IP = '' +ACCOUNT = '' +FROM_CITY = '北京' +NODE_IDS = [] +TO_CITY = '北京' +TAKE = 1 +DO_SWAP = True # True 才真正提交调换 +# ============================================================ + +ACCOUNT_MODE = 'keep_original' + + +def _list_mod(): + path = Path(__file__).resolve().with_name('代理列表请求.py') + spec = importlib.util.spec_from_file_location('yiyou_list', path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _headers(mod, token: str) -> dict: + return { + 'accept': '*/*', + 'authorization': f'Bearer {token}', + 'content-type': 'application/json', + 'origin': 'https://www.yiyouip.com', + 'referer': 'https://www.yiyouip.com/', + 'unique-id': mod.UNIQUE_ID, + } + + +def _city_key(name: str) -> str: + return str(name or '').replace('市', '').replace('省', '').strip() + + +def _same_city(name: str, keyword: str) -> bool: + a, b = _city_key(name), _city_key(keyword) + if not a or not b: + return False + return a == b or a in b or b in a + + +def load_nodes(mod, headers: dict) -> list: + url = f'{mod.API_BASE}/home/order/nodelist' + page = 1 + rows = [] + total = None + while True: + resp = requests.post(url, headers=headers, json={ + 'page': page, + 'page_size': 50, + 'order_field': 'id', + 'order_type': 'desc', + }, timeout=30) + data = resp.json() + if data.get('code') != 200: + raise RuntimeError(f"节点列表失败 code={data.get('code')} message={data.get('message')}") + result = data.get('result') or {} + batch = result.get('list') or [] + total = int(result.get('total') or 0) + rows.extend(batch) + if not batch or page * 50 >= total: + break + page += 1 + return rows + + +def _from_cities() -> list[str]: + text = str(FROM_CITY or '').replace(',', ',').replace('、', ',') + return [part.strip() for part in text.split(',') if part.strip()] + + +def _explicit_hit(row: dict, ids: set) -> bool: + if ids and int(row.get('id') or 0) in ids: + return True + if IP and str(row.get('apiip') or '').strip() == IP.strip(): + return True + if ACCOUNT and str(row.get('username') or '').strip() == ACCOUNT.strip(): + return True + return False + + +def _hit_node(row: dict, ids: set) -> bool: + if _explicit_hit(row, ids): + return True + return any(_same_city(row.get('area_name') or '', city) for city in _from_cities()) + + +def _node_line(row: dict) -> str: + return f"id={row.get('id')} {row.get('area_name')} {row.get('username')} {row.get('apiip')}:{row.get('apiport')}" + + +def limit_per_city(nodes: list) -> list: + """同一城市只留 TAKE 条。指定了节点 id、IP、账号的不裁。""" + if TAKE <= 0: + return nodes + ids = {int(x) for x in NODE_IDS} + kept_explicit = [] + groups: dict[str, list] = {} + for row in nodes: + if _explicit_hit(row, ids): + kept_explicit.append(row) + continue + key = _city_key(row.get('area_name') or '') + groups.setdefault(key, []).append(row) + kept = list(kept_explicit) + for key, items in groups.items(): + items.sort(key=lambda row: int(row.get('id') or 0), reverse=True) + kept.extend(items[:TAKE]) + for row in items[TAKE:]: + print(f"[keep] {_node_line(row)} 同城已有 {TAKE} 条要换,这条留下") + return kept + + +def pick_nodes(rows: list) -> tuple[list, list]: + ids = {int(x) for x in NODE_IDS} + opened, expired = [], [] + for row in rows: + if not _hit_node(row, ids): + continue + if str(row.get('status_text') or '') == '已过期' or int(row.get('status') or 0) != 1: + expired.append(row) + continue + opened.append(row) + return opened, expired + + +def load_areas(mod, headers: dict, code: str) -> list: + resp = requests.post( + f'{mod.API_BASE}/home/business/goods', + headers=headers, + json={'code': code}, + timeout=30, + ) + data = resp.json() + if data.get('code') != 200: + raise RuntimeError(f"地区库存失败 code={data.get('code')} message={data.get('message')}") + result = data.get('result') or {} + return result.get('business_list') or [] + + +def pick_area(areas: list, city: str) -> dict: + key = _city_key(city) + exact = [] + fuzzy = [] + for item in areas: + name = str(item.get('name') or item.get('area_name') or '') + if _city_key(name) == key: + exact.append(item) + elif _same_city(name, city): + fuzzy.append(item) + hits = exact or fuzzy + if not hits: + raise RuntimeError(f'库存里没有 {city}') + hits.sort(key=lambda item: int(item.get('total') or item.get('stock') or 0), reverse=True) + area = hits[0] + stock = int(area.get('total') or area.get('stock') or 0) + if stock <= 0: + raise RuntimeError(f"{area.get('name')} 库存为 0") + return area + + +def swap_region(mod, headers: dict, nodes: list, area: dict) -> dict: + payload = { + 'ids': [int(node['id']) for node in nodes], + 'swap_mode': 'custom_region', + 'custom_regions': [{ + 'area_id': int(area['id']), + 'area_name': area.get('name') or area.get('area_name'), + 'qty': len(nodes), + }], + 'account_mode': ACCOUNT_MODE, + } + print('[swap]', payload) + if not DO_SWAP: + print('[swap] DO_SWAP=False,未提交') + return payload + resp = requests.post( + f'{mod.API_BASE}/home/order/swapBatch', + headers=headers, + json=payload, + timeout=30, + ) + data = resp.json() + print('[swap]', data.get('code'), data.get('message')) + if data.get('code') != 200: + raise RuntimeError(f"调换失败 code={data.get('code')} message={data.get('message')}") + return data + + +def _nodes_by_id(mod, headers: dict, ids: list[int]) -> dict[int, dict]: + wanted = set(ids) + found = {} + for row in load_nodes(mod, headers): + node_id = int(row.get('id') or 0) + if node_id in wanted: + found[node_id] = row + if len(found) == len(wanted): + break + return found + + +def write_db(mod, before: list, after: dict[int, dict]): + """用调换前的 ip+端口定位原行,改成调换后的城市和代理。""" + import pymysql + + conn = pymysql.connect( + host=mod.DB_HOST, + port=mod.DB_PORT, + user=mod.DB_USER, + password=mod.DB_PWD, + database=mod.DB_NAME, + charset='utf8mb4', + connect_timeout=10, + ) + updated = inserted = 0 + try: + cur = conn.cursor() + for old in before: + node_id = int(old['id']) + new = after.get(node_id) + if not new: + print(f'[db] id={node_id} 调换后没查到,跳过') + continue + payload = mod._row_payload(new) + old_ip = str(old.get('apiip') or '').strip() + old_port = str(old.get('apiport') or '').strip() + cur.execute( + ''' + SELECT `index` FROM proxs_list + WHERE REPLACE(REPLACE(ip_address, '\t', ''), ' ', '')=%s + AND REPLACE(REPLACE(port, '\t', ''), ' ', '')=%s + ORDER BY `index` + ''', + (old_ip, old_port), + ) + hits = [row[0] for row in cur.fetchall()] + if hits: + for index in hits: + mod._write_row(cur, index, payload) + updated += len(hits) + else: + cur.execute( + ''' + INSERT INTO proxs_list + (city, prox_data, ip_address, port, acount, pwd, dll, channel) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + ''', + payload, + ) + inserted += 1 + print( + f"[db] id={node_id} {old.get('area_name')} -> {payload[0]} " + f"{old_ip}:{old_port} -> {payload[2]}:{payload[3]}" + ) + conn.commit() + print(f'[db] project_proxy.proxs_list 更新 {updated} 行,新增 {inserted} 行') + finally: + conn.close() + + +def main(): + if not any([IP.strip(), ACCOUNT.strip(), FROM_CITY.strip(), NODE_IDS]): + print('请填写 IP / ACCOUNT / FROM_CITY / NODE_IDS 里至少一项,以及 TO_CITY') + return + mod = _list_mod() + token = mod.login_token() + headers = _headers(mod, token) + nodes, expired = pick_nodes(load_nodes(mod, headers)) + if expired: + print(f'已过期 {len(expired)} 条,网站不允许调换') + for row in expired[:8]: + print( + f" id={row.get('id')} {row.get('area_name')} {row.get('status_text')} " + f"{row.get('apiip')}:{row.get('apiport')}" + ) + if len(expired) > 8: + print(f' ... 还有 {len(expired) - 8} 条') + if not nodes: + print('没有已开通的节点可调。请改成一条状态是已开通的 IP、账号或城市') + return + candidates = [] + for node in nodes: + if _same_city(node.get('area_name') or '', TO_CITY): + print(f"[skip] {_node_line(node)} 已是{TO_CITY}") + continue + candidates.append(node) + candidates = limit_per_city(candidates) + if not candidates: + print('没有需要调换的节点') + return + codes = {str(node.get('code') or '') for node in candidates} + combos = {int(node.get('combo_type') or 0) for node in candidates} + if len(codes) != 1 or len(combos) != 1: + print(f'命中的节点套餐不一致 code={codes} combo={combos},请分开调') + return + todo = [] + for node in candidates: + print(f"[hit] {_node_line(node)} -> {TO_CITY}") + todo.append(node) + if not todo: + print('没有需要调换的节点') + return + area = pick_area(load_areas(mod, headers, next(iter(codes))), TO_CITY) + print(f"[area] id={area.get('id')} name={area.get('name')} stock={area.get('total')}") + swap_region(mod, headers, todo, area) + if not DO_SWAP: + return + after = _nodes_by_id(mod, headers, [int(node['id']) for node in todo]) + write_db(mod, todo, after) + + +if __name__ == '__main__': + main() diff --git a/代理列表请求.py b/代理列表请求.py new file mode 100644 index 0000000..3c33439 --- /dev/null +++ b/代理列表请求.py @@ -0,0 +1,215 @@ +import json +import re +from datetime import datetime +import pymysql +import requests + +# ==================== 运行参数(改这里) ==================== +DB_HOST = '192.168.5.5' +DB_PORT = 3306 +DB_NAME = 'project_proxy' +DB_USER = 'root' +DB_PWD = 'Aliyun@7646!' +API_BASE = 'https://backendapi.quansuip.com/api' +MOBILE = '18027147646' +PASSWORD = 'ader123' +UNIQUE_ID = 'bpwgjeak' +# ============================================================ + + +def login_token() -> str: + """账号密码登录,拿 result.token。过期不用手改 Bearer。""" + resp = requests.post( + f'{API_BASE}/home/account/login', + headers={'Content-Type': 'application/json', 'Unique-Id': UNIQUE_ID}, + json={'mobile': MOBILE, 'password': PASSWORD, 'auto_login': 1}, + timeout=30, + ) + data = resp.json() + token = '' + if isinstance(data.get('result'), dict): + token = str(data['result'].get('token') or '').strip() + if data.get('code') != 200 or not token: + raise RuntimeError(f"登录失败 code={data.get('code')} message={data.get('message')}") + print(f'[login] {MOBILE} 已换 token') + return token + + +def get_req(): + token = login_token() + headers = { + "accept": "*/*", + "accept-language": "zh-CN,zh;q=0.9", + "authorization": f"Bearer {token}", + "content-type": "application/json", + "origin": "https://www.yiyouip.com", + "priority": "u=1, i", + "referer": "https://www.yiyouip.com/", + "sec-ch-ua": "\"Not-A.Brand\";v=\"99\", \"Google Chrome\";v=\"157\", \"Chromium\";v=\"157\"", + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": "\"Windows\"", + "sec-fetch-dest": "empty", + "sec-fetch-mode": "cors", + "sec-fetch-site": "cross-site", + "unique-id": UNIQUE_ID, + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Safari/537.36" + } + url = f'{API_BASE}/home/order/nodelist' + data = { + "page": 1, + "page_size": 50, + "order_field": "id", + "order_type": "desc" + } + response = requests.post(url, headers=headers, json=data) + + print(response.text) + print(response) + return response.json() + + +def clean_city(area_name: str) -> str: + name = (area_name or '').strip() + if '|' in name: + name = name.split('|')[-1].strip() + name = re.sub(r'【[^】]*】', '', name) + name = re.sub(r'\d+.*$', '', name).strip() + return name + + +def ts_date(ts) -> str: + return datetime.fromtimestamp(int(ts)).strftime('%Y-%m-%d') + + +def prox_json(user: str, pwd: str, ip: str, port: str) -> str: + url = f'http://{user}:{pwd}@{ip}:{port}' + return json.dumps({'http': url, 'https': url}, ensure_ascii=False) + + +def _row_payload(item: dict) -> tuple: + ip = str(item['apiip']).strip() + port = str(item['apiport']).strip() + user = str(item['username']) + pwd = str(item['password']) + return ( + clean_city(item.get('area_name') or ''), + prox_json(user, pwd, ip, port), + ip, + port, + user, + pwd, + ts_date(item['created_at']), + ts_date(item['end_at']), + ) + + +def _write_row(cur, index: int, payload: tuple): + cur.execute( + ''' + UPDATE proxs_list + SET city=%s, prox_data=%s, ip_address=%s, port=%s, + acount=%s, pwd=%s, dll=%s, channel=%s + WHERE `index`=%s + ''', + (*payload, index), + ) + + +def _read_row(cur, index: int) -> tuple: + cur.execute( + ''' + SELECT city, CAST(prox_data AS CHAR), ip_address, port, acount, pwd, dll, channel + FROM proxs_list WHERE `index`=%s + ''', + (index,), + ) + row = cur.fetchone() + prox = row[1] + if isinstance(prox, (bytes, bytearray)): + prox = prox.decode('utf-8') + return (row[0], prox, str(row[2]).strip(), str(row[3]).strip(), row[4], row[5], row[6], row[7]) + + +def sync_proxs(items: list): + """按 ip+端口更新;没有则插入。同城多条时,已开通的代理放到最大 index,查找时不会被过期条盖住。""" + conn = pymysql.connect( + host=DB_HOST, + port=DB_PORT, + user=DB_USER, + password=DB_PWD, + database=DB_NAME, + charset='utf8mb4', + connect_timeout=10, + ) + updated = inserted = 0 + try: + cur = conn.cursor() + for item in items: + payload = _row_payload(item) + ip, port = payload[2], payload[3] + cur.execute( + ''' + SELECT `index` FROM proxs_list + WHERE REPLACE(REPLACE(ip_address, '\t', ''), ' ', '')=%s + AND REPLACE(REPLACE(port, '\t', ''), ' ', '')=%s + ORDER BY `index` + ''', + (ip, port), + ) + hits = [r[0] for r in cur.fetchall()] + if hits: + for index in hits: + _write_row(cur, index, payload) + updated += len(hits) + else: + cur.execute( + ''' + INSERT INTO proxs_list + (city, prox_data, ip_address, port, acount, pwd, dll, channel) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + ''', + payload, + ) + inserted += 1 + # 同城:已开通换到最大 index(列表靠前的后处理,最新一条留在最后) + opened = [i for i in items if i.get('status_text') != '已过期'] + for item in reversed(opened): + payload = _row_payload(item) + city, ip, port = payload[0], payload[2], payload[3] + cur.execute( + 'SELECT `index` FROM proxs_list WHERE city=%s ORDER BY `index` DESC LIMIT 1', + (city,), + ) + top = cur.fetchone() + cur.execute( + ''' + SELECT `index` FROM proxs_list + WHERE REPLACE(REPLACE(ip_address, '\t', ''), ' ', '')=%s + AND REPLACE(REPLACE(port, '\t', ''), ' ', '')=%s + ORDER BY `index` LIMIT 1 + ''', + (ip, port), + ) + own = cur.fetchone() + if not top or not own or top[0] == own[0]: + continue + top_payload = _read_row(cur, top[0]) + _write_row(cur, top[0], payload) + _write_row(cur, own[0], top_payload) + conn.commit() + print(f'[db] project_proxy.proxs_list 命中更新 {updated} 行,新增 {inserted} 行,列表 {len(items)} 条') + finally: + conn.close() + + +def want_prox(item: dict) -> bool: + if item.get('status_text') == '已过期': + return False + return item.get('combo_type_text') == '新长效住宅(定制)' + + +if __name__ == '__main__': + json_tk = get_req() + picked = [i for i in json_tk['result']['list'] if want_prox(i)] + print(f'[db] 未过期且新长效住宅(定制) {len(picked)} 条') + sync_proxs(picked) \ No newline at end of file