node-red-contrib-unifi-ultimate 1.1.3 → 1.1.5

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Massimo Saccani
3
+ Copyright (c) 2026 Massimo Saccani (maxsupergiovane@icloud.com)
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -78,6 +78,7 @@ Use **Network** nodes to work with:
78
78
  Things you can do:
79
79
 
80
80
  - Check whether a device or phone is connected to your network.
81
+ - Track presence either by the exact UniFi client ID or by client name; name matching tolerates private/rotating MAC addresses by resolving the active client again on every poll.
81
82
  - Re-send the current presence state at a fixed interval with the Presence node's **Resend** field (e.g. to keep a dashboard or home-automation system in sync).
82
83
  - Count how many clients are currently online.
83
84
  - List the site's configured networks, Wi-Fi broadcasts, and WAN interfaces.
@@ -183,7 +183,6 @@
183
183
  "type": "unifi-protect-config",
184
184
  "name": "My Protect",
185
185
  "host": "192.168.1.10",
186
- "authHeader": "X-API-Key",
187
186
  "rejectUnauthorized": false
188
187
  }
189
188
  ]
@@ -74,7 +74,6 @@
74
74
  "type": "unifi-protect-config",
75
75
  "name": "My Protect",
76
76
  "host": "192.168.1.10",
77
- "authHeader": "X-API-Key",
78
77
  "rejectUnauthorized": true
79
78
  },
80
79
  {
@@ -92,7 +92,6 @@
92
92
  "type": "unifi-protect-config",
93
93
  "name": "My Protect",
94
94
  "host": "192.168.1.10",
95
- "authHeader": "X-API-Key",
96
95
  "rejectUnauthorized": false
97
96
  }
98
97
  ]
@@ -850,7 +850,20 @@
850
850
  );
851
851
  });
852
852
 
853
- if (currentValue && $deviceId.find("option[value='" + currentValue + "']").length > 0) {
853
+ const hasCurrentValue = currentValue && $deviceId.find("option").filter(function () {
854
+ return String($(this).val() || "") === currentValue;
855
+ }).length > 0;
856
+ if (hasCurrentValue) {
857
+ $deviceId.val(currentValue);
858
+ } else if (currentValue) {
859
+ const savedName = String(node.deviceName || currentValue).trim();
860
+ $deviceId.append(
861
+ $("<option></option>")
862
+ .val(currentValue)
863
+ .text(savedName + " (saved; currently unavailable)")
864
+ .attr("data-device-name", savedName)
865
+ .attr("data-unavailable", "true")
866
+ );
854
867
  $deviceId.val(currentValue);
855
868
  } else {
856
869
  $deviceId.val("");
@@ -1069,6 +1082,7 @@
1069
1082
  });
1070
1083
 
1071
1084
  refreshSelectionSummary();
1085
+ renderDevices([]);
1072
1086
  ensureDefaultServerSelection();
1073
1087
  refreshEditor();
1074
1088
  }
@@ -1135,7 +1149,7 @@
1135
1149
 
1136
1150
  <h3>Configuration</h3>
1137
1151
  <p><b>Connection</b> selects the shared UniFi Access config node.</p>
1138
- <p><b>Control</b> chooses the Access category. <b>Device</b> chooses the specific door, device, visitor, policy, schedule, holiday group, door group, or recent system-log entry. Selectors are searchable and open with the complete list before filtering.</p>
1152
+ <p><b>Control</b> chooses the Access category. <b>Device</b> chooses the specific door, device, visitor, policy, schedule, holiday group, door group, or recent system-log entry. Selectors are searchable and open with the complete list before filtering. A saved selection that is temporarily unavailable is preserved instead of being cleared.</p>
1139
1153
  <p><b>Action</b> only shows actions supported by the selected item.</p>
1140
1154
  <p>Additional fields appear only when the selected action needs extra input, such as a temporary lock rule or a room name for doorbell actions.</p>
1141
1155
  <p>For <code>Set Temporary Lock Rule</code>, choose <code>Custom Duration</code> to reveal the minutes field. Legacy <code>ended_time</code> is still available only as fallback compatibility.</p>
@@ -24,9 +24,14 @@ const {
24
24
  resolveScopedIdentifiers,
25
25
  summarizeDevice
26
26
  } = require("./utils/unifi-network-device-registry");
27
+ const {
28
+ normalizePresenceMatchBy,
29
+ normalizeClientMatchName,
30
+ findActiveClientsByName,
31
+ resolveClientResourceId
32
+ } = require("./utils/unifi-network-presence-utils");
27
33
 
28
34
  module.exports = function(RED) {
29
- const API_KEY_HEADER = "X-API-Key";
30
35
  const MIN_POWER_OBSERVER_INTERVAL_SECONDS = 5;
31
36
  const DEFAULT_POWER_OBSERVER_INTERVAL_SECONDS = 15;
32
37
  const POWER_OBSERVER_SCHEDULER_TICK_MS = 1000;
@@ -311,7 +316,7 @@ module.exports = function(RED) {
311
316
  const normalizedPath = String(path || "").startsWith("/") ? String(path || "") : `/${String(path || "")}`;
312
317
  const requestUrl = new URL(`${node.baseUrl}${normalizedPath}${queryString}`);
313
318
  const requestMethod = String(method || "GET").toUpperCase();
314
- const requestHeaders = buildRequestHeaders(API_KEY_HEADER, apiKey, headers);
319
+ const requestHeaders = buildRequestHeaders(apiKey, headers);
315
320
  const requestBody = buildRequestBody(requestHeaders, requestMethod, payload);
316
321
 
317
322
  return doRequest(
@@ -351,7 +356,7 @@ module.exports = function(RED) {
351
356
  const legacyBaseUrl = node.baseUrl.replace(/\/integration\/?$/, "");
352
357
  const requestUrl = new URL(`${legacyBaseUrl}${normalizedPath}${queryString}`);
353
358
  const requestMethod = String(method || "GET").toUpperCase();
354
- const requestHeaders = buildRequestHeaders(API_KEY_HEADER, apiKey, headers);
359
+ const requestHeaders = buildRequestHeaders(apiKey, headers);
355
360
  const requestBody = buildRequestBody(requestHeaders, requestMethod, payload);
356
361
 
357
362
  return doRequest(
@@ -1433,7 +1438,7 @@ module.exports = function(RED) {
1433
1438
  return node.legacySiteNameById.get(normalizedSiteId) || "";
1434
1439
  }
1435
1440
 
1436
- async function fetchLegacySiteCollection(siteId, collectionPath) {
1441
+ async function fetchLegacySiteCollection(siteId, collectionPath, timeout) {
1437
1442
  const legacySiteName = await fetchLegacySiteName(siteId);
1438
1443
  if (!legacySiteName) {
1439
1444
  return [];
@@ -1441,7 +1446,8 @@ module.exports = function(RED) {
1441
1446
 
1442
1447
  const response = await node.legacyApiRequest({
1443
1448
  path: `/api/s/${encodeURIComponent(legacySiteName)}${collectionPath}`,
1444
- method: "GET"
1449
+ method: "GET",
1450
+ timeout: Number(timeout) > 0 ? Number(timeout) : 15000
1445
1451
  });
1446
1452
 
1447
1453
  if (response.statusCode < 200 || response.statusCode >= 300) {
@@ -1451,8 +1457,8 @@ module.exports = function(RED) {
1451
1457
  return normalizeNetworkCollection(response.payload);
1452
1458
  }
1453
1459
 
1454
- async function fetchLegacyClients(siteId) {
1455
- const clients = await fetchLegacySiteCollection(siteId, "/stat/sta");
1460
+ async function fetchLegacyClients(siteId, timeout) {
1461
+ const clients = await fetchLegacySiteCollection(siteId, "/stat/sta", timeout);
1456
1462
  return clients.map((client) => ({
1457
1463
  ...client,
1458
1464
  __unifiUltimateOnline: true,
@@ -2503,11 +2509,126 @@ module.exports = function(RED) {
2503
2509
  };
2504
2510
  };
2505
2511
 
2512
+ node.fetchActivePresenceClients = async (siteId, timeout) => {
2513
+ const normalizedSiteId = normalizeString(siteId);
2514
+ if (!normalizedSiteId) {
2515
+ throw new Error("Client selection is invalid. Re-select the client from the editor.");
2516
+ }
2517
+
2518
+ // Name matching needs the currently connected population, not the
2519
+ // historical known-client list. Query both sources so aliases and
2520
+ // hostnames remain available across controller/API versions.
2521
+ const results = await Promise.allSettled([
2522
+ node.fetchPagedCollection({
2523
+ path: `/v1/sites/${encodeURIComponent(normalizedSiteId)}/clients`,
2524
+ timeout: Number(timeout) > 0 ? Number(timeout) : 8000
2525
+ }),
2526
+ fetchLegacyClients(normalizedSiteId, Number(timeout) > 0 ? Number(timeout) : 8000)
2527
+ ]);
2528
+ const successful = results.filter((result) => result.status === "fulfilled");
2529
+ if (successful.length === 0) {
2530
+ const firstFailure = results.find((result) => result.status === "rejected");
2531
+ throw (firstFailure && firstFailure.reason) || new Error("Unable to load active clients.");
2532
+ }
2533
+
2534
+ const officialClients = results[0].status === "fulfilled" && Array.isArray(results[0].value)
2535
+ ? results[0].value
2536
+ : [];
2537
+ const legacyClients = results[1].status === "fulfilled" && Array.isArray(results[1].value)
2538
+ ? results[1].value
2539
+ : [];
2540
+
2541
+ return officialClients
2542
+ .map((client) => ({
2543
+ ...client,
2544
+ siteId: client && (client.siteId || client.site_id) || normalizedSiteId,
2545
+ isOnline: true,
2546
+ online: true,
2547
+ offline: false
2548
+ }))
2549
+ .concat(legacyClients.map((client) => ({
2550
+ ...client,
2551
+ siteId: client && (client.siteId || client.site_id) || normalizedSiteId,
2552
+ isOnline: true,
2553
+ online: true,
2554
+ offline: false
2555
+ })));
2556
+ };
2557
+
2558
+ node.fetchPresenceObservationSnapshotByName = async (clientId, clientName, timeout, activeClients) => {
2559
+ const scoped = resolveScopedIdentifiers("client", clientId);
2560
+ const normalizedClientName = normalizeString(clientName);
2561
+ if (!scoped.siteId || !normalizedClientName) {
2562
+ throw new Error("Client name selection is invalid. Re-select the client from the editor.");
2563
+ }
2564
+
2565
+ const clients = Array.isArray(activeClients)
2566
+ ? activeClients
2567
+ : await node.fetchActivePresenceClients(scoped.siteId, timeout);
2568
+ const matches = findActiveClientsByName(clients, normalizedClientName);
2569
+ if (matches.length === 0) {
2570
+ return {
2571
+ found: false,
2572
+ connected: false,
2573
+ statusCode: 404,
2574
+ client: null,
2575
+ matchBy: "name",
2576
+ clientName: normalizedClientName,
2577
+ matchCount: 0
2578
+ };
2579
+ }
2580
+
2581
+ // The official and legacy collections can describe the same active
2582
+ // client. Count unique identities so metadata is not inflated.
2583
+ const uniqueMatches = new Map();
2584
+ matches.forEach((client, index) => {
2585
+ const key = normalizeIdentifierKey(client && (client.macAddress || client.mac_address || client.mac))
2586
+ || normalizeIdentifierKey(resolveClientResourceId(client))
2587
+ || String(index);
2588
+ if (!uniqueMatches.has(key)) {
2589
+ uniqueMatches.set(key, client);
2590
+ }
2591
+ });
2592
+ const matchedClient = uniqueMatches.values().next().value;
2593
+ const matchedResourceId = resolveClientResourceId(matchedClient);
2594
+ const matchedClientId = encodeScopedDeviceId(scoped.siteId, matchedResourceId) || matchedResourceId;
2595
+
2596
+ return {
2597
+ found: true,
2598
+ connected: true,
2599
+ statusCode: 200,
2600
+ client: {
2601
+ ...matchedClient,
2602
+ siteId: matchedClient && (matchedClient.siteId || matchedClient.site_id) || scoped.siteId
2603
+ },
2604
+ matchBy: "name",
2605
+ clientName: normalizedClientName,
2606
+ matchCount: uniqueMatches.size,
2607
+ matchedClientId: matchedClientId || undefined
2608
+ };
2609
+ };
2610
+
2611
+ node.fetchPresenceObservationSnapshotForDescriptor = async (descriptor, activeClients) => {
2612
+ const matchBy = normalizePresenceMatchBy(descriptor && descriptor.matchBy);
2613
+ if (matchBy === "name") {
2614
+ return node.fetchPresenceObservationSnapshotByName(
2615
+ descriptor && descriptor.clientId,
2616
+ descriptor && descriptor.clientName,
2617
+ descriptor && descriptor.timeout,
2618
+ activeClients
2619
+ );
2620
+ }
2621
+ return node.fetchPresenceObservationSnapshot(
2622
+ descriptor && descriptor.clientId,
2623
+ descriptor && descriptor.timeout
2624
+ );
2625
+ };
2626
+
2506
2627
  node.requestPresenceObservationNow = async (descriptor) => {
2507
2628
  if (!descriptor || typeof descriptor !== "object") {
2508
2629
  throw new Error("Invalid presence descriptor.");
2509
2630
  }
2510
- const snapshot = await node.fetchPresenceObservationSnapshot(descriptor.clientId, descriptor.timeout);
2631
+ const snapshot = await node.fetchPresenceObservationSnapshotForDescriptor(descriptor);
2511
2632
  return {
2512
2633
  source: normalizeString(descriptor.source) || "manual-input",
2513
2634
  ...snapshot,
@@ -2542,9 +2663,14 @@ module.exports = function(RED) {
2542
2663
  }
2543
2664
 
2544
2665
  const clientId = normalizeString(descriptor.clientId);
2666
+ const matchBy = normalizePresenceMatchBy(descriptor.matchBy);
2667
+ const clientName = normalizeString(descriptor.clientName);
2545
2668
  const pollIntervalSeconds = Number(descriptor.pollIntervalSeconds);
2546
2669
  const timeout = Number(descriptor.timeout);
2547
- if (!clientId || !Number.isFinite(pollIntervalSeconds) || pollIntervalSeconds <= 0) {
2670
+ if (!clientId
2671
+ || (matchBy === "name" && !clientName)
2672
+ || !Number.isFinite(pollIntervalSeconds)
2673
+ || pollIntervalSeconds <= 0) {
2548
2674
  return null;
2549
2675
  }
2550
2676
 
@@ -2552,6 +2678,8 @@ module.exports = function(RED) {
2552
2678
  client,
2553
2679
  descriptor: {
2554
2680
  clientId,
2681
+ matchBy,
2682
+ clientName,
2555
2683
  pollIntervalMs: Math.max(1000, Math.trunc(pollIntervalSeconds * 1000)),
2556
2684
  timeout: Number.isFinite(timeout) && timeout > 0 ? Math.trunc(timeout) : 8000
2557
2685
  }
@@ -2634,9 +2762,14 @@ module.exports = function(RED) {
2634
2762
  }
2635
2763
 
2636
2764
  state.nextRunAt = now + entry.descriptor.pollIntervalMs;
2637
- const key = entry.descriptor.clientId;
2765
+ const scoped = resolveScopedIdentifiers("client", entry.descriptor.clientId);
2766
+ const key = entry.descriptor.matchBy === "name"
2767
+ ? `name::${scoped.siteId}::${normalizeClientMatchName(entry.descriptor.clientName)}`
2768
+ : `id::${entry.descriptor.clientId}`;
2638
2769
  const group = dueGroups.get(key) || {
2639
2770
  clientId: entry.descriptor.clientId,
2771
+ matchBy: entry.descriptor.matchBy,
2772
+ clientName: entry.descriptor.clientName,
2640
2773
  timeout: entry.descriptor.timeout,
2641
2774
  entries: []
2642
2775
  };
@@ -2645,10 +2778,22 @@ module.exports = function(RED) {
2645
2778
  dueGroups.set(key, group);
2646
2779
  });
2647
2780
 
2781
+ const activeClientsBySite = new Map();
2648
2782
  for (const group of dueGroups.values()) {
2649
2783
  let snapshot;
2650
2784
  try {
2651
- snapshot = await node.fetchPresenceObservationSnapshot(group.clientId, group.timeout);
2785
+ let activeClients;
2786
+ if (group.matchBy === "name") {
2787
+ const scoped = resolveScopedIdentifiers("client", group.clientId);
2788
+ if (!activeClientsBySite.has(scoped.siteId)) {
2789
+ activeClientsBySite.set(
2790
+ scoped.siteId,
2791
+ node.fetchActivePresenceClients(scoped.siteId, group.timeout)
2792
+ );
2793
+ }
2794
+ activeClients = await activeClientsBySite.get(scoped.siteId);
2795
+ }
2796
+ snapshot = await node.fetchPresenceObservationSnapshotForDescriptor(group, activeClients);
2652
2797
  } catch (error) {
2653
2798
  snapshot = {
2654
2799
  found: false,
@@ -2663,6 +2808,8 @@ module.exports = function(RED) {
2663
2808
  node.notifyPresenceObserverClient(entry.client, {
2664
2809
  source: "poll",
2665
2810
  clientId: group.clientId,
2811
+ matchBy: group.matchBy,
2812
+ clientName: group.clientName,
2666
2813
  ...snapshot
2667
2814
  });
2668
2815
  });
@@ -941,7 +941,20 @@
941
941
  $deviceId.append($option);
942
942
  });
943
943
 
944
- if (currentValue && $deviceId.find("option[value='" + currentValue + "']").length > 0) {
944
+ const hasCurrentValue = currentValue && $deviceId.find("option").filter(function () {
945
+ return String($(this).val() || "") === currentValue;
946
+ }).length > 0;
947
+ if (hasCurrentValue) {
948
+ $deviceId.val(currentValue);
949
+ } else if (currentValue) {
950
+ const savedName = String(node.deviceName || currentValue).trim();
951
+ $deviceId.append(
952
+ $("<option></option>")
953
+ .val(currentValue)
954
+ .text(savedName + " (saved; currently unavailable)")
955
+ .attr("data-device-name", savedName)
956
+ .attr("data-unavailable", "true")
957
+ );
945
958
  $deviceId.val(currentValue);
946
959
  } else {
947
960
  $deviceId.val("");
@@ -955,16 +968,28 @@
955
968
  }
956
969
 
957
970
  function renderDevicesLoading(label) {
971
+ const savedValue = getCurrentOrNodeValue($deviceId, node.deviceId, "");
972
+ const savedName = String(node.deviceName || savedValue).trim();
958
973
  clientTargetsLoading = isClientResourceSelected();
959
974
  clientTargetsPopulated = false;
960
975
  withSuppressedChanges(function () {
961
976
  $deviceId.empty();
962
- $deviceId.append(
963
- $("<option></option>")
964
- .val("")
965
- .text(label)
966
- );
967
- $deviceId.val("");
977
+ if (savedValue) {
978
+ $deviceId.append(
979
+ $("<option></option>")
980
+ .val(savedValue)
981
+ .text(savedName + " (loading...)")
982
+ .attr("data-device-name", savedName)
983
+ );
984
+ $deviceId.val(savedValue);
985
+ } else {
986
+ $deviceId.append(
987
+ $("<option></option>")
988
+ .val("")
989
+ .text(label)
990
+ );
991
+ $deviceId.val("");
992
+ }
968
993
  });
969
994
 
970
995
  makeSelectSearchable($deviceId, label);
@@ -1197,6 +1222,7 @@
1197
1222
  });
1198
1223
 
1199
1224
  refreshSelectionSummary();
1225
+ renderDevicesLoading("Loading items, please wait...");
1200
1226
  ensureDefaultServerSelection();
1201
1227
  $refresh.find("i").addClass("fa-spin");
1202
1228
  refreshEditor();
@@ -1265,7 +1291,7 @@
1265
1291
  <h3>Configuration</h3>
1266
1292
  <p><b>Connection</b> selects the shared UniFi Network config node.</p>
1267
1293
  <p><b>Resource</b> chooses what you want to work with: Site, UniFi Device, or Client.</p>
1268
- <p><b>Item</b> chooses the specific site, device, or client. Device and client selectors are searchable and open with the complete list before filtering.</p>
1294
+ <p><b>Item</b> chooses the specific site, device, or client. Device and client selectors are searchable and open with the complete list before filtering. A saved selection that is offline or temporarily unavailable is preserved instead of being cleared.</p>
1269
1295
  <p><b>Action</b> only shows actions supported by the selected resource. Additional fields appear only when the selected action needs extra input.</p>
1270
1296
  <p>Action highlights include <code>Count Online Clients</code>, <code>List Networks</code>, <code>List Wi-Fi Broadcasts</code>, <code>List WAN Interfaces</code>, <code>List VPN Servers</code>, <code>List Site-to-Site VPN Tunnels</code>, <code>List Guest Vouchers</code>, <code>Create Guest Voucher</code>, <code>Read CPU</code>, <code>Read Memory</code>, <code>Read Uptime</code>, <code>Read Temperatures</code>, <code>Is Client Online</code>, <code>Restart Device</code>, and <code>Power Cycle Port</code>.</p>
1271
1297
  <p><code>Read Application Info</code> is available on the <code>Site</code> resource type and returns Network application metadata.</p>
@@ -17,6 +17,18 @@
17
17
  return (self && self.watchBy) ? String(self.watchBy).trim() : "presence";
18
18
  }
19
19
 
20
+ function currentPresenceMatchByValue(self) {
21
+ try {
22
+ const live = $("#node-input-matchBy").val();
23
+ if (live) {
24
+ return String(live).trim();
25
+ }
26
+ } catch (error) {
27
+ // jQuery/DOM not available in this context.
28
+ }
29
+ return (self && self.matchBy) ? String(self.matchBy).trim() : "id";
30
+ }
31
+
20
32
  RED.nodes.registerType("unifi-network-presence", {
21
33
  category: "Unifi Ultimate",
22
34
  color: "#CFE8FB",
@@ -24,6 +36,7 @@
24
36
  name: { value: "" },
25
37
  server: { value: "", type: "unifi-network-config", required: true },
26
38
  watchBy: { value: "presence", required: true },
39
+ matchBy: { value: "id", required: true },
27
40
  clientId: {
28
41
  value: "",
29
42
  validate: function (v) {
@@ -31,6 +44,16 @@
31
44
  return mode === "network" ? true : String(v || "").trim() !== "";
32
45
  }
33
46
  },
47
+ clientName: {
48
+ value: "",
49
+ validate: function (v) {
50
+ const mode = currentWatchByValue(this);
51
+ const matchBy = currentPresenceMatchByValue(this);
52
+ return mode !== "presence" || matchBy !== "name"
53
+ ? true
54
+ : String(v || this.deviceName || "").trim() !== "";
55
+ }
56
+ },
34
57
  deviceName: { value: "" },
35
58
  pollInterval: { value: 10, required: true, validate: RED.validators.number() },
36
59
  onlineHysteresis: { value: 15, required: true, validate: RED.validators.number() },
@@ -54,12 +77,12 @@
54
77
  paletteLabel: "Presence Detection",
55
78
  outputLabels: ["result", "error"],
56
79
  label: function () {
57
- if (this.name) {
58
- return this.name;
59
- }
60
80
  if (this.watchBy === "network" && this.networkName) {
61
81
  return this.networkName;
62
82
  }
83
+ if (this.watchBy !== "network" && (this.clientName || this.deviceName)) {
84
+ return this.clientName || this.deviceName;
85
+ }
63
86
  return "Presence Detection";
64
87
  },
65
88
  oneditsave: function () {
@@ -70,28 +93,42 @@
70
93
  const $selected = $("#node-input-networkId option:selected");
71
94
  this.networkName = String($selected.attr("data-network-name") || "").trim();
72
95
  $("#node-input-networkName").val(this.networkName);
96
+ } else {
97
+ const selectedClientName = String($("#node-input-clientId option:selected").attr("data-client-name") || "").trim();
98
+ const configuredClientName = String($("#node-input-clientName").val() || "").trim();
99
+ if (selectedClientName) {
100
+ this.deviceName = selectedClientName;
101
+ $("#node-input-deviceName").val(selectedClientName);
102
+ }
103
+ this.clientName = configuredClientName || selectedClientName;
104
+ $("#node-input-clientName").val(this.clientName);
73
105
  }
74
106
  },
75
107
  oneditprepare: function () {
76
108
  const node = this;
77
- const $name = $("#node-input-name");
78
109
  const $server = $("#node-input-server");
79
110
  const $watchBy = $("#node-input-watchBy");
111
+ const $matchBy = $("#node-input-matchBy");
80
112
  const $clientId = $("#node-input-clientId");
113
+ const $clientName = $("#node-input-clientName");
81
114
  const $deviceName = $("#node-input-deviceName");
82
115
  const $refresh = $("#node-input-refreshClients");
83
116
  const $clientRow = $clientId.closest(".form-row");
117
+ const $clientNameRow = $("#node-row-clientName");
84
118
  const $advancedRow = $("#node-row-advanced");
85
119
  // Network-mode controls.
86
120
  const $networkId = $("#node-input-networkId");
87
121
  const $refreshNetworks = $("#node-input-refreshNetworks");
88
122
  const $watchByRow = $("#node-row-watchBy");
123
+ const $matchByRow = $("#node-row-matchBy");
89
124
  const $networkRow = $("#node-row-networkId");
90
125
  const $networkStatus = $("#unifi-presence-network-status");
91
126
  let suspendChangeHandling = false;
92
127
  let loadedNetworksServerId = "";
93
128
 
94
129
  $watchBy.val(this.watchBy || "presence");
130
+ $matchBy.val(this.matchBy || "id");
131
+ $clientName.val(this.clientName || this.deviceName || "");
95
132
 
96
133
  function currentMode() {
97
134
  return String($watchBy.val() || "presence").trim();
@@ -108,7 +145,9 @@
108
145
  const hasTarget = isNetwork ? hasSelection($networkId) : hasSelection($clientId);
109
146
 
110
147
  $watchByRow.toggle(hasServer);
148
+ $matchByRow.toggle(hasServer && !isNetwork);
111
149
  $clientRow.toggle(hasServer && !isNetwork);
150
+ $clientNameRow.toggle(hasServer && !isNetwork && hasSelection($clientId));
112
151
  $networkRow.toggle(hasServer && isNetwork);
113
152
  $advancedRow.toggle(hasServer && hasTarget);
114
153
  // Tuning rows depend on the active mode.
@@ -137,7 +176,48 @@
137
176
  $("<option></option>").val(id).text(name + suffix).attr("data-network-name", name)
138
177
  );
139
178
  });
140
- $networkId.val(currentValue && $networkId.find("option[value='" + currentValue + "']").length > 0 ? currentValue : "");
179
+ const hasCurrentValue = currentValue && $networkId.find("option").filter(function () {
180
+ return String($(this).val() || "") === currentValue;
181
+ }).length > 0;
182
+ if (hasCurrentValue) {
183
+ $networkId.val(currentValue);
184
+ } else if (currentValue) {
185
+ const savedName = String(node.networkName || currentValue).trim();
186
+ $networkId.append(
187
+ $("<option></option>")
188
+ .val(currentValue)
189
+ .text(savedName + " (saved; currently unavailable)")
190
+ .attr("data-network-name", savedName)
191
+ .attr("data-unavailable", "true")
192
+ );
193
+ $networkId.val(currentValue);
194
+ } else {
195
+ $networkId.val("");
196
+ }
197
+ } finally {
198
+ suspendChangeHandling = false;
199
+ }
200
+ syncProgressiveRows();
201
+ }
202
+
203
+ function renderNetworksLoading() {
204
+ const savedValue = String($networkId.val() || node.networkId || "").trim();
205
+ const savedName = String(node.networkName || savedValue).trim();
206
+ suspendChangeHandling = true;
207
+ try {
208
+ $networkId.empty();
209
+ if (savedValue) {
210
+ $networkId.append(
211
+ $("<option></option>")
212
+ .val(savedValue)
213
+ .text(savedName + " (loading...)")
214
+ .attr("data-network-name", savedName)
215
+ );
216
+ $networkId.val(savedValue);
217
+ } else {
218
+ $networkId.append($('<option></option>').val("").text("Loading networks..."));
219
+ $networkId.val("");
220
+ }
141
221
  } finally {
142
222
  suspendChangeHandling = false;
143
223
  }
@@ -156,6 +236,7 @@
156
236
  }
157
237
  $networkStatus.text("Loading networks...");
158
238
  $refreshNetworks.find("i").addClass("fa-spin");
239
+ renderNetworksLoading();
159
240
  loadedNetworksServerId = serverId;
160
241
  return requestJson("unifiNetwork/networks?serverId=" + encodeURIComponent(serverId))
161
242
  .then(function (networks) {
@@ -446,7 +527,9 @@
446
527
 
447
528
  if (serverId && serverId !== "_ADD_") {
448
529
  summary = "Choose the client to monitor.";
449
- detail = "Presence checks are scheduled by the shared Network config node using UniFi Network data.";
530
+ detail = $matchBy.val() === "name"
531
+ ? "The active client is matched by alias or hostname on every poll."
532
+ : "The selected UniFi client ID is checked on every poll.";
450
533
  }
451
534
 
452
535
  if (clientName) {
@@ -456,22 +539,16 @@
456
539
  syncProgressiveRows();
457
540
  }
458
541
 
459
- function syncNameFromSelection() {
460
- const clientName = getSelectedClientName();
461
- if (!clientName) {
462
- return;
463
- }
464
-
465
- $name.val(clientName);
466
- }
467
-
468
- function rememberSelectedClientName() {
542
+ function rememberSelectedClientName(forceTargetName) {
469
543
  const clientName = getSelectedClientName();
470
544
  if (!clientName) {
471
545
  return;
472
546
  }
473
547
 
474
548
  $deviceName.val(clientName);
549
+ if (forceTargetName || !String($clientName.val() || "").trim()) {
550
+ $clientName.val(clientName);
551
+ }
475
552
  }
476
553
 
477
554
  function renderClients(items) {
@@ -500,7 +577,28 @@
500
577
  $clientId.append($option);
501
578
  });
502
579
 
503
- if (currentValue && $clientId.find("option[value='" + currentValue + "']").length > 0) {
580
+ const hasCurrentValue = currentValue && $clientId.find("option").filter(function () {
581
+ return String($(this).val() || "") === currentValue;
582
+ }).length > 0;
583
+ if (hasCurrentValue) {
584
+ $clientId.val(currentValue);
585
+ const loadedClientName = getSelectedClientName();
586
+ if (loadedClientName) {
587
+ $clientName.val(loadedClientName);
588
+ $deviceName.val(loadedClientName);
589
+ }
590
+ } else if (currentValue) {
591
+ // Never discard a saved target just because the controller
592
+ // omitted it from this refresh. Keeping a synthetic option
593
+ // prevents opening/saving the editor from erasing clientId.
594
+ const savedName = String($clientName.val() || node.clientName || node.deviceName || currentValue).trim();
595
+ $clientId.append(
596
+ $("<option></option>")
597
+ .val(currentValue)
598
+ .text(savedName + " (saved; currently unavailable)")
599
+ .attr("data-client-name", savedName)
600
+ .attr("data-unavailable", "true")
601
+ );
504
602
  $clientId.val(currentValue);
505
603
  } else {
506
604
  $clientId.val("");
@@ -510,20 +608,32 @@
510
608
  }
511
609
 
512
610
  makeSelectSearchable($clientId, "Search clients");
513
- rememberSelectedClientName();
611
+ rememberSelectedClientName(false);
514
612
  refreshSummary();
515
613
  }
516
614
 
517
615
  function renderClientsLoading() {
616
+ const savedValue = String($clientId.val() || node.clientId || "").trim();
617
+ const savedName = String($clientName.val() || node.clientName || node.deviceName || savedValue).trim();
518
618
  suspendChangeHandling = true;
519
619
  try {
520
620
  $clientId.empty();
521
- $clientId.append(
522
- $("<option></option>")
523
- .val("")
524
- .text("Loading clients, please wait...")
525
- );
526
- $clientId.val("");
621
+ if (savedValue) {
622
+ $clientId.append(
623
+ $("<option></option>")
624
+ .val(savedValue)
625
+ .text(savedName + " (loading...)")
626
+ .attr("data-client-name", savedName)
627
+ );
628
+ $clientId.val(savedValue);
629
+ } else {
630
+ $clientId.append(
631
+ $("<option></option>")
632
+ .val("")
633
+ .text("Loading clients, please wait...")
634
+ );
635
+ $clientId.val("");
636
+ }
527
637
  } finally {
528
638
  suspendChangeHandling = false;
529
639
  }
@@ -580,12 +690,8 @@
580
690
  if (suspendChangeHandling) {
581
691
  return;
582
692
  }
583
- rememberSelectedClientName();
584
- const isUserSelection = $clientId.data("unifi-user-selection") === true;
693
+ rememberSelectedClientName(true);
585
694
  $clientId.removeData("unifi-user-selection");
586
- if (isUserSelection) {
587
- syncNameFromSelection();
588
- }
589
695
  refreshSummary();
590
696
  });
591
697
 
@@ -603,6 +709,14 @@
603
709
  }
604
710
  });
605
711
 
712
+ $matchBy.on("change", function () {
713
+ refreshSummary();
714
+ });
715
+
716
+ $clientName.on("input change", function () {
717
+ refreshSummary();
718
+ });
719
+
606
720
  $networkId.on("change", function () {
607
721
  if (suspendChangeHandling) {
608
722
  return;
@@ -650,6 +764,13 @@
650
764
  <option value="network">Network (join/leave)</option>
651
765
  </select>
652
766
  </div>
767
+ <div class="form-row" id="node-row-matchBy" style="display:none;">
768
+ <label for="node-input-matchBy"><i class="fa fa-id-card-o"></i> Identify by</label>
769
+ <select id="node-input-matchBy">
770
+ <option value="id">Client ID</option>
771
+ <option value="name">Client name</option>
772
+ </select>
773
+ </div>
653
774
  <div class="form-row" id="node-row-clientId">
654
775
  <label for="node-input-clientId"><i class="fa fa-wifi"></i> Client</label>
655
776
  <select id="node-input-clientId" style="width:62%;"></select>
@@ -666,9 +787,10 @@
666
787
  <div id="unifi-presence-network-status" class="unifi-presence-network-status"></div>
667
788
  </div>
668
789
  <div id="node-row-advanced" class="unifi-ultimate-advanced">
669
- <div class="form-row">
670
- <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
671
- <input type="text" id="node-input-name" placeholder="Node name">
790
+ <div class="form-row" id="node-row-clientName" style="display:none;">
791
+ <label for="node-input-clientName"><i class="fa fa-font"></i> Match name</label>
792
+ <input type="text" id="node-input-clientName" readonly>
793
+ <div class="form-tips">Read-only value copied from the selected client. It is used when Identify by is set to Client name.</div>
672
794
  </div>
673
795
  <div id="node-presence-tuning">
674
796
  <div class="form-row">
@@ -694,6 +816,7 @@
694
816
  <input type="checkbox" id="node-input-emitInitial" style="display:inline-block; width:auto; vertical-align:top;">
695
817
  </div>
696
818
  </div>
819
+ <input type="hidden" id="node-input-name">
697
820
  <input type="hidden" id="node-input-deviceName">
698
821
  <input type="hidden" id="node-input-networkName">
699
822
  <input type="hidden" id="node-input-joinConfirmPolls">
@@ -712,6 +835,8 @@
712
835
 
713
836
  <h4>Single client (presence)</h4>
714
837
  <p><b>Client</b> selects the client to track. The selector is searchable and opens with the complete list before filtering. Each entry shows the user-defined client name (e.g. "iPhone di Massimo") when set, otherwise the device hostname. Known-but-offline clients are included too and marked with an <code>(offline)</code> label, so you can pick a target even while it is disconnected.</p>
838
+ <p><b>Identify by</b> controls how the selected client is found. <b>Client ID</b> (default) tracks the exact UniFi record and is the safest choice for most devices. <b>Client name</b> searches the currently connected clients by alias, display name, or hostname on every poll, so presence continues to work when a privacy-enabled device rotates its MAC address and UniFi assigns it a new client ID. The read-only <b>Match name</b> value is copied from the client selected above. Name matching is exact but case-insensitive; give devices unique names because any online client with the same name counts as present.</p>
839
+ <p>If a saved client is temporarily missing from the controller response, the editor keeps it as <code>saved; currently unavailable</code> instead of clearing the configuration.</p>
715
840
  <p><b>Connect Hysteresis (s)</b> delays the <code>true</code> output so brief reconnects do not flap. <b>Hysteresis (s)</b> delays the <code>false</code> output. <b>Resend (s)</b> optionally re-emits the last saved value on a fixed cadence (<code>0</code> = off); resent messages carry <code>msg.eventName = "repeat"</code>.</p>
716
841
 
717
842
  <h4>Network (join/leave)</h4>
@@ -726,7 +851,7 @@
726
851
  </ul>
727
852
  <p>The node reports the controller's data faithfully and applies a small built-in debounce, but it cannot fully remove this upstream noise. If duplicates are a problem, debounce in your flow — for example an <code>rbe</code> ("block unless value changes") node, or a <code>delay</code> node in rate-limit mode, keyed on <code>msg.deviceName</code>/<code>msg.payload.mac</code>.</p>
728
853
 
729
- <p>In <b>presence</b> mode, <b>Poll (s)</b> sets the check cadence. <b>Name</b> is the node name shown in the editor. Request timeout is handled automatically.</p>
854
+ <p>In <b>presence</b> mode, <b>Poll (s)</b> sets the check cadence. Request timeout is handled automatically.</p>
730
855
 
731
856
  <h3>Input</h3>
732
857
  <ul>
@@ -794,4 +919,4 @@
794
919
  font-size: 0.85em;
795
920
  color: var(--red-ui-text-color-error, #b30000);
796
921
  }
797
- </style>
922
+ </style>
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const { decodeScopedDeviceId } = require("./utils/unifi-network-device-registry");
4
+ const { normalizePresenceMatchBy } = require("./utils/unifi-network-presence-utils");
4
5
  const {
5
6
  buildStatusTimestampText,
6
7
  appendStatusTimestamp,
@@ -277,6 +278,11 @@ module.exports = function(RED) {
277
278
  }
278
279
 
279
280
  node.clientId = config.clientId || "";
281
+ // Existing flows keep the historical ID-based behavior. Name matching
282
+ // deliberately resolves the active client again on every poll, allowing
283
+ // privacy-addressed devices to rotate their MAC/resource id.
284
+ node.matchBy = normalizePresenceMatchBy(config.matchBy);
285
+ node.clientName = normalizeString(config.clientName || config.deviceName);
280
286
  node.pollIntervalSeconds = parsePositiveSeconds(config.pollInterval, 10);
281
287
  node.onlineHysteresisSeconds = parseNonNegativeSeconds(config.onlineHysteresis, 15);
282
288
  node.offlineHysteresisSeconds = parseNonNegativeSeconds(config.offlineHysteresis, 30);
@@ -293,6 +299,8 @@ module.exports = function(RED) {
293
299
  node.firstOnlineDetectedAt = 0;
294
300
  node.firstOfflineDetectedAt = 0;
295
301
  node.lastKnownClient = null;
302
+ node.lastMatchedClientId = "";
303
+ node.lastMatchCount = 0;
296
304
 
297
305
  function setNodeStatus(status) {
298
306
  if (!status || typeof status !== "object" || Array.isArray(status)) {
@@ -341,6 +349,10 @@ module.exports = function(RED) {
341
349
  name: nodeName || undefined,
342
350
  deviceName: resolvedDeviceName || undefined,
343
351
  clientId,
352
+ matchBy: node.matchBy,
353
+ clientName: node.matchBy === "name" ? node.clientName || undefined : undefined,
354
+ matchedClientId: node.lastMatchedClientId || undefined,
355
+ matchCount: node.matchBy === "name" ? node.lastMatchCount : undefined,
344
356
  siteId: scoped.siteId || undefined,
345
357
  resourceId: scoped.resourceId || undefined,
346
358
  source,
@@ -469,6 +481,14 @@ module.exports = function(RED) {
469
481
  const client = snapshot && snapshot.client && typeof snapshot.client === "object" && !Array.isArray(snapshot.client)
470
482
  ? snapshot.client
471
483
  : null;
484
+ if (node.matchBy === "name") {
485
+ node.lastMatchCount = Number.isFinite(Number(snapshot && snapshot.matchCount))
486
+ ? Math.max(0, Math.trunc(Number(snapshot.matchCount)))
487
+ : 0;
488
+ if (normalizeString(snapshot && snapshot.matchedClientId)) {
489
+ node.lastMatchedClientId = normalizeString(snapshot.matchedClientId);
490
+ }
491
+ }
472
492
  if (client) {
473
493
  node.lastKnownClient = client;
474
494
  }
@@ -507,6 +527,8 @@ module.exports = function(RED) {
507
527
  }
508
528
  return node.server.requestPresenceObservationNow({
509
529
  clientId,
530
+ matchBy: node.matchBy,
531
+ clientName: node.clientName,
510
532
  timeout: node.timeout,
511
533
  source: source || "manual-input"
512
534
  });
@@ -587,6 +609,8 @@ module.exports = function(RED) {
587
609
  }
588
610
  return {
589
611
  clientId,
612
+ matchBy: node.matchBy,
613
+ clientName: node.clientName,
590
614
  pollIntervalSeconds: node.pollIntervalSeconds,
591
615
  timeout: node.timeout
592
616
  };
@@ -606,6 +630,8 @@ module.exports = function(RED) {
606
630
  setNodeStatus({ fill: "red", shape: "ring", text: "no config" });
607
631
  } else if (!node.clientId) {
608
632
  setNodeStatus({ fill: "grey", shape: "ring", text: "set client" });
633
+ } else if (node.matchBy === "name" && !node.clientName) {
634
+ setNodeStatus({ fill: "grey", shape: "ring", text: "set client name" });
609
635
  } else {
610
636
  if (node.server && typeof node.server.addClient === "function") {
611
637
  node.server.addClient(node);
@@ -58,6 +58,15 @@
58
58
  }
59
59
  }
60
60
 
61
+ function parseStoredNames() {
62
+ try {
63
+ const parsed = JSON.parse(String(node.deviceNames || "{}"));
64
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
65
+ } catch (error) {
66
+ return {};
67
+ }
68
+ }
69
+
61
70
  function hasSelection($field) {
62
71
  return String($field.val() || "").trim() !== "";
63
72
  }
@@ -101,16 +110,12 @@
101
110
  const hasStoredSelection = storedIds.length > 0;
102
111
  const storedSet = {};
103
112
  storedIds.forEach(function (id) { storedSet[id] = true; });
113
+ const storedNames = parseStoredNames();
114
+ const renderedSet = {};
104
115
 
105
116
  $list.empty();
106
117
 
107
- if (!Array.isArray(items) || items.length === 0) {
108
- $list.append($("<div class='unifi-restart-empty'></div>").text("No UniFi Network devices found."));
109
- updateSelectedCount();
110
- return;
111
- }
112
-
113
- items
118
+ (Array.isArray(items) ? items : [])
114
119
  .slice()
115
120
  .sort(function (a, b) {
116
121
  return String(a.name || a.id).localeCompare(String(b.name || b.id));
@@ -120,6 +125,7 @@
120
125
  if (!id) {
121
126
  return;
122
127
  }
128
+ renderedSet[id] = true;
123
129
  const name = String(item.name || id).trim();
124
130
  const model = String(item.state || "").trim();
125
131
  const checked = hasStoredSelection ? Boolean(storedSet[id]) : !isGatewayLike(item);
@@ -139,6 +145,30 @@
139
145
  $list.append($row);
140
146
  });
141
147
 
148
+ // Keep configured devices that are missing from this controller
149
+ // response. Otherwise opening and saving the editor would silently
150
+ // delete an offline or temporarily unavailable target.
151
+ storedIds.forEach(function (id) {
152
+ if (renderedSet[id]) {
153
+ return;
154
+ }
155
+ const name = String(storedNames[id] || id).trim();
156
+ const $row = $("<label class='unifi-restart-device-row unifi-restart-device-unavailable'></label>");
157
+ const $checkbox = $("<input type='checkbox'>")
158
+ .attr("data-id", id)
159
+ .attr("data-name", name)
160
+ .prop("checked", true);
161
+ $checkbox.on("change", updateSelectedCount);
162
+ $row.append($checkbox);
163
+ $row.append($("<span class='unifi-restart-device-name'></span>").text(name));
164
+ $row.append($("<span class='unifi-restart-device-model'></span>").text("saved; currently unavailable"));
165
+ $list.append($row);
166
+ });
167
+
168
+ if ($list.find("input[type='checkbox']").length === 0) {
169
+ $list.append($("<div class='unifi-restart-empty'></div>").text("No UniFi Network devices found."));
170
+ }
171
+
142
172
  applyFilter();
143
173
  updateSelectedCount();
144
174
  }
@@ -158,9 +188,8 @@
158
188
  function loadDevices(force) {
159
189
  const serverId = String($server.val() || "").trim();
160
190
  if (!serverId || serverId === "_ADD_") {
161
- $list.empty();
191
+ renderDevices([]);
162
192
  $status.text("");
163
- updateSelectedCount();
164
193
  return Promise.resolve();
165
194
  }
166
195
 
@@ -169,6 +198,9 @@
169
198
  }
170
199
 
171
200
  $status.text("Loading devices...");
201
+ if ($list.find("input[type='checkbox']").length === 0) {
202
+ renderDevices([]);
203
+ }
172
204
  loadedServerId = serverId;
173
205
  loadingPromise = requestJson("unifiNetwork/devices?serverId=" + encodeURIComponent(serverId) + "&deviceType=device")
174
206
  .then(function (devices) {
@@ -176,7 +208,7 @@
176
208
  $status.text("");
177
209
  })
178
210
  .catch(function (xhr) {
179
- $list.empty();
211
+ renderDevices([]);
180
212
  const message = xhr && xhr.responseJSON && xhr.responseJSON.error
181
213
  ? xhr.responseJSON.error
182
214
  : "Unable to load devices.";
@@ -278,7 +310,7 @@
278
310
  <li><code>Restart devices</code> — reboots each selected device (UniFi <code>RESTART</code> action).</li>
279
311
  <li><code>Power cycle PoE ports</code> — power-cycles every port currently delivering PoE on each selected device (UniFi <code>POWER_CYCLE</code> action). Devices with no active PoE ports are skipped.</li>
280
312
  </ul>
281
- <p><b>Devices</b> lists every adopted UniFi Network device. By default switches and access points are pre-selected; gateways, consoles and cloud keys are listed but unchecked. Add or remove devices freely — the selection is saved with the node. Use <code>All</code>/<code>None</code> and the filter box to manage long lists.</p>
313
+ <p><b>Devices</b> lists every adopted UniFi Network device. By default switches and access points are pre-selected; gateways, consoles and cloud keys are listed but unchecked. Add or remove devices freely — the selection is saved with the node. A configured device missing from the current controller response remains checked and is marked as <code>saved; currently unavailable</code>. Use <code>All</code>/<code>None</code> and the filter box to manage long lists.</p>
282
314
 
283
315
  <h3>Input</h3>
284
316
  <ul>
@@ -18,7 +18,6 @@
18
18
  return /^\d+$/.test(String(value)) && Number(value) >= 1 && Number(value) <= 65535;
19
19
  }
20
20
  },
21
- authHeader: { value: "X-API-Key", required: true },
22
21
  rejectUnauthorized: { value: false }
23
22
  },
24
23
  credentials: {
@@ -105,10 +104,6 @@
105
104
  <label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
106
105
  <input type="text" id="node-config-input-name" placeholder="Node name">
107
106
  </div>
108
- <div class="form-row">
109
- <label for="node-config-input-authHeader"><i class="fa fa-header"></i> API Header</label>
110
- <input type="text" id="node-config-input-authHeader" placeholder="X-API-Key">
111
- </div>
112
107
  </div>
113
108
  </script>
114
109
 
@@ -120,12 +115,11 @@
120
115
  <h3>Configuration</h3>
121
116
  <p><b>Controller</b> accepts the UniFi OS host or IP address. The node builds the Protect integration URL automatically.</p>
122
117
  <p><b>Port</b> is optional. Leave it empty to use the default <code>443</code>. Set it when your UniFi OS server listens on a custom port (for example <code>11443</code>). A port embedded directly in the Controller field (<code>host:port</code>) takes precedence over this field.</p>
123
- <p><b>API Key</b> is required for authentication.</p>
118
+ <p><b>API Key</b> is required for authentication and is sent automatically as <code>X-API-Key</code>.</p>
124
119
  <p><b>Security</b> &mdash; <b>Allow self-signed certificate</b> is enabled by default because UniFi controllers almost always present a self-signed certificate. Leave it checked for UniFi OS setups. Uncheck it only if your controller serves a certificate signed by a trusted certificate authority and you want strict verification.</p>
125
120
  <p><b>Name</b> is the config node name shown in the editor.</p>
126
- <p><b>API Header</b> is an advanced field. Leave the default value unless your UniFi Protect setup expects a different header name.</p>
127
121
 
128
122
  <h3>Usage</h3>
129
123
  <p>This config node is used by UniFi Protect Device nodes for API requests and live device/event updates.</p>
130
124
  <p>All Protect API calls and websocket streams are managed by this config node. Runtime nodes subscribe through <code>addClient/removeClient</code> and receive broadcast updates.</p>
131
- </script>
125
+ </script>
@@ -27,7 +27,6 @@ module.exports = function(RED) {
27
27
  node.host = String(config.host || "").trim();
28
28
  node.port = normalizePort(config.port);
29
29
  node.baseUrl = buildBaseUrlFromHost(node.host, node.port);
30
- node.authHeader = (config.authHeader || "X-API-Key").trim() || "X-API-Key";
31
30
  // UniFi controllers almost always use self-signed certificates, so accept
32
31
  // them unless the user explicitly opted into strict verification.
33
32
  node.rejectUnauthorized = config.rejectUnauthorized === true || config.rejectUnauthorized === "true";
@@ -62,7 +61,7 @@ module.exports = function(RED) {
62
61
  const normalizedPath = String(path || "").startsWith("/") ? String(path || "") : `/${String(path || "")}`;
63
62
  const requestUrl = new URL(`${node.baseUrl}${normalizedPath}${queryString}`);
64
63
  const requestMethod = String(method || "GET").toUpperCase();
65
- const requestHeaders = buildRequestHeaders(node.authHeader, apiKey, headers);
64
+ const requestHeaders = buildRequestHeaders(apiKey, headers);
66
65
  const requestBody = buildRequestBody(requestHeaders, requestMethod, payload);
67
66
 
68
67
  return doRequest(
@@ -220,7 +219,7 @@ module.exports = function(RED) {
220
219
  try {
221
220
  ws = new WebSocket(node.buildWebSocketUrl(path), {
222
221
  headers: {
223
- [node.authHeader]: apiKey,
222
+ "X-API-Key": apiKey,
224
223
  Accept: "application/json"
225
224
  },
226
225
  rejectUnauthorized: node.rejectUnauthorized
@@ -861,7 +861,20 @@
861
861
  );
862
862
  });
863
863
 
864
- if (currentValue && $deviceId.find("option[value='" + currentValue + "']").length > 0) {
864
+ const hasCurrentValue = currentValue && $deviceId.find("option").filter(function () {
865
+ return String($(this).val() || "") === currentValue;
866
+ }).length > 0;
867
+ if (hasCurrentValue) {
868
+ $deviceId.val(currentValue);
869
+ } else if (currentValue) {
870
+ const savedName = String(node.deviceName || currentValue).trim();
871
+ $deviceId.append(
872
+ $("<option></option>")
873
+ .val(currentValue)
874
+ .text(savedName + " (saved; currently unavailable)")
875
+ .attr("data-device-name", savedName)
876
+ .attr("data-unavailable", "true")
877
+ );
865
878
  $deviceId.val(currentValue);
866
879
  } else {
867
880
  $deviceId.val("");
@@ -1080,6 +1093,7 @@
1080
1093
  });
1081
1094
 
1082
1095
  refreshSelectionSummary();
1096
+ renderDevices([]);
1083
1097
  ensureDefaultServerSelection();
1084
1098
  refreshEditor();
1085
1099
  }
@@ -1146,7 +1160,7 @@
1146
1160
 
1147
1161
  <h3>Configuration</h3>
1148
1162
  <p><b>Connection</b> selects the shared UniFi Protect config node.</p>
1149
- <p><b>Control</b> chooses the Protect device category. <b>Device</b> chooses the specific item. Device selectors are searchable and open with the complete list before filtering.</p>
1163
+ <p><b>Control</b> chooses the Protect device category. <b>Device</b> chooses the specific item. Device selectors are searchable and open with the complete list before filtering. A saved selection that is temporarily unavailable is preserved instead of being cleared.</p>
1150
1164
  <p><b>Action</b> only shows actions supported by the selected device.</p>
1151
1165
  <p>Additional fields appear only when the selected action needs extra input. For example, events, PTZ presets, live views, or discovered properties.</p>
1152
1166
  <p>Action highlights: <code>Receive Events</code>, <code>Read Device State</code>, <code>Take Snapshot</code>, <code>Show Doorbell Message</code>, siren play/stop/test, relay output control, speaker sound test, and <code>Read Application Info</code> on <code>NVR</code>.</p>
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+
3
+ function normalizeString(value) {
4
+ return String(value || "").trim();
5
+ }
6
+
7
+ function stripOfflineTag(value) {
8
+ return normalizeString(value)
9
+ .replace(/\s*\(\s*offline\s*\)\s*/ig, " ")
10
+ .replace(/\s+/g, " ")
11
+ .trim();
12
+ }
13
+
14
+ function normalizePresenceMatchBy(value) {
15
+ return normalizeString(value).toLowerCase() === "name" ? "name" : "id";
16
+ }
17
+
18
+ function normalizeClientMatchName(value) {
19
+ const cleaned = stripOfflineTag(value);
20
+ try {
21
+ return cleaned.normalize("NFKC").toLowerCase();
22
+ } catch (error) {
23
+ return cleaned.toLowerCase();
24
+ }
25
+ }
26
+
27
+ function getClientNameCandidates(client) {
28
+ const item = client && typeof client === "object" && !Array.isArray(client)
29
+ ? client
30
+ : {};
31
+ const raw = item.raw && typeof item.raw === "object" && !Array.isArray(item.raw)
32
+ ? item.raw
33
+ : {};
34
+ const values = [
35
+ item.name,
36
+ item.displayName,
37
+ item.display_name,
38
+ item.deviceName,
39
+ item.hostname,
40
+ item.host_name,
41
+ item.last_hostname,
42
+ raw.name,
43
+ raw.displayName,
44
+ raw.display_name,
45
+ raw.deviceName,
46
+ raw.hostname,
47
+ raw.host_name,
48
+ raw.last_hostname
49
+ ];
50
+ const candidates = [];
51
+ const seen = new Set();
52
+
53
+ values.forEach((value) => {
54
+ const cleaned = stripOfflineTag(value);
55
+ const normalized = normalizeClientMatchName(cleaned);
56
+ if (!cleaned || !normalized || seen.has(normalized)) {
57
+ return;
58
+ }
59
+ seen.add(normalized);
60
+ candidates.push(cleaned);
61
+ });
62
+
63
+ return candidates;
64
+ }
65
+
66
+ function isExplicitlyOffline(client) {
67
+ const item = client && typeof client === "object" && !Array.isArray(client)
68
+ ? client
69
+ : {};
70
+ return item.offline === true
71
+ || item.isOnline === false
72
+ || item.online === false
73
+ || item.connected === false
74
+ || item.isConnected === false
75
+ || normalizeString(item.connectionState).toLowerCase() === "disconnected"
76
+ || normalizeString(item.status).toLowerCase() === "offline"
77
+ || normalizeString(item.state).toLowerCase() === "offline";
78
+ }
79
+
80
+ function findActiveClientsByName(clients, targetName) {
81
+ const wanted = normalizeClientMatchName(targetName);
82
+ if (!wanted) {
83
+ return [];
84
+ }
85
+
86
+ return (Array.isArray(clients) ? clients : []).filter((client) => {
87
+ if (!client || typeof client !== "object" || Array.isArray(client) || isExplicitlyOffline(client)) {
88
+ return false;
89
+ }
90
+ return getClientNameCandidates(client)
91
+ .some((candidate) => normalizeClientMatchName(candidate) === wanted);
92
+ });
93
+ }
94
+
95
+ function resolveClientResourceId(client) {
96
+ const item = client && typeof client === "object" && !Array.isArray(client)
97
+ ? client
98
+ : {};
99
+ return [
100
+ item.id,
101
+ item.clientId,
102
+ item.client_id,
103
+ item.user_id,
104
+ item._id,
105
+ item.macAddress,
106
+ item.mac_address,
107
+ item.mac
108
+ ].map(normalizeString).find(Boolean) || "";
109
+ }
110
+
111
+ module.exports = {
112
+ normalizePresenceMatchBy,
113
+ normalizeClientMatchName,
114
+ getClientNameCandidates,
115
+ findActiveClientsByName,
116
+ resolveClientResourceId
117
+ };
@@ -95,13 +95,15 @@ function doRequest(url, options, body) {
95
95
  });
96
96
  }
97
97
 
98
- function buildRequestHeaders(authHeader, apiKey, msgHeaders) {
98
+ function buildRequestHeaders(apiKey, msgHeaders) {
99
99
  return Object.assign(
100
100
  {
101
- Accept: "application/json",
102
- [authHeader]: apiKey
101
+ Accept: "application/json"
103
102
  },
104
- msgHeaders && typeof msgHeaders === "object" ? msgHeaders : {}
103
+ msgHeaders && typeof msgHeaders === "object" ? msgHeaders : {},
104
+ {
105
+ "X-API-Key": apiKey
106
+ }
105
107
  );
106
108
  }
107
109
 
@@ -91,13 +91,15 @@ function doRequest(url, options, body) {
91
91
  });
92
92
  }
93
93
 
94
- function buildRequestHeaders(authHeader, apiKey, msgHeaders) {
94
+ function buildRequestHeaders(apiKey, msgHeaders) {
95
95
  return Object.assign(
96
96
  {
97
- Accept: "application/json",
98
- [authHeader]: apiKey
97
+ Accept: "application/json"
99
98
  },
100
- msgHeaders && typeof msgHeaders === "object" ? msgHeaders : {}
99
+ msgHeaders && typeof msgHeaders === "object" ? msgHeaders : {},
100
+ {
101
+ "X-API-Key": apiKey
102
+ }
101
103
  );
102
104
  }
103
105
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.1.3",
3
+ "version": "1.1.5",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",
@@ -66,7 +66,7 @@
66
66
  }
67
67
  },
68
68
  "scripts": {
69
- "test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
69
+ "test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-network-presence-utils.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
70
70
  "registry:discover:network": "node scripts/discover-unifi-network-registry.js",
71
71
  "registry:discover:protect": "node scripts/discover-unifi-protect-registry.js",
72
72
  "registry:discover:access": "node scripts/discover-unifi-access-registry.js"