Spaces:
Runtime error
Runtime error
File size: 2,189 Bytes
4327358 |
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 |
import { Agent } from 'https';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { URL } from 'url';
import { WhatsappConfigService } from '../config.service';
import { ProxyConfig } from '../structures/sessions.dto';
import { WhatsappSession } from './abc/session.abc';
export function getProxyConfig(
config: WhatsappConfigService,
sessions: Record<string, WhatsappSession>,
sessionName: string,
): ProxyConfig | undefined {
// Single proxy server configuration
if (typeof config.proxyServer === 'string') {
return {
server: config.proxyServer,
username: config.proxyServerUsername,
password: config.proxyServerPassword,
};
}
// Multiple proxy server configuration
if (Array.isArray(config.proxyServer)) {
const prefix = config.proxyServerIndexPrefix;
let indexToUse: number | undefined = undefined;
if (prefix && sessionName.includes(prefix)) {
// match numbers at the end of the string
const matches = sessionName.match(/\d+$/);
indexToUse = matches ? parseInt(matches[0], 10) : undefined;
}
let idx = 0;
idx = Object.keys(sessions).length % config.proxyServer.length;
const index = indexToUse ? indexToUse % config.proxyServer.length : idx;
return {
server: config.proxyServer[index],
username: config.proxyServerUsername,
password: config.proxyServerPassword,
};
}
// No proxy server configuration
return undefined;
}
function getAuthenticatedUrl(
url: string,
username: string,
password: string,
): string {
const hasSchema = url.startsWith('http://') || url.startsWith('https://');
if (!hasSchema) {
url = `http://${url}`;
}
const parsedUrl = new URL(url);
parsedUrl.protocol = parsedUrl.protocol || 'http';
parsedUrl.username = username;
parsedUrl.password = password;
return parsedUrl.toString();
}
/**
* Return https Agent proxy for the config
* @param proxyConfig
*/
export function createAgentProxy(proxyConfig: ProxyConfig): Agent | undefined {
const url = getAuthenticatedUrl(
proxyConfig.server,
proxyConfig.username || '',
proxyConfig.password || '',
);
return new HttpsProxyAgent(url);
}
|