NapCatQQ/src/common/system.ts

74 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-08-08 06:29:29 +00:00
import os from 'node:os';
import path from 'node:path';
import { networkInterfaces } from 'os';
import { randomUUID } from 'crypto';
// 缓解Win7设备兼容性问题
let osName: string;
// 设备ID
let machineId: Promise<string>;
try {
osName = os.hostname();
2024-08-08 06:29:29 +00:00
} catch (e) {
osName = 'NapCat'; // + crypto.randomUUID().substring(0, 4);
2024-08-08 06:29:29 +00:00
}
const invalidMacAddresses = new Set([
'00:00:00:00:00:00',
'ff:ff:ff:ff:ff:ff',
2024-08-10 11:58:31 +00:00
'ac:de:48:00:11:22',
2024-08-08 06:29:29 +00:00
]);
function validateMacAddress(candidate: string): boolean {
// eslint-disable-next-line no-useless-escape
const tempCandidate = candidate.replace(/\-/g, ':').toLowerCase();
return !invalidMacAddresses.has(tempCandidate);
2024-08-08 06:29:29 +00:00
}
export async function getMachineId(): Promise<string> {
if (!machineId) {
machineId = (async () => {
const id = await getMacMachineId();
2024-08-25 16:29:52 +00:00
return id ?? randomUUID(); // fallback, generate a UUID
})();
}
2024-08-08 06:29:29 +00:00
return machineId;
2024-08-08 06:29:29 +00:00
}
export function getMac(): string {
const ifaces = networkInterfaces();
for (const name in ifaces) {
const networkInterface = ifaces[name];
if (networkInterface) {
for (const { mac } of networkInterface) {
if (validateMacAddress(mac)) {
return mac;
}
}
2024-08-08 06:29:29 +00:00
}
}
throw new Error('Unable to retrieve mac address (unexpected format)');
2024-08-08 06:29:29 +00:00
}
async function getMacMachineId(): Promise<string | undefined> {
try {
const crypto = await import('crypto');
const macAddress = getMac();
return crypto.createHash('sha256').update(macAddress, 'utf8').digest('hex');
} catch (err) {
return undefined;
}
2024-08-08 06:29:29 +00:00
}
const homeDir = os.homedir();
export const systemPlatform = os.platform();
export const cpuArch = os.arch();
export const systemVersion = os.release();
export const hostname = osName;
export const downloadsPath = path.join(homeDir, 'Downloads');
2024-08-10 11:58:31 +00:00
export const systemName = os.type();