File size: 10,596 Bytes
d715364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d919696
 
d715364
 
d919696
 
d715364
 
 
 
 
 
d919696
 
 
 
 
 
 
 
 
 
 
 
 
d715364
 
d919696
 
 
 
d715364
 
 
 
 
 
 
d919696
d715364
 
 
 
 
d919696
d715364
 
 
d919696
d715364
d919696
d715364
d919696
d715364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d919696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d715364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AdFoc.us 自动化 Worker - WARP 矩阵版
功能:
- 集成 WARP 隧道代理 (SOCKS5 @ 40000)
- 自动 IP 轮转
- 真人行为模拟
- 收益统计
"""

import asyncio
import json
import logging
import random
import sys
import os
import time
from datetime import datetime
from typing import Optional, List, Tuple
from collections import deque
import socket

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - [ADFOC-WORKER] - %(message)s',
    handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)

# ==================== 配置 ====================
ADFOC_URL = "http://adfoc.us/874953112736856"
REVENUE_RATES = {'us': 19.25, 'default': 5.00}
DEFAULT_COUNTRY = 'us'

# WARP 配置
WARP_PROXY = "socks5://127.0.0.1:40000"

# ==================== 浏览器指纹 ====================
class BrowserFingerprint:
    """浏览器指纹生成器"""
    USER_AGENTS = [
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    ]
    RESOLUTIONS = [{'width': 1920, 'height': 1080}, {'width': 1366, 'height': 768}]
    
    @classmethod
    def generate(cls):
        return {
            'user_agent': random.choice(cls.USER_AGENTS),
            'viewport': random.choice(cls.RESOLUTIONS),
            'timezone': 'America/New_York',
            'languages': ['en-US', 'en'],
            'hardware_concurrency': random.choice([4, 8]),
            'device_memory': random.choice([4, 8]),
        }

# ==================== 反检测脚本 ====================
class StealthMode:
    @staticmethod
    def get_stealth_script(fp):
        return f"""
        Object.defineProperty(navigator, 'webdriver', {{ get: () => undefined }});
        Object.defineProperty(navigator, 'plugins', {{
            get: () => [
                {{ name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer' }},
                {{ name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai' }},
            ]
        }});
        window.chrome = {{ runtime: {{}}, loadTimes: function() {{}}, csi: function() {{}} }};
        Object.defineProperty(navigator, 'hardwareConcurrency', {{ get: () => {fp['hardware_concurrency']} }});
        Object.defineProperty(navigator, 'deviceMemory', {{ get: () => {fp['device_memory']} }});
        """

# ==================== 自动化核心 ====================
class AdFocAutomation:
    def __init__(self):
        self.fingerprint = BrowserFingerprint.generate()
        self.browser = None
        self.pw = None
        self.consecutive_errors = 0
    
    async def start(self):
        """启动浏览器"""
        from playwright.async_api import async_playwright
        self.pw = await async_playwright().start()
        
        launch_args = [
            '--disable-blink-features=AutomationControlled',
            '--no-sandbox',
            '--disable-infobars',
            '--disable-dev-shm-usage',
        ]
        
        self.browser = await self.pw.chromium.launch(
            headless=True,
            args=launch_args
        )
        logger.info("✅ 浏览器启动成功")
    
    async def _check_port(self, port):
        """检查本地端口是否开放"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex(('127.0.0.1', port))
            sock.close()
            return result == 0
        except:
            return False

    async def run_single(self, url: str) -> bool:
        """运行单次访问 (支持多级代理回退)"""
        
        # 定义代理策略链
        # 优先使用 WARP (高速, 住宅IP) -> 其次 Tor (无限IP, 慢速) -> 最后直连 (保底)
        proxy_strategies = []
        
        if await self._check_port(40000):
            proxy_strategies.append({'server': 'socks5://127.0.0.1:40000', 'name': 'WARP'})
            
        if await self._check_port(9050):
            proxy_strategies.append({'server': 'socks5://127.0.0.1:9050', 'name': 'Tor'})
            
        proxy_strategies.append({'server': None, 'name': 'Direct'})

        # 定义内部函数以支持重试
        async def attempt_visit(proxy_conf):
            proxy_settings = {'server': proxy_conf['server']} if proxy_conf['server'] else None
            proxy_name = proxy_conf['name']
            
            ctx = None
            try:
                ctx = await self.browser.new_context(
                    viewport=self.fingerprint['viewport'],
                    user_agent=self.fingerprint['user_agent'],
                    locale='en-US',
                    timezone_id='America/New_York',
                    proxy=proxy_settings
                )
                
                page = await ctx.new_page()
                await page.add_init_script(StealthMode.get_stealth_script(self.fingerprint))
                
                # 1. 验证 IP
                try:
                    await page.goto("https://ifconfig.me", timeout=15000)
                    ip = await page.inner_text("body")
                    logger.info(f"🌐 当前 IP ({proxy_name}): {ip}")
                except Exception as e:
                    logger.warning(f"⚠️ 无法获取当前 IP ({proxy_name}): {str(e)[:100]}")
                    # 如果是代理连接失败,抛出以便外层捕获
                    if proxy_settings and ("ERR_SOCKS_CONNECTION_FAILED" in str(e) or "ERR_CONNECTION_RESET" in str(e)):
                        raise e
                
                # 2. 访问目标
                logger.info(f"📍 访问 AdFoc: {url}")
                await page.goto(url, wait_until="domcontentloaded", timeout=30000)
                
                # 3. 寻找 Skip 按钮
                try:
                    # 等待 6-8 秒
                    await asyncio.sleep(random.uniform(6.5, 8.5))
                    
                    # 检查 Skip 按钮
                    skip_btn = await page.wait_for_selector('a.skip', timeout=10000)
                    if skip_btn:
                        logger.info("✅ 找到 Skip 按钮,准备点击...")
                        
                        # 模拟鼠标移动
                        box = await skip_btn.bounding_box()
                        if box:
                            await page.mouse.move(box['x'] + 5, box['y'] + 5)
                            await asyncio.sleep(0.5)
                            await page.mouse.click(box['x'] + 5, box['y'] + 5)
                            logger.info("🖱️ 已点击 Skip")
                            
                            # 等待跳转
                            await asyncio.sleep(5)
                            return True
                except Exception as e:
                    logger.warning(f"⚠️ 未找到按钮或超时: {str(e)[:100]}")
                    
                return False
                
            finally:
                if ctx:
                    await ctx.close()

        # 遍历策略链尝试
        for strategy in proxy_strategies:
            try:
                if strategy['name'] != 'Direct':
                    logger.info(f"🔄 尝试使用 {strategy['name']} 代理...")
                else:
                    logger.info("⚠️ 切换至直连模式 (Direct)...")
                    
                success = await attempt_visit(strategy)
                if success:
                    return True
                # 如果没成功但没抛异常,可能是没找到按钮,算作本次尝试失败,不强制切换代理(或者可以强制切换?)
                # 这里我们假设没找到按钮也可能是IP问题,所以继续尝试下一个代理? 
                # 不,Playwright 没抛错意味着网络通了。没找到按钮可能是页面逻辑问题。
                # 但为了最大化收益,我们可以试试下一个IP(即下一个代理)
                logger.info(f"⚠️ {strategy['name']} 模式下未完成任务,尝试下一策略...")
                
            except Exception as e:
                logger.error(f"❌ {strategy['name']} 代理失败: {str(e)[:100]}")
                # 继续下一个策略
                continue
                
        self.consecutive_errors += 1
        return False

    async def run_loop(self, url: str):
        """循环运行"""
        count = 0
        while True:
            count += 1
            logger.info(f"\n🔄 第 {count} 次尝试")
            
            # 如果连续错误过多,尝试触发 IP 轮转 (通过重启 warp_manager)
            if self.consecutive_errors >= 5:
                logger.warning("⚠️ 连续失败过多,请求更换 IP...")
                # 这里可以通过写文件或其他方式通知 warp_manager
                # os.system("pkill -f wireproxy")
                self.consecutive_errors = 0
                await asyncio.sleep(10)
            
            success = await self.run_single(url)
            
            if success:
                self.consecutive_errors = 0
                logger.info("✨ 任务完成,收益 +1")
            
            # 随机休眠
            sleep_time = random.uniform(10, 20)
            logger.info(f"😴 休眠 {sleep_time:.1f} 秒...")
            await asyncio.sleep(sleep_time)

    async def stop(self):
        if self.browser:
            await self.browser.close()
        if self.pw:
            await self.pw.stop()

async def main():
    logger.info("🔥 AdFoc Worker (WARP版) 启动...")
    
    # 等待 WARP 启动
    logger.info("⏳ 等待 WARP 服务就绪...")
    for _ in range(30):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            if sock.connect_ex(('127.0.0.1', 40000)) == 0:
                logger.info("✅ WARP 服务已连接")
                break
            sock.close()
        except:
            pass
        await asyncio.sleep(2)
    
    bot = AdFocAutomation()
    await bot.start()
    try:
        await bot.run_loop(ADFOC_URL)
    finally:
        await bot.stop()

if __name__ == "__main__":
    asyncio.run(main())