Browse Source

调整验证函数

torsen
453530270@qq.com 1 year ago
parent
commit
73a7b393e5
  1. 171
      douyin/background.js

171
douyin/background.js

@ -8,13 +8,13 @@ chrome.runtime.onInstalled.addListener(() => {
async function checkProxyAvailability(proxyConfig) { async function checkProxyAvailability(proxyConfig) {
return new Promise((resolve) => { return new Promise((resolve) => {
const timeoutDuration = 10000; // 增加超时时间到10秒 const timeoutDuration = 10000; // 增加超时时间到10秒
console.log(`正在测试代理 ${proxyConfig.host}:${proxyConfig.port} 的可用性...`); console.log(`正在测试代理 ${proxyConfig.host}:${proxyConfig.port} 的可用性...`);
// 使用 XMLHttpRequest 来测试代理 // 使用 XMLHttpRequest 来测试代理
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.timeout = timeoutDuration; xhr.timeout = timeoutDuration;
// 设置超时处理 // 设置超时处理
const timeoutHandler = setTimeout(() => { const timeoutHandler = setTimeout(() => {
xhr.abort(); xhr.abort();
@ -22,7 +22,7 @@ async function checkProxyAvailability(proxyConfig) {
resolve(false); resolve(false);
}, timeoutDuration); }, timeoutDuration);
xhr.onreadystatechange = function() { xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { if (xhr.readyState === 4) {
clearTimeout(timeoutHandler); clearTimeout(timeoutHandler);
if (xhr.status === 200) { if (xhr.status === 200) {
@ -35,7 +35,7 @@ async function checkProxyAvailability(proxyConfig) {
} }
}; };
xhr.onerror = function() { xhr.onerror = function () {
clearTimeout(timeoutHandler); clearTimeout(timeoutHandler);
console.log(`代理 ${proxyConfig.host}:${proxyConfig.port} 连接错误`); console.log(`代理 ${proxyConfig.host}:${proxyConfig.port} 连接错误`);
resolve(false); resolve(false);
@ -68,11 +68,13 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
windowProxyMap.set(windowId, proxyConfig); windowProxyMap.set(windowId, proxyConfig);
// 设置认证监听器 // 设置认证监听器
const authHandler = function(details) { const authHandler = function (details) {
console.log("=========PROXY CONFIG===========",proxyConfig)
return { return {
authCredentials: { authCredentials: {
username: proxyConfig.username, username: "hwfq28m43",
password: proxyConfig.password password: "YW29ABi6"
} }
}; };
}; };
@ -80,11 +82,17 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
// 移除之前的监听器(如果存在) // 移除之前的监听器(如果存在)
try { try {
chrome.webRequest.onAuthRequired.removeListener(authHandler); chrome.webRequest.onAuthRequired.removeListener(authHandler);
} catch (e) {} } catch (e) { }
// 添加新的监听器 // 添加新的监听器
chrome.webRequest.onAuthRequired.addListener( chrome.webRequest.onAuthRequired.addListener(
authHandler, // authHandler,
function(details,callbackFn){
console.log("onAuthRequired!", details, callbackFn);
callbackFn({
authCredentials: {username: "hwfq28m43", password: "YW29ABi6"}
});
},
{ urls: ["<all_urls>"] }, { urls: ["<all_urls>"] },
["asyncBlocking"] ["asyncBlocking"]
); );
@ -98,7 +106,16 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
scheme: "http", scheme: "http",
host: proxyConfig.host, host: proxyConfig.host,
port: parseInt(proxyConfig.port) port: parseInt(proxyConfig.port)
},
httpsProxy:{
// 添加 HTTPS 代理规则
scheme: "http",
host: proxyConfig.host,
port: parseInt(proxyConfig.port),
username: proxyConfig.username,
password: proxyConfig.password
} }
} }
}, },
scope: "regular" scope: "regular"
@ -107,7 +124,7 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
// 设置代理 // 设置代理
chrome.proxy.settings.set( chrome.proxy.settings.set(
config, config,
function() { function () {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
console.error('设置代理失败:', chrome.runtime.lastError); console.error('设置代理失败:', chrome.runtime.lastError);
callback(chrome.runtime.lastError); callback(chrome.runtime.lastError);
@ -115,17 +132,17 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
} }
console.log(`窗口 ${windowId} 代理设置成功`); console.log(`窗口 ${windowId} 代理设置成功`);
// 刷新标签页 // 刷新标签页
chrome.tabs.query({ windowId: windowId }, function(tabs) { chrome.tabs.query({ windowId: windowId }, function (tabs) {
if (tabs.length === 0) { if (tabs.length === 0) {
callback(null, true); callback(null, true);
return; return;
} }
let refreshedCount = 0; let refreshedCount = 0;
tabs.forEach(function(tab) { tabs.forEach(function (tab) {
chrome.tabs.reload(tab.id, { bypassCache: true }, function() { chrome.tabs.reload(tab.id, { bypassCache: true }, function () {
refreshedCount++; refreshedCount++;
if (refreshedCount === tabs.length) { if (refreshedCount === tabs.length) {
callback(null, true); callback(null, true);
@ -142,10 +159,10 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'checkIncognitoWindows') { if (request.action === 'checkIncognitoWindows') {
chrome.windows.getAll({ populate: true }, (windows) => { chrome.windows.getAll({ populate: true }, (windows) => {
console.log('获取到所有窗口数量:', windows.length); console.log('获取到所有窗口数量:', windows.length);
const incognitoWindows = windows.filter(w => w.incognito); const incognitoWindows = windows.filter(w => w.incognito);
console.log('找到无痕窗口数量:', incognitoWindows.length); console.log('找到无痕窗口数量:', incognitoWindows.length);
const windowDetails = incognitoWindows.map(w => ({ const windowDetails = incognitoWindows.map(w => ({
id: w.id, id: w.id,
type: w.type, type: w.type,
@ -153,9 +170,9 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
tabCount: w.tabs ? w.tabs.length : 0, tabCount: w.tabs ? w.tabs.length : 0,
firstTabUrl: w.tabs && w.tabs[0] ? w.tabs[0].url : 'no tabs' firstTabUrl: w.tabs && w.tabs[0] ? w.tabs[0].url : 'no tabs'
})); }));
console.log('无痕窗口详情:', windowDetails); console.log('无痕窗口详情:', windowDetails);
sendResponse({ sendResponse({
count: incognitoWindows.length, count: incognitoWindows.length,
windows: windowDetails, windows: windowDetails,
@ -170,14 +187,14 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
chrome.windows.create({ chrome.windows.create({
incognito: true, incognito: true,
url: "https://www.douyin.com" url: "https://www.douyin.com"
}, function(window) { }, function (window) {
console.log('抖音无痕窗口已打开'); console.log('抖音无痕窗口已打开');
}); });
} else if (request.action === 'openLiveIncognito') { } else if (request.action === 'openLiveIncognito') {
chrome.windows.create({ chrome.windows.create({
incognito: true, incognito: true,
url: request.url url: request.url
}, function(window) { }, function (window) {
console.log('直播无痕窗口已打开'); console.log('直播无痕窗口已打开');
}); });
} }
@ -195,34 +212,34 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
}, },
body: JSON.stringify(loginData) body: JSON.stringify(loginData)
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
console.log('登录结果:', data); console.log('登录结果:', data);
if (data.status === 200) { if (data.status === 200) {
sendResponse({ status: 'success' }); sendResponse({ status: 'success' });
chrome.storage.local.set({ loginStatus: true }); chrome.storage.local.set({ loginStatus: true });
chrome.storage.local.set({ loginInfo: loginData }); chrome.storage.local.set({ loginInfo: loginData });
chrome.storage.local.set({ loginTime: new Date().toLocaleString() }); chrome.storage.local.set({ loginTime: new Date().toLocaleString() });
chrome.storage.local.set({ loginToken: data.token }); chrome.storage.local.set({ loginToken: data.token });
chrome.cookies.set({ chrome.cookies.set({
url: 'https://douyin.xingtongworld.com', url: 'https://douyin.xingtongworld.com',
name: 'sessionid', name: 'sessionid',
value: data.token, value: data.token,
domain: 'douyin.xingtongworld.com' domain: 'douyin.xingtongworld.com'
}); });
} else { } else {
sendResponse({ status: 'error', message: '登录失败:' + (data.message || '未知错误') }); sendResponse({ status: 'error', message: '登录失败:' + (data.message || '未知错误') });
} }
}) })
.catch(error => { .catch(error => {
console.error('登录请求出错:', error); console.error('登录请求出错:', error);
sendResponse({ status: 'error', message: '登录请出错,请检查网络连接或稍后重试。' }); sendResponse({ status: 'error', message: '登录请出错,请检查网络连接或稍后重试。' });
}); });
} }
if (request.action === 'checkStatus') { if (request.action === 'checkStatus') {
let status = '正常'; let status = '正常';
sendResponse({status: status}); sendResponse({ status: status });
} }
if (request.action === 'openLiveWithProxy') { if (request.action === 'openLiveWithProxy') {
@ -264,8 +281,8 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('可用代理列表:', proxyList); console.log('可用代理列表:', proxyList);
if (proxyList.length === 0) { if (proxyList.length === 0) {
sendResponse({ sendResponse({
success: false, success: false,
error: '没有可用的代理' error: '没有可用的代理'
}); });
return; return;
@ -283,7 +300,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
} }
const window = incognitoWindows[currentIndex]; const window = incognitoWindows[currentIndex];
// 检查窗口是否已经有代理设置 // 检查窗口是否已经有代理设置
const existingProxy = windowProxyMap.get(window.id); const existingProxy = windowProxyMap.get(window.id);
if (existingProxy) { if (existingProxy) {
@ -301,7 +318,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// 使用循环方式获取代理配置 // 使用循环方式获取代理配置
const proxyIndex = currentIndex % proxyList.length; const proxyIndex = currentIndex % proxyList.length;
const proxy = proxyList[proxyIndex]; const proxy = proxyList[proxyIndex];
if (!proxy || !proxy.host || !proxy.port) { if (!proxy || !proxy.host || !proxy.port) {
errors.push(`代理配置无效: ${JSON.stringify(proxy)}`); errors.push(`代理配置无效: ${JSON.stringify(proxy)}`);
completedCount++; completedCount++;
@ -345,12 +362,12 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
function checkComplete() { function checkComplete() {
if (completedCount === incognitoWindows.length) { if (completedCount === incognitoWindows.length) {
if (errors.length > 0) { if (errors.length > 0) {
sendResponse({ sendResponse({
success: false, success: false,
error: errors.join('\n') error: errors.join('\n')
}); });
} else { } else {
sendResponse({ sendResponse({
success: true, success: true,
message: `已为 ${incognitoWindows.length} 个无痕窗口设置代理` message: `已为 ${incognitoWindows.length} 个无痕窗口设置代理`
}); });
@ -364,12 +381,13 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
return true; return true;
} }
// 清除代理信息
if (request.action === 'clearProxy') { if (request.action === 'clearProxy') {
try { try {
// 清除代理设置 // 清除代理设置
chrome.proxy.settings.clear( chrome.proxy.settings.clear(
{ scope: "regular" }, { scope: "regular" },
async function() { async function () {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
console.error('清除代理设置失败:', chrome.runtime.lastError); console.error('清除代理设置失败:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message }); sendResponse({ success: false, error: chrome.runtime.lastError.message });
@ -381,8 +399,8 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
try { try {
// 获取所有窗口 // 获取所有窗口
const windows = await new Promise((resolve) => { const windows = await new Promise((resolve) => {
chrome.windows.getAll({ chrome.windows.getAll({
populate: true populate: true
}, resolve); }, resolve);
}); });
@ -436,15 +454,15 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
} }
} }
sendResponse({ sendResponse({
success: true, success: true,
message: '已清除所有代理设置、认证缓存并刷新标签页' message: '已清除所有代理设置、认证缓存并刷新标签页'
}); });
} catch (error) { } catch (error) {
console.error('刷新标签页时出错:', error); console.error('刷新标签页时出错:', error);
sendResponse({ sendResponse({
success: false, success: false,
error: '清除代理成功但刷新标签页失败: ' + error.message error: '清除代理成功但刷新标签页失败: ' + error.message
}); });
} }
} }
@ -456,11 +474,12 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
return true; return true;
} }
// 当前代理
if (request.action === 'getCurrentProxy') { if (request.action === 'getCurrentProxy') {
try { try {
const windowId = request.windowId; const windowId = request.windowId;
const proxyConfig = windowProxyMap.get(windowId); const proxyConfig = windowProxyMap.get(windowId);
if (proxyConfig) { if (proxyConfig) {
sendResponse({ sendResponse({
success: true, success: true,
@ -488,13 +507,14 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
} }
chrome.webRequest.onCompleted.addListener( chrome.webRequest.onCompleted.addListener(
function(details) { function (details) {
console.log("请求完成:", details); console.log("请求完成:", details);
}, },
{urls: ["<all_urls>"]} { urls: ["<all_urls>"] }
); );
}); });
// 新窗口监听
chrome.windows.onCreated.addListener((window) => { chrome.windows.onCreated.addListener((window) => {
console.log('新窗口创:', { console.log('新窗口创:', {
id: window.id, id: window.id,
@ -507,6 +527,7 @@ chrome.windows.onCreated.addListener((window) => {
}); });
}); });
// 新标签监听
chrome.tabs.onCreated.addListener((tab) => { chrome.tabs.onCreated.addListener((tab) => {
console.log('新标签创建:', { console.log('新标签创建:', {
id: tab.id, id: tab.id,
@ -517,7 +538,7 @@ chrome.tabs.onCreated.addListener((tab) => {
// 修改错误监听器,添加更多需要忽略的误类型 // 修改错误监听器,添加更多需要忽略的误类型
chrome.webRequest.onErrorOccurred.addListener( chrome.webRequest.onErrorOccurred.addListener(
function(details) { function (details) {
// 扩展需要忽略的错误类型列表 // 扩展需要忽略的错误类型列表
const ignoredErrors = [ const ignoredErrors = [
'net::ERR_ABORTED', // 请求中断 'net::ERR_ABORTED', // 请求中断
@ -540,10 +561,10 @@ chrome.webRequest.onErrorOccurred.addListener(
'other' // 其他资源 'other' // 其他资源
]; ];
if (details.error && if (details.error &&
!ignoredErrors.includes(details.error) && !ignoredErrors.includes(details.error) &&
!ignoredResourceTypes.includes(details.type)) { !ignoredResourceTypes.includes(details.type)) {
// 只记录重要的错误 // 只记录重要的错误
const errorInfo = { const errorInfo = {
错误类型: details.error, 错误类型: details.error,
@ -554,26 +575,26 @@ chrome.webRequest.onErrorOccurred.addListener(
}; };
// 如果是代理相关错误,添加更多信息 // 如果是代理相关错误,添加更多信息
if (details.error.toLowerCase().includes('proxy') || if (details.error.toLowerCase().includes('proxy') ||
details.error.toLowerCase().includes('connection_refused')) { details.error.toLowerCase().includes('connection_refused')) {
errorInfo.代理错误 = true; errorInfo.代理错误 = true;
errorInfo.IP地址 = details.ip || '未知'; errorInfo.IP地址 = details.ip || '未知';
console.error('代理相关错误:\n' + console.error('代理相关错误:\n' +
Object.entries(errorInfo) Object.entries(errorInfo)
.map(([key, value]) => `${key}: ${value}`) .map(([key, value]) => `${key}: ${value}`)
.join('\n') .join('\n')
); );
} else if (details.error.toLowerCase().includes('cert')) { } else if (details.error.toLowerCase().includes('cert')) {
// 证书相关错误 // 证书相关错误
console.warn('证书相关错误:\n' + console.warn('证书相关错误:\n' +
Object.entries(errorInfo) Object.entries(errorInfo)
.map(([key, value]) => `${key}: ${value}`) .map(([key, value]) => `${key}: ${value}`)
.join('\n') .join('\n')
); );
} else { } else {
// 其他重要错误 // 其他重要错误
console.error('重要网络错误:\n' + console.error('重要网络错误:\n' +
Object.entries(errorInfo) Object.entries(errorInfo)
.map(([key, value]) => `${key}: ${value}`) .map(([key, value]) => `${key}: ${value}`)
.join('\n') .join('\n')
@ -581,7 +602,7 @@ chrome.webRequest.onErrorOccurred.addListener(
} }
} }
}, },
{urls: ["<all_urls>"]} { urls: ["<all_urls>"] }
); );
chrome.windows.onRemoved.addListener((windowId) => { chrome.windows.onRemoved.addListener((windowId) => {
@ -620,7 +641,7 @@ chrome.windows.onRemoved.addListener((windowId) => {
// 添加证书错误处理 // 添加证书错误处理
chrome.webRequest.onErrorOccurred.addListener( chrome.webRequest.onErrorOccurred.addListener(
function(details) { function (details) {
if (details.error && details.error.includes('ERR_CERT')) { if (details.error && details.error.includes('ERR_CERT')) {
console.log('忽略证书错误:', details.url); console.log('忽略证书错误:', details.url);
return { cancel: false }; return { cancel: false };

Loading…
Cancel
Save