electron-cast 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/client/cast-client.d.ts +92 -0
- package/dist/client/cast-client.js +427 -0
- package/dist/client/cast-client.js.map +1 -0
- package/dist/client/errors.d.ts +17 -0
- package/dist/client/errors.js +30 -0
- package/dist/client/errors.js.map +1 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +5 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/namespaces.d.ts +9 -0
- package/dist/client/namespaces.js +10 -0
- package/dist/client/namespaces.js.map +1 -0
- package/dist/client/types.d.ts +27 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/discovery/cast-discovery.d.ts +84 -0
- package/dist/discovery/cast-discovery.js +234 -0
- package/dist/discovery/cast-discovery.js.map +1 -0
- package/dist/discovery/device-cache.d.ts +40 -0
- package/dist/discovery/device-cache.js +212 -0
- package/dist/discovery/device-cache.js.map +1 -0
- package/dist/discovery/dns-packet.d.ts +70 -0
- package/dist/discovery/dns-packet.js +244 -0
- package/dist/discovery/dns-packet.js.map +1 -0
- package/dist/discovery/index.d.ts +4 -0
- package/dist/discovery/index.js +5 -0
- package/dist/discovery/index.js.map +1 -0
- package/dist/discovery/udp-socket.d.ts +12 -0
- package/dist/discovery/udp-socket.js +105 -0
- package/dist/discovery/udp-socket.js.map +1 -0
- package/dist/electron/main.d.ts +49 -0
- package/dist/electron/main.js +79 -0
- package/dist/electron/main.js.map +1 -0
- package/dist/electron/preload.d.ts +22 -0
- package/dist/electron/preload.js +36 -0
- package/dist/electron/preload.js.map +1 -0
- package/dist/electron/session-service.d.ts +125 -0
- package/dist/electron/session-service.js +661 -0
- package/dist/electron/session-service.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/polyfill/bridge-types.d.ts +82 -0
- package/dist/polyfill/bridge-types.js +2 -0
- package/dist/polyfill/bridge-types.js.map +1 -0
- package/dist/polyfill/install.d.ts +12 -0
- package/dist/polyfill/install.js +546 -0
- package/dist/polyfill/install.js.map +1 -0
- package/dist/protocol/cast-message.d.ts +20 -0
- package/dist/protocol/cast-message.js +166 -0
- package/dist/protocol/cast-message.js.map +1 -0
- package/dist/protocol/errors.d.ts +4 -0
- package/dist/protocol/errors.js +8 -0
- package/dist/protocol/errors.js.map +1 -0
- package/dist/protocol/framing.d.ts +18 -0
- package/dist/protocol/framing.js +95 -0
- package/dist/protocol/framing.js.map +1 -0
- package/dist/protocol/index.d.ts +3 -0
- package/dist/protocol/index.js +4 -0
- package/dist/protocol/index.js.map +1 -0
- package/package.json +59 -4
- package/src/client/cast-client.ts +483 -0
- package/src/client/errors.ts +32 -0
- package/src/client/index.ts +4 -0
- package/src/client/namespaces.ts +10 -0
- package/src/client/types.ts +27 -0
- package/src/discovery/cast-discovery.ts +265 -0
- package/src/discovery/device-cache.ts +231 -0
- package/src/discovery/dns-packet.ts +262 -0
- package/src/discovery/index.ts +4 -0
- package/src/discovery/udp-socket.ts +121 -0
- package/src/electron/main.ts +110 -0
- package/src/electron/preload.ts +57 -0
- package/src/electron/session-service.ts +715 -0
- package/src/index.ts +8 -0
- package/src/polyfill/bridge-types.ts +26 -0
- package/src/polyfill/install.ts +576 -0
- package/src/protocol/cast-message.ts +176 -0
- package/src/protocol/errors.ts +7 -0
- package/src/protocol/framing.ts +97 -0
- package/src/protocol/index.ts +3 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { CastDeviceCache, type CastDevice } from "./device-cache.ts";
|
|
4
|
+
import { decodeDnsPacket, encodeMdnsQuery, RecordType, type DnsPacket } from "./dns-packet.ts";
|
|
5
|
+
import { openUdpMdnsSocket } from "./udp-socket.ts";
|
|
6
|
+
|
|
7
|
+
/** An external IPv4 interface. */
|
|
8
|
+
export interface NetworkInterfaceInfo { name: string; address: string }
|
|
9
|
+
|
|
10
|
+
/** Callbacks for an mDNS socket: incoming packets and socket errors. */
|
|
11
|
+
export interface MdnsSocketHandlers {
|
|
12
|
+
message(packet: Buffer, from: { address: string; port: number }): void;
|
|
13
|
+
error(error: Error): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** An open mDNS socket: send queries on it, close it when done. */
|
|
17
|
+
export interface MdnsSocket { send(packet: Buffer): void; close(): void }
|
|
18
|
+
|
|
19
|
+
/** Opens an mDNS socket on one interface; rejects if it cannot. */
|
|
20
|
+
export type OpenMdnsSocket = (iface: NetworkInterfaceInfo, handlers: MdnsSocketHandlers) => Promise<MdnsSocket>;
|
|
21
|
+
|
|
22
|
+
const DEFAULT_SERVICE_NAME = "_googlecast._tcp.local";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* External IPv4 interfaces: non-internal, non-link-local, one entry per
|
|
26
|
+
* address (first name wins), in the order the OS reports them.
|
|
27
|
+
*/
|
|
28
|
+
export function listIPv4Interfaces(nets?: NodeJS.Dict<os.NetworkInterfaceInfo[]>): NetworkInterfaceInfo[] {
|
|
29
|
+
const out: NetworkInterfaceInfo[] = [];
|
|
30
|
+
const seen = new Set<string>();
|
|
31
|
+
for (const [name, addrs] of Object.entries(nets ?? os.networkInterfaces())) {
|
|
32
|
+
for (const addr of addrs ?? []) {
|
|
33
|
+
const family: unknown = addr.family;
|
|
34
|
+
if (family !== "IPv4" && family !== 4) continue;
|
|
35
|
+
if (addr.internal) continue;
|
|
36
|
+
if (addr.address.startsWith("169.254.")) continue;
|
|
37
|
+
if (seen.has(addr.address)) continue;
|
|
38
|
+
seen.add(addr.address);
|
|
39
|
+
out.push({ name, address: addr.address });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface CastDiscoveryOptions {
|
|
46
|
+
serviceName?: string; // default "_googlecast._tcp.local"
|
|
47
|
+
interfaces?: () => NetworkInterfaceInfo[]; // default () => listIPv4Interfaces()
|
|
48
|
+
openSocket?: OpenMdnsSocket; // default openUdpMdnsSocket
|
|
49
|
+
followUpQueriesMs?: number[]; // default [1000, 3000], measured from start
|
|
50
|
+
refreshMs?: number; // default 60000
|
|
51
|
+
expireCheckMs?: number; // default 1000
|
|
52
|
+
interfaceCheckMs?: number; // default 10000
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface CastDiscoveryEvents {
|
|
56
|
+
deviceUp: [device: CastDevice];
|
|
57
|
+
deviceDown: [device: CastDevice];
|
|
58
|
+
deviceChanged: [device: CastDevice];
|
|
59
|
+
socketError: [iface: NetworkInterfaceInfo, error: Error];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface SocketEntry {
|
|
63
|
+
iface: NetworkInterfaceInfo;
|
|
64
|
+
socket: MdnsSocket;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function toError(error: unknown): Error {
|
|
68
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Discovers Cast devices by sending mDNS PTR queries on every external IPv4
|
|
73
|
+
* interface and joining the answers into {@link CastDevice}s.
|
|
74
|
+
*/
|
|
75
|
+
export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
|
|
76
|
+
private readonly serviceName: string;
|
|
77
|
+
private readonly listIfaces: () => NetworkInterfaceInfo[];
|
|
78
|
+
private readonly openSocketFn: OpenMdnsSocket;
|
|
79
|
+
private readonly followUpQueriesMs: number[];
|
|
80
|
+
private readonly refreshMs: number;
|
|
81
|
+
private readonly expireCheckMs: number;
|
|
82
|
+
private readonly interfaceCheckMs: number;
|
|
83
|
+
private readonly queryPacket: Buffer;
|
|
84
|
+
private cache: CastDeviceCache;
|
|
85
|
+
private sockets: SocketEntry[] = [];
|
|
86
|
+
private readonly pending = new Set<string>();
|
|
87
|
+
private timers: NodeJS.Timeout[] = [];
|
|
88
|
+
private startPromise: Promise<void> | null = null;
|
|
89
|
+
private stopped = false;
|
|
90
|
+
|
|
91
|
+
constructor(options: CastDiscoveryOptions = {}) {
|
|
92
|
+
super();
|
|
93
|
+
this.serviceName = options.serviceName ?? DEFAULT_SERVICE_NAME;
|
|
94
|
+
this.listIfaces = options.interfaces ?? (() => listIPv4Interfaces());
|
|
95
|
+
this.openSocketFn = options.openSocket ?? openUdpMdnsSocket;
|
|
96
|
+
this.followUpQueriesMs = options.followUpQueriesMs ?? [1000, 3000];
|
|
97
|
+
this.refreshMs = options.refreshMs ?? 60_000;
|
|
98
|
+
this.expireCheckMs = options.expireCheckMs ?? 1000;
|
|
99
|
+
this.interfaceCheckMs = options.interfaceCheckMs ?? 10_000;
|
|
100
|
+
this.cache = new CastDeviceCache(this.serviceName);
|
|
101
|
+
this.queryPacket = encodeMdnsQuery(this.serviceName, RecordType.PTR);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Opens a socket on every interface and starts querying; see the options for the schedule. */
|
|
105
|
+
start(): Promise<void> {
|
|
106
|
+
if (this.stopped) return Promise.reject(new Error("discovery stopped"));
|
|
107
|
+
if (this.startPromise !== null) return this.startPromise;
|
|
108
|
+
this.startTimers();
|
|
109
|
+
const ifaces = this.listIfaces();
|
|
110
|
+
this.startPromise = Promise.allSettled(ifaces.map((iface) => this.openIface(iface))).then(
|
|
111
|
+
() => undefined,
|
|
112
|
+
);
|
|
113
|
+
return this.startPromise;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Sends one query on every open socket now. */
|
|
117
|
+
query(): void {
|
|
118
|
+
if (this.stopped) return;
|
|
119
|
+
for (const entry of [...this.sockets]) this.safeQuery(entry.iface, entry.socket);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Fresh copies of all currently known devices. */
|
|
123
|
+
devices(): CastDevice[] {
|
|
124
|
+
return this.cache.devices();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The interfaces with an open socket, in the order their sockets were added. */
|
|
128
|
+
interfaces(): NetworkInterfaceInfo[] {
|
|
129
|
+
return this.sockets.map((entry) => ({ ...entry.iface }));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Stops everything at once: timers, sockets, remembered devices. Idempotent. */
|
|
133
|
+
stop(): void {
|
|
134
|
+
if (this.stopped) return;
|
|
135
|
+
this.stopped = true;
|
|
136
|
+
for (const timer of this.timers) {
|
|
137
|
+
clearTimeout(timer);
|
|
138
|
+
clearInterval(timer);
|
|
139
|
+
}
|
|
140
|
+
this.timers = [];
|
|
141
|
+
for (const entry of this.sockets) this.closeQuietly(entry.socket);
|
|
142
|
+
this.sockets = [];
|
|
143
|
+
this.pending.clear();
|
|
144
|
+
this.cache = new CastDeviceCache(this.serviceName);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private startTimers(): void {
|
|
148
|
+
for (const offset of this.followUpQueriesMs) {
|
|
149
|
+
this.timers.push(setTimeout(() => this.query(), offset));
|
|
150
|
+
}
|
|
151
|
+
const lastFollowUp = this.followUpQueriesMs.length > 0 ? Math.max(...this.followUpQueriesMs) : 0;
|
|
152
|
+
this.timers.push(
|
|
153
|
+
setTimeout(() => {
|
|
154
|
+
this.query();
|
|
155
|
+
this.timers.push(setInterval(() => this.query(), this.refreshMs));
|
|
156
|
+
}, lastFollowUp + this.refreshMs),
|
|
157
|
+
);
|
|
158
|
+
this.timers.push(
|
|
159
|
+
setInterval(() => {
|
|
160
|
+
const change = this.cache.expire(Date.now());
|
|
161
|
+
for (const device of change.removed) this.emit("deviceDown", device);
|
|
162
|
+
}, this.expireCheckMs),
|
|
163
|
+
);
|
|
164
|
+
this.timers.push(setInterval(() => this.checkInterfaces(), this.interfaceCheckMs));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Opens a socket on `iface`; on success adds it and sends one query on it. */
|
|
168
|
+
private openIface(iface: NetworkInterfaceInfo): Promise<void> {
|
|
169
|
+
this.pending.add(iface.address);
|
|
170
|
+
const work = (async (): Promise<void> => {
|
|
171
|
+
// Errors are matched to this socket, not to its address: a late error from a replaced socket must not
|
|
172
|
+
// close the socket that replaced it.
|
|
173
|
+
const holder: { socket?: MdnsSocket } = {};
|
|
174
|
+
let socket: MdnsSocket;
|
|
175
|
+
try {
|
|
176
|
+
socket = await this.openSocketFn(iface, this.makeHandlers(iface, holder));
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if (!this.stopped) this.emit("socketError", iface, toError(error));
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
holder.socket = socket;
|
|
182
|
+
if (this.stopped || this.sockets.some((s) => s.iface.address === iface.address)) {
|
|
183
|
+
this.closeQuietly(socket);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
this.sockets.push({ iface, socket });
|
|
187
|
+
this.safeQuery(iface, socket);
|
|
188
|
+
})();
|
|
189
|
+
return work.finally(() => this.pending.delete(iface.address));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
private makeHandlers(iface: NetworkInterfaceInfo, holder: { socket?: MdnsSocket }): MdnsSocketHandlers {
|
|
193
|
+
return {
|
|
194
|
+
message: (packet: Buffer) => this.onMessage(packet),
|
|
195
|
+
error: (error: Error) => this.onSocketError(iface, error, holder.socket),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private onMessage(packet: Buffer): void {
|
|
200
|
+
if (this.stopped) return;
|
|
201
|
+
let decoded: DnsPacket;
|
|
202
|
+
try {
|
|
203
|
+
decoded = decodeDnsPacket(packet);
|
|
204
|
+
} catch {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (!decoded.isResponse) return;
|
|
208
|
+
const records = [...decoded.answers, ...decoded.authorities, ...decoded.additionals];
|
|
209
|
+
const change = this.cache.ingest(records, Date.now());
|
|
210
|
+
for (const device of change.removed) this.emit("deviceDown", device);
|
|
211
|
+
for (const device of change.updated) this.emit("deviceChanged", device);
|
|
212
|
+
for (const device of change.added) this.emit("deviceUp", device);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private onSocketError(iface: NetworkInterfaceInfo, error: Error, socket: MdnsSocket | undefined): void {
|
|
216
|
+
if (this.stopped) return;
|
|
217
|
+
const idx = this.sockets.findIndex((s) => s.socket === socket);
|
|
218
|
+
if (idx === -1) {
|
|
219
|
+
// Not (or no longer) one of ours: a socket already dropped or replaced. Close it quietly.
|
|
220
|
+
if (socket !== undefined) this.closeQuietly(socket);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
this.sockets.splice(idx, 1);
|
|
224
|
+
if (socket !== undefined) this.closeQuietly(socket);
|
|
225
|
+
this.emit("socketError", iface, error);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private safeQuery(iface: NetworkInterfaceInfo, socket: MdnsSocket): void {
|
|
229
|
+
try {
|
|
230
|
+
socket.send(this.queryPacket);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
this.onSocketError(iface, toError(error), socket);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Re-lists interfaces: opens new ones, closes vanished ones, leaves the rest alone. */
|
|
237
|
+
private checkInterfaces(): void {
|
|
238
|
+
if (this.stopped) return;
|
|
239
|
+
let ifaces: NetworkInterfaceInfo[];
|
|
240
|
+
try {
|
|
241
|
+
ifaces = this.listIfaces();
|
|
242
|
+
} catch {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const listed = new Set(ifaces.map((i) => i.address));
|
|
246
|
+
this.sockets = this.sockets.filter((entry) => {
|
|
247
|
+
if (listed.has(entry.iface.address)) return true;
|
|
248
|
+
this.closeQuietly(entry.socket);
|
|
249
|
+
return false;
|
|
250
|
+
});
|
|
251
|
+
for (const iface of ifaces) {
|
|
252
|
+
if (this.sockets.some((s) => s.iface.address === iface.address)) continue;
|
|
253
|
+
if (this.pending.has(iface.address)) continue;
|
|
254
|
+
void this.openIface(iface);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
private closeQuietly(socket: MdnsSocket): void {
|
|
259
|
+
try {
|
|
260
|
+
socket.close();
|
|
261
|
+
} catch {
|
|
262
|
+
// already closed
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import type { DnsRecord } from "./dns-packet.ts";
|
|
2
|
+
|
|
3
|
+
/** A Cast device assembled from PTR, SRV, TXT and address records. */
|
|
4
|
+
export interface CastDevice {
|
|
5
|
+
id: string;
|
|
6
|
+
name: string;
|
|
7
|
+
model: string;
|
|
8
|
+
host: string;
|
|
9
|
+
addresses: string[];
|
|
10
|
+
port: number;
|
|
11
|
+
capabilities: number;
|
|
12
|
+
isGroup: boolean;
|
|
13
|
+
statusText: string;
|
|
14
|
+
instanceName: string;
|
|
15
|
+
txt: Record<string, string>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Devices added, updated or removed by one ingest or expire call. */
|
|
19
|
+
export interface CacheChange {
|
|
20
|
+
added: CastDevice[];
|
|
21
|
+
updated: CastDevice[];
|
|
22
|
+
removed: CastDevice[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface StoredRecord {
|
|
26
|
+
record: DnsRecord;
|
|
27
|
+
receivedAt: number;
|
|
28
|
+
expiresAt: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Data-identity component of a storage key ("" for TXT, which is keyed by name alone). */
|
|
32
|
+
function dataKey(record: DnsRecord): string {
|
|
33
|
+
switch (record.type) {
|
|
34
|
+
case "A":
|
|
35
|
+
case "AAAA":
|
|
36
|
+
case "PTR":
|
|
37
|
+
return record.data.toLowerCase();
|
|
38
|
+
case "SRV":
|
|
39
|
+
return `${record.data.port}:${record.data.target.toLowerCase()}`;
|
|
40
|
+
case "TXT":
|
|
41
|
+
return "";
|
|
42
|
+
case "UNKNOWN":
|
|
43
|
+
return record.data.toString("hex");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function keyOf(record: DnsRecord): string {
|
|
48
|
+
return `${record.name.toLowerCase()}\u0000${record.type}\u0000${dataKey(record)}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function compareDevices(a: CastDevice, b: CastDevice): number {
|
|
52
|
+
if (a.name < b.name) return -1;
|
|
53
|
+
if (a.name > b.name) return 1;
|
|
54
|
+
if (a.id < b.id) return -1;
|
|
55
|
+
if (a.id > b.id) return 1;
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sortDevices(list: CastDevice[]): CastDevice[] {
|
|
60
|
+
return [...list].sort(compareDevices);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function deepEqual(a: unknown, b: unknown): boolean {
|
|
64
|
+
if (Object.is(a, b)) return true;
|
|
65
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
|
|
66
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
67
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
|
68
|
+
for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
const ao = a as Record<string, unknown>;
|
|
72
|
+
const bo = b as Record<string, unknown>;
|
|
73
|
+
const ak = Object.keys(ao);
|
|
74
|
+
const bk = Object.keys(bo);
|
|
75
|
+
if (ak.length !== bk.length) return false;
|
|
76
|
+
for (const k of ak) {
|
|
77
|
+
if (!Object.prototype.hasOwnProperty.call(bo, k) || !deepEqual(ao[k], bo[k])) return false;
|
|
78
|
+
}
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Parses the TXT `ca` value: a non-negative base-10 integer, or 0 otherwise. */
|
|
83
|
+
function parseCapabilities(raw: string | undefined): number {
|
|
84
|
+
if (typeof raw !== "string" || !/^\d+$/.test(raw)) return 0;
|
|
85
|
+
const n = Number(raw);
|
|
86
|
+
return Number.isSafeInteger(n) ? n : 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Deep copy of a device: fresh object, fresh arrays, fresh TXT map. */
|
|
90
|
+
function copyDevice(d: CastDevice): CastDevice {
|
|
91
|
+
return {
|
|
92
|
+
...d,
|
|
93
|
+
addresses: [...d.addresses],
|
|
94
|
+
txt: Object.assign(Object.create(null), d.txt) as Record<string, string>,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* TTL-aware cache that joins mDNS records into Cast devices. Pure: no timers,
|
|
100
|
+
* no network; callers pass the current time to every method.
|
|
101
|
+
*/
|
|
102
|
+
export class CastDeviceCache {
|
|
103
|
+
readonly serviceName: string;
|
|
104
|
+
private readonly stored: StoredRecord[] = [];
|
|
105
|
+
|
|
106
|
+
constructor(serviceName?: string) {
|
|
107
|
+
this.serviceName = serviceName ?? "_googlecast._tcp.local";
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Ingests a batch of records (in arrival order) and reports device changes. */
|
|
111
|
+
ingest(records: DnsRecord[], now: number): CacheChange {
|
|
112
|
+
const before = this.devices();
|
|
113
|
+
for (const record of records) this.store(record, now);
|
|
114
|
+
return this.diff(before);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Removes expired records and reports device changes. */
|
|
118
|
+
expire(now: number): CacheChange {
|
|
119
|
+
const before = this.devices();
|
|
120
|
+
this.stored.splice(0, this.stored.length, ...this.stored.filter((r) => now < r.expiresAt));
|
|
121
|
+
return this.diff(before);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Fresh, sorted copies of all currently known devices. */
|
|
125
|
+
devices(): CastDevice[] {
|
|
126
|
+
return this.snapshot().map(copyDevice);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private store(record: DnsRecord, now: number): void {
|
|
130
|
+
const key = keyOf(record);
|
|
131
|
+
if (record.ttl === 0) {
|
|
132
|
+
// Goodbye: drop the matching stored record, do not store it.
|
|
133
|
+
const idx = this.stored.findIndex((r) => keyOf(r.record) === key);
|
|
134
|
+
if (idx !== -1) this.stored.splice(idx, 1);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (record.cacheFlush) {
|
|
138
|
+
// RFC 6762 10.2: evict same name+type records received more than a second ago.
|
|
139
|
+
const name = record.name.toLowerCase();
|
|
140
|
+
this.stored.splice(
|
|
141
|
+
0,
|
|
142
|
+
this.stored.length,
|
|
143
|
+
...this.stored.filter(
|
|
144
|
+
(r) => !(r.record.name.toLowerCase() === name && r.record.type === record.type && now - r.receivedAt > 1000),
|
|
145
|
+
),
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
const entry = { record, receivedAt: now, expiresAt: now + record.ttl * 1000 };
|
|
149
|
+
const idx = this.stored.findIndex((r) => keyOf(r.record) === key);
|
|
150
|
+
if (idx !== -1) this.stored[idx] = entry;
|
|
151
|
+
else this.stored.push(entry);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Joins the stored records into devices, deduplicated by TXT id. */
|
|
155
|
+
private snapshot(): CastDevice[] {
|
|
156
|
+
const service = this.serviceName.toLowerCase();
|
|
157
|
+
const srvByInstance = new Map<string, { record: Extract<DnsRecord, { type: "SRV" }>; receivedAt: number }>();
|
|
158
|
+
const txtByInstance = new Map<string, { record: Extract<DnsRecord, { type: "TXT" }>; receivedAt: number }>();
|
|
159
|
+
const addrsByHost = new Map<string, { v4: string[]; v6: string[] }>();
|
|
160
|
+
for (const s of this.stored) {
|
|
161
|
+
const rec = s.record;
|
|
162
|
+
const name = rec.name.toLowerCase();
|
|
163
|
+
if (rec.type === "SRV") {
|
|
164
|
+
const prev = srvByInstance.get(name);
|
|
165
|
+
if (!prev || s.receivedAt >= prev.receivedAt) srvByInstance.set(name, { record: rec, receivedAt: s.receivedAt });
|
|
166
|
+
} else if (rec.type === "TXT") {
|
|
167
|
+
const prev = txtByInstance.get(name);
|
|
168
|
+
if (!prev || s.receivedAt >= prev.receivedAt) txtByInstance.set(name, { record: rec, receivedAt: s.receivedAt });
|
|
169
|
+
} else if (rec.type === "A" || rec.type === "AAAA") {
|
|
170
|
+
let list = addrsByHost.get(name);
|
|
171
|
+
if (!list) {
|
|
172
|
+
list = { v4: [], v6: [] };
|
|
173
|
+
addrsByHost.set(name, list);
|
|
174
|
+
}
|
|
175
|
+
(rec.type === "A" ? list.v4 : list.v6).push(rec.data);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const byId = new Map<string, { device: CastDevice; recency: number }>();
|
|
179
|
+
for (const s of this.stored) {
|
|
180
|
+
const ptr = s.record;
|
|
181
|
+
if (ptr.type !== "PTR" || ptr.name.toLowerCase() !== service) continue;
|
|
182
|
+
const instance = ptr.data;
|
|
183
|
+
const ik = instance.toLowerCase();
|
|
184
|
+
const srv = srvByInstance.get(ik);
|
|
185
|
+
const txt = txtByInstance.get(ik);
|
|
186
|
+
if (!srv || !txt) continue;
|
|
187
|
+
const id = txt.record.data["id"];
|
|
188
|
+
if (!id) continue;
|
|
189
|
+
const addrs = addrsByHost.get(srv.record.data.target.toLowerCase());
|
|
190
|
+
if (!addrs || (addrs.v4.length + addrs.v6.length) === 0) continue;
|
|
191
|
+
const txtData = txt.record.data;
|
|
192
|
+
const fn = txtData["fn"];
|
|
193
|
+
const dot = instance.indexOf(".");
|
|
194
|
+
const label = dot === -1 ? instance : instance.slice(0, dot);
|
|
195
|
+
const capabilities = parseCapabilities(txtData["ca"]);
|
|
196
|
+
const device: CastDevice = {
|
|
197
|
+
id,
|
|
198
|
+
name: fn && fn !== "" ? fn : label,
|
|
199
|
+
model: txtData["md"] ?? "",
|
|
200
|
+
host: addrs.v4[0] ?? addrs.v6[0] ?? "",
|
|
201
|
+
addresses: [...addrs.v4, ...addrs.v6],
|
|
202
|
+
port: srv.record.data.port,
|
|
203
|
+
capabilities,
|
|
204
|
+
isGroup: (capabilities & 32) !== 0,
|
|
205
|
+
statusText: txtData["rs"] ?? "",
|
|
206
|
+
instanceName: instance,
|
|
207
|
+
txt: Object.assign(Object.create(null), txtData) as Record<string, string>,
|
|
208
|
+
};
|
|
209
|
+
const recency = Math.max(s.receivedAt, srv.receivedAt, txt.receivedAt);
|
|
210
|
+
const existing = byId.get(id);
|
|
211
|
+
if (!existing || recency >= existing.recency) byId.set(id, { device, recency });
|
|
212
|
+
}
|
|
213
|
+
return sortDevices([...byId.values()].map((e) => e.device));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private diff(before: CastDevice[]): CacheChange {
|
|
217
|
+
const after = this.devices();
|
|
218
|
+
const beforeById = new Map<string, CastDevice>(before.map((d): [string, CastDevice] => [d.id, d]));
|
|
219
|
+
const afterById = new Map<string, CastDevice>(after.map((d): [string, CastDevice] => [d.id, d]));
|
|
220
|
+
const added: CastDevice[] = [];
|
|
221
|
+
const removed: CastDevice[] = [];
|
|
222
|
+
const updated: CastDevice[] = [];
|
|
223
|
+
for (const d of after) if (!beforeById.has(d.id)) added.push(d);
|
|
224
|
+
for (const d of before) if (!afterById.has(d.id)) removed.push(d);
|
|
225
|
+
for (const d of after) {
|
|
226
|
+
const prev = beforeById.get(d.id);
|
|
227
|
+
if (prev && !deepEqual(prev, d)) updated.push(d);
|
|
228
|
+
}
|
|
229
|
+
return { added: sortDevices(added), updated: sortDevices(updated), removed: sortDevices(removed) };
|
|
230
|
+
}
|
|
231
|
+
}
|