118 lines
2.8 KiB
TypeScript
118 lines
2.8 KiB
TypeScript
import { decode, encode } from 'js-base64'
|
|
import { getdata } from 'src/api/api';
|
|
import { VlessLink, vmess } from 'src/models/models';
|
|
import { is_ip } from './comm';
|
|
import { vmessDefault } from 'src/config';
|
|
|
|
/**
|
|
* 创建直连vmess
|
|
* @param ip 服务器IP地址
|
|
* @returns vmess链接
|
|
*/
|
|
async function CreatVmessDirect(ip: string): Promise<string> {
|
|
let tmp = ''
|
|
const api = new getdata;
|
|
const obj = JSON.parse(decode(vmessDefault))
|
|
const array = ip.split(/[\s\n]/)
|
|
for (let index = 0; index < array.length; index++) {
|
|
if (!is_ip(array[index])) {
|
|
return ''
|
|
}
|
|
|
|
for (let index = 0; index < array.length; index++) {
|
|
const name = await api.get_country(array[index])
|
|
obj.ps = name + array[index]
|
|
obj.add = array[index]
|
|
tmp += 'vmess://' + encode(JSON.stringify(obj)) + '\n'
|
|
}
|
|
|
|
}
|
|
return tmp
|
|
}
|
|
|
|
function ChangVmessServer() {
|
|
return 0
|
|
}
|
|
/**
|
|
*
|
|
* @param type 生成链接的类型 vmess |vless
|
|
*/
|
|
function CreateLink(type: 'vmess' | 'vless', linkinfo: vmess | VlessLink) {
|
|
let tmp = ''
|
|
switch (true) {
|
|
case type === 'vless':
|
|
if ('uuid' in linkinfo) {
|
|
tmp = createVlessLink(linkinfo)
|
|
}
|
|
break;
|
|
case type === 'vmess':
|
|
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
return tmp
|
|
}
|
|
|
|
function parseVlessLink(link: string): VlessLink | null {
|
|
const regex = /^vless:/;
|
|
const match = link.match(regex);
|
|
|
|
if (!match) {
|
|
console.error('Invalid VLESS link format.');
|
|
return null;
|
|
}
|
|
|
|
const uuid = match[1];
|
|
const host = match[2];
|
|
const port = parseInt(match[3], 10);
|
|
const params = parseParams(match[4]); // 解析参数
|
|
const name = match[5] ? decodeURIComponent(match[5].slice(1)) : undefined; // 去掉 "#" 并解码
|
|
|
|
return {
|
|
uuid,
|
|
host,
|
|
port,
|
|
params,
|
|
name,
|
|
};
|
|
}
|
|
|
|
function parseParams(paramsString?: string): Record<string, string> | undefined {
|
|
if (!paramsString || !paramsString.startsWith('?')) return undefined;
|
|
|
|
return paramsString
|
|
.slice(1) // 去掉开头的 "?"
|
|
.split('&') // 分割每个键值对
|
|
.reduce<Record<string, string>>((acc, pair) => {
|
|
const [key, value] = pair.split('=');
|
|
if (key) acc[key] = value || ''; // 处理可能的无值参数
|
|
return acc;
|
|
}, {});
|
|
}
|
|
|
|
/**
|
|
* 创建vless链接
|
|
* @param param0
|
|
* @returns
|
|
*/
|
|
function createVlessLink({ uuid, host, port, params, name }: VlessLink): string {
|
|
// 基本的 VLESS 链接格式
|
|
let link = `vless://${uuid}@${host}:${port}\n`;
|
|
|
|
// 如果有查询参数,则拼接它们
|
|
if (params && Object.keys(params).length > 0) {
|
|
const queryString = new URLSearchParams(params).toString();
|
|
link += `?${queryString}`;
|
|
}
|
|
|
|
// 如果有名称字段,将名称放在 # 后面
|
|
if (name) {
|
|
link += `#${encodeURIComponent(name)}`;
|
|
}
|
|
|
|
return link;
|
|
}
|
|
|
|
export { CreatVmessDirect, ChangVmessServer, CreateLink, parseVlessLink }
|