initial
This commit is contained in:
313
ts/discovery/discovery.classes.mdns.ts
Normal file
313
ts/discovery/discovery.classes.mdns.ts
Normal file
@@ -0,0 +1,313 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import type {
|
||||
IDiscoveredDevice,
|
||||
IDiscoveryOptions,
|
||||
TDeviceType,
|
||||
TScannerProtocol,
|
||||
} from '../interfaces/index.js';
|
||||
|
||||
/**
|
||||
* Service type definitions for mDNS discovery
|
||||
*/
|
||||
const SERVICE_TYPES = {
|
||||
// Scanners
|
||||
ESCL: '_uscan._tcp', // eSCL/AirScan scanners
|
||||
ESCL_SECURE: '_uscans._tcp', // eSCL over TLS
|
||||
SANE: '_scanner._tcp', // SANE network scanners
|
||||
|
||||
// Printers
|
||||
IPP: '_ipp._tcp', // IPP printers
|
||||
IPPS: '_ipps._tcp', // IPP over TLS
|
||||
PDL: '_pdl-datastream._tcp', // Raw/JetDirect printers
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Default discovery options
|
||||
*/
|
||||
const DEFAULT_OPTIONS: Required<IDiscoveryOptions> = {
|
||||
serviceTypes: [
|
||||
SERVICE_TYPES.ESCL,
|
||||
SERVICE_TYPES.ESCL_SECURE,
|
||||
SERVICE_TYPES.SANE,
|
||||
SERVICE_TYPES.IPP,
|
||||
SERVICE_TYPES.IPPS,
|
||||
],
|
||||
timeout: 10000,
|
||||
};
|
||||
|
||||
/**
|
||||
* mDNS/Bonjour discovery service for network devices
|
||||
*/
|
||||
export class MdnsDiscovery extends plugins.events.EventEmitter {
|
||||
private bonjour: plugins.bonjourService.Bonjour | null = null;
|
||||
private browsers: plugins.bonjourService.Browser[] = [];
|
||||
private discoveredDevices: Map<string, IDiscoveredDevice> = new Map();
|
||||
private options: Required<IDiscoveryOptions>;
|
||||
private isRunning: boolean = false;
|
||||
|
||||
constructor(options?: IDiscoveryOptions) {
|
||||
super();
|
||||
this.options = { ...DEFAULT_OPTIONS, ...options };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if discovery is currently running
|
||||
*/
|
||||
public get running(): boolean {
|
||||
return this.isRunning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all discovered devices
|
||||
*/
|
||||
public getDevices(): IDiscoveredDevice[] {
|
||||
return Array.from(this.discoveredDevices.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get discovered scanners only
|
||||
*/
|
||||
public getScanners(): IDiscoveredDevice[] {
|
||||
return this.getDevices().filter((d) => d.type === 'scanner');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get discovered printers only
|
||||
*/
|
||||
public getPrinters(): IDiscoveredDevice[] {
|
||||
return this.getDevices().filter((d) => d.type === 'printer');
|
||||
}
|
||||
|
||||
/**
|
||||
* Start mDNS discovery
|
||||
*/
|
||||
public async start(): Promise<void> {
|
||||
if (this.isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.bonjour = new plugins.bonjourService.Bonjour();
|
||||
this.isRunning = true;
|
||||
this.emit('started');
|
||||
|
||||
for (const serviceType of this.options.serviceTypes) {
|
||||
this.browseService(serviceType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop mDNS discovery
|
||||
*/
|
||||
public async stop(): Promise<void> {
|
||||
if (!this.isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Stop all browsers
|
||||
for (const browser of this.browsers) {
|
||||
browser.stop();
|
||||
}
|
||||
this.browsers = [];
|
||||
|
||||
// Destroy bonjour instance
|
||||
if (this.bonjour) {
|
||||
this.bonjour.destroy();
|
||||
this.bonjour = null;
|
||||
}
|
||||
|
||||
this.isRunning = false;
|
||||
this.emit('stopped');
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear discovered devices
|
||||
*/
|
||||
public clear(): void {
|
||||
this.discoveredDevices.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Browse for a specific service type
|
||||
*/
|
||||
private browseService(serviceType: string): void {
|
||||
if (!this.bonjour) {
|
||||
return;
|
||||
}
|
||||
|
||||
const browser = this.bonjour.find({ type: serviceType }, (service) => {
|
||||
this.handleServiceFound(service, serviceType);
|
||||
});
|
||||
|
||||
browser.on('down', (service) => {
|
||||
this.handleServiceLost(service, serviceType);
|
||||
});
|
||||
|
||||
this.browsers.push(browser);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle discovered service
|
||||
*/
|
||||
private handleServiceFound(
|
||||
service: plugins.bonjourService.Service,
|
||||
serviceType: string
|
||||
): void {
|
||||
const device = this.parseService(service, serviceType);
|
||||
if (!device) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingDevice = this.discoveredDevices.get(device.id);
|
||||
if (existingDevice) {
|
||||
// Update existing device
|
||||
this.discoveredDevices.set(device.id, device);
|
||||
this.emit('device:updated', device);
|
||||
} else {
|
||||
// New device found
|
||||
this.discoveredDevices.set(device.id, device);
|
||||
this.emit('device:found', device);
|
||||
|
||||
if (device.type === 'scanner') {
|
||||
this.emit('scanner:found', device);
|
||||
} else if (device.type === 'printer') {
|
||||
this.emit('printer:found', device);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle lost service
|
||||
*/
|
||||
private handleServiceLost(
|
||||
service: plugins.bonjourService.Service,
|
||||
serviceType: string
|
||||
): void {
|
||||
const deviceId = this.generateDeviceId(service, serviceType);
|
||||
const device = this.discoveredDevices.get(deviceId);
|
||||
|
||||
if (device) {
|
||||
this.discoveredDevices.delete(deviceId);
|
||||
this.emit('device:lost', device);
|
||||
|
||||
if (device.type === 'scanner') {
|
||||
this.emit('scanner:lost', deviceId);
|
||||
} else if (device.type === 'printer') {
|
||||
this.emit('printer:lost', deviceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Bonjour service into device info
|
||||
*/
|
||||
private parseService(
|
||||
service: plugins.bonjourService.Service,
|
||||
serviceType: string
|
||||
): IDiscoveredDevice | null {
|
||||
const addresses = service.addresses ?? [];
|
||||
// Prefer IPv4 address
|
||||
const address =
|
||||
addresses.find((a) => !a.includes(':')) ?? addresses[0] ?? service.host;
|
||||
|
||||
if (!address) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const txtRecords = this.parseTxtRecords(service.txt);
|
||||
const deviceType = this.getDeviceType(serviceType);
|
||||
const protocol = this.getProtocol(serviceType);
|
||||
|
||||
const deviceId = this.generateDeviceId(service, serviceType);
|
||||
|
||||
return {
|
||||
id: deviceId,
|
||||
name: service.name || txtRecords['ty'] || txtRecords['product'] || 'Unknown Device',
|
||||
type: deviceType,
|
||||
protocol: protocol,
|
||||
address: address,
|
||||
port: service.port,
|
||||
txtRecords: txtRecords,
|
||||
serviceType: serviceType,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate unique device ID
|
||||
*/
|
||||
private generateDeviceId(
|
||||
service: plugins.bonjourService.Service,
|
||||
serviceType: string
|
||||
): string {
|
||||
const addresses = service.addresses ?? [];
|
||||
const address = addresses.find((a) => !a.includes(':')) ?? addresses[0] ?? service.host;
|
||||
return `${serviceType}:${address}:${service.port}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse TXT records from service
|
||||
*/
|
||||
private parseTxtRecords(
|
||||
txt: Record<string, unknown> | undefined
|
||||
): Record<string, string> {
|
||||
const records: Record<string, string> = {};
|
||||
|
||||
if (!txt) {
|
||||
return records;
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(txt)) {
|
||||
if (typeof value === 'string') {
|
||||
records[key] = value;
|
||||
} else if (Buffer.isBuffer(value)) {
|
||||
records[key] = value.toString('utf-8');
|
||||
} else if (value !== undefined && value !== null) {
|
||||
records[key] = String(value);
|
||||
}
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine device type from service type
|
||||
*/
|
||||
private getDeviceType(serviceType: string): TDeviceType {
|
||||
switch (serviceType) {
|
||||
case SERVICE_TYPES.ESCL:
|
||||
case SERVICE_TYPES.ESCL_SECURE:
|
||||
case SERVICE_TYPES.SANE:
|
||||
return 'scanner';
|
||||
case SERVICE_TYPES.IPP:
|
||||
case SERVICE_TYPES.IPPS:
|
||||
case SERVICE_TYPES.PDL:
|
||||
return 'printer';
|
||||
default:
|
||||
// Check if it's a scanner or printer based on service type pattern
|
||||
if (serviceType.includes('scan') || serviceType.includes('scanner')) {
|
||||
return 'scanner';
|
||||
}
|
||||
return 'printer';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine protocol from service type
|
||||
*/
|
||||
private getProtocol(serviceType: string): TScannerProtocol | 'ipp' {
|
||||
switch (serviceType) {
|
||||
case SERVICE_TYPES.ESCL:
|
||||
case SERVICE_TYPES.ESCL_SECURE:
|
||||
return 'escl';
|
||||
case SERVICE_TYPES.SANE:
|
||||
return 'sane';
|
||||
case SERVICE_TYPES.IPP:
|
||||
case SERVICE_TYPES.IPPS:
|
||||
case SERVICE_TYPES.PDL:
|
||||
return 'ipp';
|
||||
default:
|
||||
return 'ipp';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { SERVICE_TYPES };
|
||||
378
ts/discovery/discovery.classes.networkscanner.ts
Normal file
378
ts/discovery/discovery.classes.networkscanner.ts
Normal file
@@ -0,0 +1,378 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
import { EsclProtocol } from '../scanner/scanner.classes.esclprotocol.js';
|
||||
import { IppProtocol } from '../printer/printer.classes.ippprotocol.js';
|
||||
import {
|
||||
cidrToIps,
|
||||
ipRangeToIps,
|
||||
isValidIp,
|
||||
} from '../helpers/helpers.iprange.js';
|
||||
import type {
|
||||
INetworkScanOptions,
|
||||
INetworkScanResult,
|
||||
INetworkScanDevice,
|
||||
INetworkScanProgress,
|
||||
} from '../interfaces/index.js';
|
||||
|
||||
/**
|
||||
* Default ports to probe for device discovery
|
||||
*/
|
||||
const DEFAULT_PORTS = [631, 80, 443, 6566, 9100];
|
||||
|
||||
/**
|
||||
* Default scan options
|
||||
*/
|
||||
const DEFAULT_OPTIONS: Required<Omit<INetworkScanOptions, 'ipRange' | 'startIp' | 'endIp'>> = {
|
||||
concurrency: 50,
|
||||
timeout: 2000,
|
||||
ports: DEFAULT_PORTS,
|
||||
probeEscl: true,
|
||||
probeIpp: true,
|
||||
probeSane: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Simple concurrency limiter
|
||||
*/
|
||||
class ConcurrencyLimiter {
|
||||
private running = 0;
|
||||
private queue: (() => void)[] = [];
|
||||
|
||||
constructor(private limit: number) {}
|
||||
|
||||
async run<T>(fn: () => Promise<T>): Promise<T> {
|
||||
while (this.running >= this.limit) {
|
||||
await new Promise<void>((resolve) => this.queue.push(resolve));
|
||||
}
|
||||
|
||||
this.running++;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
this.running--;
|
||||
const next = this.queue.shift();
|
||||
if (next) next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Network Scanner - scans IP ranges for scanners and printers
|
||||
*/
|
||||
export class NetworkScanner extends plugins.events.EventEmitter {
|
||||
private cancelled = false;
|
||||
private scanning = false;
|
||||
|
||||
/**
|
||||
* Check if a scan is currently in progress
|
||||
*/
|
||||
public get isScanning(): boolean {
|
||||
return this.scanning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan a network range for devices
|
||||
*/
|
||||
public async scan(options: INetworkScanOptions): Promise<INetworkScanResult[]> {
|
||||
if (this.scanning) {
|
||||
throw new Error('A scan is already in progress');
|
||||
}
|
||||
|
||||
this.cancelled = false;
|
||||
this.scanning = true;
|
||||
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||
const results: INetworkScanResult[] = [];
|
||||
|
||||
try {
|
||||
// Get list of IPs to scan
|
||||
const ips = this.resolveIps(options);
|
||||
|
||||
if (ips.length === 0) {
|
||||
throw new Error('No IPs to scan. Provide ipRange, or startIp and endIp.');
|
||||
}
|
||||
|
||||
const limiter = new ConcurrencyLimiter(opts.concurrency);
|
||||
let scanned = 0;
|
||||
|
||||
// Progress tracking
|
||||
const emitProgress = (currentIp?: string) => {
|
||||
const progress: INetworkScanProgress = {
|
||||
total: ips.length,
|
||||
scanned,
|
||||
percentage: Math.round((scanned / ips.length) * 100),
|
||||
currentIp,
|
||||
devicesFound: results.reduce((sum, r) => sum + r.devices.length, 0),
|
||||
};
|
||||
this.emit('progress', progress);
|
||||
};
|
||||
|
||||
emitProgress();
|
||||
|
||||
// Scan all IPs with concurrency limit
|
||||
const scanPromises = ips.map((ip) =>
|
||||
limiter.run(async () => {
|
||||
if (this.cancelled) return;
|
||||
|
||||
const devices = await this.probeIp(ip, opts);
|
||||
scanned++;
|
||||
|
||||
if (devices.length > 0) {
|
||||
const result: INetworkScanResult = { address: ip, devices };
|
||||
results.push(result);
|
||||
this.emit('device:found', result);
|
||||
}
|
||||
|
||||
emitProgress(ip);
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(scanPromises);
|
||||
|
||||
if (this.cancelled) {
|
||||
this.emit('cancelled');
|
||||
} else {
|
||||
this.emit('complete', results);
|
||||
}
|
||||
|
||||
return results;
|
||||
} finally {
|
||||
this.scanning = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an ongoing scan
|
||||
*/
|
||||
public async cancel(): Promise<void> {
|
||||
if (this.scanning) {
|
||||
this.cancelled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve IPs from options (CIDR or start/end range)
|
||||
*/
|
||||
private resolveIps(options: INetworkScanOptions): string[] {
|
||||
if (options.ipRange) {
|
||||
return cidrToIps(options.ipRange);
|
||||
}
|
||||
|
||||
if (options.startIp && options.endIp) {
|
||||
return ipRangeToIps(options.startIp, options.endIp);
|
||||
}
|
||||
|
||||
if (options.startIp && !options.endIp) {
|
||||
// Single IP
|
||||
if (isValidIp(options.startIp)) {
|
||||
return [options.startIp];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe a single IP address for devices
|
||||
*/
|
||||
private async probeIp(
|
||||
ip: string,
|
||||
opts: Required<Omit<INetworkScanOptions, 'ipRange' | 'startIp' | 'endIp'>>
|
||||
): Promise<INetworkScanDevice[]> {
|
||||
const devices: INetworkScanDevice[] = [];
|
||||
const timeout = opts.timeout;
|
||||
|
||||
// First, do a quick port scan to see which ports are open
|
||||
const openPorts = await this.scanPorts(ip, opts.ports, timeout / 2);
|
||||
|
||||
if (openPorts.length === 0 || this.cancelled) {
|
||||
return devices;
|
||||
}
|
||||
|
||||
// Probe each open port for specific protocols
|
||||
const probePromises: Promise<void>[] = [];
|
||||
|
||||
for (const port of openPorts) {
|
||||
// IPP probe (port 631)
|
||||
if (opts.probeIpp && port === 631) {
|
||||
probePromises.push(
|
||||
this.probeIpp(ip, port, timeout).then((device) => {
|
||||
if (device) devices.push(device);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// eSCL probe (ports 80, 443)
|
||||
if (opts.probeEscl && (port === 80 || port === 443)) {
|
||||
probePromises.push(
|
||||
this.probeEscl(ip, port, timeout).then((device) => {
|
||||
if (device) devices.push(device);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// SANE probe (port 6566)
|
||||
if (opts.probeSane && port === 6566) {
|
||||
probePromises.push(
|
||||
this.probeSane(ip, port, timeout).then((device) => {
|
||||
if (device) devices.push(device);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// JetDirect probe (port 9100) - just mark as raw printer
|
||||
if (port === 9100) {
|
||||
devices.push({
|
||||
type: 'printer',
|
||||
protocol: 'jetdirect',
|
||||
port: 9100,
|
||||
name: `Raw Printer at ${ip}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(probePromises);
|
||||
|
||||
return devices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick TCP port scan
|
||||
*/
|
||||
private async scanPorts(ip: string, ports: number[], timeout: number): Promise<number[]> {
|
||||
const openPorts: number[] = [];
|
||||
|
||||
const scanPromises = ports.map(async (port) => {
|
||||
const isOpen = await this.isPortOpen(ip, port, timeout);
|
||||
if (isOpen) {
|
||||
openPorts.push(port);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(scanPromises);
|
||||
return openPorts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a TCP port is open
|
||||
*/
|
||||
private isPortOpen(ip: string, port: number, timeout: number): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const socket = new plugins.net.Socket();
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
socket.destroy();
|
||||
resolve(false);
|
||||
}, timeout);
|
||||
|
||||
socket.on('connect', () => {
|
||||
clearTimeout(timer);
|
||||
socket.destroy();
|
||||
resolve(true);
|
||||
});
|
||||
|
||||
socket.on('error', () => {
|
||||
clearTimeout(timer);
|
||||
socket.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
|
||||
socket.connect(port, ip);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe for IPP printer
|
||||
*/
|
||||
private async probeIpp(
|
||||
ip: string,
|
||||
port: number,
|
||||
timeout: number
|
||||
): Promise<INetworkScanDevice | null> {
|
||||
try {
|
||||
const ipp = new IppProtocol(ip, port);
|
||||
const attrs = await Promise.race([
|
||||
ipp.getAttributes(),
|
||||
new Promise<null>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Timeout')), timeout)
|
||||
),
|
||||
]);
|
||||
|
||||
if (attrs) {
|
||||
return {
|
||||
type: 'printer',
|
||||
protocol: 'ipp',
|
||||
port,
|
||||
name: `IPP Printer at ${ip}`,
|
||||
model: undefined,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Not an IPP printer
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe for eSCL scanner
|
||||
*/
|
||||
private async probeEscl(
|
||||
ip: string,
|
||||
port: number,
|
||||
timeout: number
|
||||
): Promise<INetworkScanDevice | null> {
|
||||
try {
|
||||
const secure = port === 443;
|
||||
const escl = new EsclProtocol(ip, port, secure);
|
||||
|
||||
const caps = await Promise.race([
|
||||
escl.getCapabilities(),
|
||||
new Promise<null>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Timeout')), timeout)
|
||||
),
|
||||
]);
|
||||
|
||||
if (caps) {
|
||||
return {
|
||||
type: 'scanner',
|
||||
protocol: 'escl',
|
||||
port,
|
||||
name: caps.makeAndModel || `eSCL Scanner at ${ip}`,
|
||||
model: caps.makeAndModel,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Not an eSCL scanner
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe for SANE scanner (quick check)
|
||||
*/
|
||||
private async probeSane(
|
||||
ip: string,
|
||||
port: number,
|
||||
timeout: number
|
||||
): Promise<INetworkScanDevice | null> {
|
||||
// SANE probing requires full protocol implementation
|
||||
// For now, just check if port is open and assume it's SANE
|
||||
// A more thorough implementation would send SANE_NET_INIT
|
||||
try {
|
||||
const isOpen = await this.isPortOpen(ip, port, timeout);
|
||||
if (isOpen) {
|
||||
return {
|
||||
type: 'scanner',
|
||||
protocol: 'sane',
|
||||
port,
|
||||
name: `SANE Scanner at ${ip}`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Not a SANE scanner
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
357
ts/discovery/discovery.classes.ssdp.ts
Normal file
357
ts/discovery/discovery.classes.ssdp.ts
Normal file
@@ -0,0 +1,357 @@
|
||||
import * as plugins from '../plugins.js';
|
||||
|
||||
/**
|
||||
* SSDP service types for device discovery
|
||||
*/
|
||||
export const SSDP_SERVICE_TYPES = {
|
||||
// Root device
|
||||
ROOT: 'upnp:rootdevice',
|
||||
|
||||
// DLNA/UPnP AV
|
||||
MEDIA_RENDERER: 'urn:schemas-upnp-org:device:MediaRenderer:1',
|
||||
MEDIA_SERVER: 'urn:schemas-upnp-org:device:MediaServer:1',
|
||||
|
||||
// Sonos
|
||||
SONOS_ZONE_PLAYER: 'urn:schemas-upnp-org:device:ZonePlayer:1',
|
||||
|
||||
// Generic
|
||||
BASIC_DEVICE: 'urn:schemas-upnp-org:device:Basic:1',
|
||||
INTERNET_GATEWAY: 'urn:schemas-upnp-org:device:InternetGatewayDevice:1',
|
||||
};
|
||||
|
||||
/**
|
||||
* SSDP discovered device information
|
||||
*/
|
||||
export interface ISsdpDevice {
|
||||
/** Unique service name (USN) */
|
||||
usn: string;
|
||||
/** Service type (ST) */
|
||||
serviceType: string;
|
||||
/** Location URL of device description */
|
||||
location: string;
|
||||
/** IP address */
|
||||
address: string;
|
||||
/** Port number */
|
||||
port: number;
|
||||
/** Device description (fetched from location) */
|
||||
description?: ISsdpDeviceDescription;
|
||||
/** Raw headers from SSDP response */
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* UPnP device description (from XML)
|
||||
*/
|
||||
export interface ISsdpDeviceDescription {
|
||||
deviceType: string;
|
||||
friendlyName: string;
|
||||
manufacturer: string;
|
||||
manufacturerURL?: string;
|
||||
modelDescription?: string;
|
||||
modelName: string;
|
||||
modelNumber?: string;
|
||||
modelURL?: string;
|
||||
serialNumber?: string;
|
||||
UDN: string;
|
||||
services: ISsdpService[];
|
||||
icons?: ISsdpIcon[];
|
||||
}
|
||||
|
||||
export interface ISsdpService {
|
||||
serviceType: string;
|
||||
serviceId: string;
|
||||
SCPDURL: string;
|
||||
controlURL: string;
|
||||
eventSubURL: string;
|
||||
}
|
||||
|
||||
export interface ISsdpIcon {
|
||||
mimetype: string;
|
||||
width: number;
|
||||
height: number;
|
||||
depth: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* SSDP Discovery service using node-ssdp
|
||||
*/
|
||||
export class SsdpDiscovery extends plugins.events.EventEmitter {
|
||||
private client: InstanceType<typeof plugins.nodeSsdp.Client> | null = null;
|
||||
private devices: Map<string, ISsdpDevice> = new Map();
|
||||
private running = false;
|
||||
private searchInterval: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start SSDP discovery
|
||||
*/
|
||||
public async start(serviceTypes?: string[]): Promise<void> {
|
||||
if (this.running) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.running = true;
|
||||
this.client = new plugins.nodeSsdp.Client();
|
||||
|
||||
// Handle SSDP responses
|
||||
this.client.on('response', (headers: Record<string, string>, statusCode: number, rinfo: { address: string; port: number }) => {
|
||||
this.handleSsdpResponse(headers, rinfo);
|
||||
});
|
||||
|
||||
// Search for devices
|
||||
const typesToSearch = serviceTypes ?? [
|
||||
SSDP_SERVICE_TYPES.ROOT,
|
||||
SSDP_SERVICE_TYPES.MEDIA_RENDERER,
|
||||
SSDP_SERVICE_TYPES.MEDIA_SERVER,
|
||||
SSDP_SERVICE_TYPES.SONOS_ZONE_PLAYER,
|
||||
];
|
||||
|
||||
// Initial search
|
||||
for (const st of typesToSearch) {
|
||||
this.client.search(st);
|
||||
}
|
||||
|
||||
// Periodic re-search (every 30 seconds)
|
||||
this.searchInterval = setInterval(() => {
|
||||
if (this.client) {
|
||||
for (const st of typesToSearch) {
|
||||
this.client.search(st);
|
||||
}
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
this.emit('started');
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop SSDP discovery
|
||||
*/
|
||||
public async stop(): Promise<void> {
|
||||
if (!this.running) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.running = false;
|
||||
|
||||
if (this.searchInterval) {
|
||||
clearInterval(this.searchInterval);
|
||||
this.searchInterval = null;
|
||||
}
|
||||
|
||||
if (this.client) {
|
||||
this.client.stop();
|
||||
this.client = null;
|
||||
}
|
||||
|
||||
this.emit('stopped');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if discovery is running
|
||||
*/
|
||||
public get isRunning(): boolean {
|
||||
return this.running;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all discovered devices
|
||||
*/
|
||||
public getDevices(): ISsdpDevice[] {
|
||||
return Array.from(this.devices.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get devices by service type
|
||||
*/
|
||||
public getDevicesByType(serviceType: string): ISsdpDevice[] {
|
||||
return this.getDevices().filter((d) => d.serviceType === serviceType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a specific service type
|
||||
*/
|
||||
public search(serviceType: string): void {
|
||||
if (this.client && this.running) {
|
||||
this.client.search(serviceType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle SSDP response
|
||||
*/
|
||||
private handleSsdpResponse(
|
||||
headers: Record<string, string>,
|
||||
rinfo: { address: string; port: number }
|
||||
): void {
|
||||
const usn = headers['USN'] || headers['usn'];
|
||||
const location = headers['LOCATION'] || headers['location'];
|
||||
const st = headers['ST'] || headers['st'];
|
||||
|
||||
if (!usn || !location) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse location URL
|
||||
let address = rinfo.address;
|
||||
let port = 80;
|
||||
|
||||
try {
|
||||
const url = new URL(location);
|
||||
address = url.hostname;
|
||||
port = parseInt(url.port) || (url.protocol === 'https:' ? 443 : 80);
|
||||
} catch {
|
||||
// Keep rinfo address
|
||||
}
|
||||
|
||||
const device: ISsdpDevice = {
|
||||
usn,
|
||||
serviceType: st || 'unknown',
|
||||
location,
|
||||
address,
|
||||
port,
|
||||
headers: { ...headers },
|
||||
};
|
||||
|
||||
const isNew = !this.devices.has(usn);
|
||||
this.devices.set(usn, device);
|
||||
|
||||
if (isNew) {
|
||||
// Fetch device description
|
||||
this.fetchDeviceDescription(device).then(() => {
|
||||
this.emit('device:found', device);
|
||||
}).catch(() => {
|
||||
// Still emit even without description
|
||||
this.emit('device:found', device);
|
||||
});
|
||||
} else {
|
||||
this.emit('device:updated', device);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and parse device description XML
|
||||
*/
|
||||
private async fetchDeviceDescription(device: ISsdpDevice): Promise<void> {
|
||||
try {
|
||||
const response = await fetch(device.location, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const xml = await response.text();
|
||||
device.description = this.parseDeviceDescription(xml);
|
||||
} catch {
|
||||
// Ignore fetch errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse UPnP device description XML
|
||||
*/
|
||||
private parseDeviceDescription(xml: string): ISsdpDeviceDescription {
|
||||
const getTagContent = (tag: string, source: string = xml): string => {
|
||||
const regex = new RegExp(`<${tag}[^>]*>([^<]*)</${tag}>`, 'i');
|
||||
const match = source.match(regex);
|
||||
return match?.[1]?.trim() ?? '';
|
||||
};
|
||||
|
||||
const getTagBlock = (tag: string, source: string = xml): string => {
|
||||
const regex = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'i');
|
||||
const match = source.match(regex);
|
||||
return match?.[1] ?? '';
|
||||
};
|
||||
|
||||
// Parse services
|
||||
const services: ISsdpService[] = [];
|
||||
const serviceListBlock = getTagBlock('serviceList');
|
||||
const serviceMatches = serviceListBlock.match(/<service>[\s\S]*?<\/service>/gi) || [];
|
||||
|
||||
for (const serviceXml of serviceMatches) {
|
||||
services.push({
|
||||
serviceType: getTagContent('serviceType', serviceXml),
|
||||
serviceId: getTagContent('serviceId', serviceXml),
|
||||
SCPDURL: getTagContent('SCPDURL', serviceXml),
|
||||
controlURL: getTagContent('controlURL', serviceXml),
|
||||
eventSubURL: getTagContent('eventSubURL', serviceXml),
|
||||
});
|
||||
}
|
||||
|
||||
// Parse icons
|
||||
const icons: ISsdpIcon[] = [];
|
||||
const iconListBlock = getTagBlock('iconList');
|
||||
const iconMatches = iconListBlock.match(/<icon>[\s\S]*?<\/icon>/gi) || [];
|
||||
|
||||
for (const iconXml of iconMatches) {
|
||||
icons.push({
|
||||
mimetype: getTagContent('mimetype', iconXml),
|
||||
width: parseInt(getTagContent('width', iconXml)) || 0,
|
||||
height: parseInt(getTagContent('height', iconXml)) || 0,
|
||||
depth: parseInt(getTagContent('depth', iconXml)) || 0,
|
||||
url: getTagContent('url', iconXml),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
deviceType: getTagContent('deviceType'),
|
||||
friendlyName: getTagContent('friendlyName'),
|
||||
manufacturer: getTagContent('manufacturer'),
|
||||
manufacturerURL: getTagContent('manufacturerURL') || undefined,
|
||||
modelDescription: getTagContent('modelDescription') || undefined,
|
||||
modelName: getTagContent('modelName'),
|
||||
modelNumber: getTagContent('modelNumber') || undefined,
|
||||
modelURL: getTagContent('modelURL') || undefined,
|
||||
serialNumber: getTagContent('serialNumber') || undefined,
|
||||
UDN: getTagContent('UDN'),
|
||||
services,
|
||||
icons: icons.length > 0 ? icons : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a UPnP SOAP request
|
||||
*/
|
||||
public async soapRequest(
|
||||
controlUrl: string,
|
||||
serviceType: string,
|
||||
action: string,
|
||||
args: Record<string, string | number> = {}
|
||||
): Promise<string> {
|
||||
// Build SOAP body
|
||||
let argsXml = '';
|
||||
for (const [key, value] of Object.entries(args)) {
|
||||
argsXml += `<${key}>${value}</${key}>`;
|
||||
}
|
||||
|
||||
const soapBody = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
|
||||
<s:Body>
|
||||
<u:${action} xmlns:u="${serviceType}">
|
||||
${argsXml}
|
||||
</u:${action}>
|
||||
</s:Body>
|
||||
</s:Envelope>`;
|
||||
|
||||
const response = await fetch(controlUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'text/xml; charset=utf-8',
|
||||
'SOAPACTION': `"${serviceType}#${action}"`,
|
||||
},
|
||||
body: soapBody,
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`SOAP request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.text();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user