This commit is contained in:
upload
2026-11-29 12:57:13 +08:00
commit 99014efb55
5 changed files with 543 additions and 0 deletions
+328
View File
@@ -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()