node-red-contrib-unifi-ultimate 0.1.9 → 0.1.11

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/README.md CHANGED
@@ -20,6 +20,19 @@ Control and monitor `UniFi Network`, `UniFi Protect`, and `UniFi Access` from No
20
20
 
21
21
  [View Changelog](CHANGELOG.md)
22
22
 
23
+ <a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ">
24
+ <img src="resources/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" align="absmiddle">
25
+ Watch news and tutorials on YouTube
26
+ <br/>
27
+ <br/>
28
+ <p align="center">
29
+ <img src="nodes/readme-assets/unifi-editor-preview.jpeg" alt="UniFi Ultimate editor preview" width="860">
30
+ </p>
31
+ </a>
32
+
33
+ <br/>
34
+ <br/>
35
+
23
36
  ## Install
24
37
 
25
38
  In Node-RED:
@@ -310,4 +323,4 @@ Import from `examples/`:
310
323
  [license-image]: https://img.shields.io/badge/license-MIT-green.svg
311
324
  [license-url]: https://opensource.org/licenses/MIT
312
325
  [youtube-image]: https://img.shields.io/badge/YouTube-Subscribe-red?logo=youtube&logoColor=white
313
- [youtube-url]: https://www.youtube.com/@maxsupervibe
326
+ [youtube-url]: https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28 20" role="img" aria-labelledby="title">
2
+ <title id="title">YouTube</title>
3
+ <path fill="#FF0000" d="M27.4 3.1c-.3-1.2-1.3-2.1-2.5-2.4C22.7.1 14 .1 14 .1S5.3.1 3.1.7C1.9 1 .9 1.9.6 3.1 0 5.3 0 10 0 10s0 4.7.6 6.9c.3 1.2 1.3 2.1 2.5 2.4 2.2.6 10.9.6 10.9.6s8.7 0 10.9-.6c1.2-.3 2.1-1.2 2.5-2.4.6-2.2.6-6.9.6-6.9s0-4.7-.6-6.9z"/>
4
+ <path fill="#FFFFFF" d="M11.2 14.2 18.5 10l-7.3-4.2v8.4z"/>
5
+ </svg>
@@ -16,36 +16,17 @@
16
16
  },
17
17
  oneditprepare: function () {
18
18
  const $host = $("#node-config-input-host");
19
- const $connectionHint = $("#node-config-input-connectionHint");
19
+ const $apiToken = $("#node-config-input-apiToken");
20
+ const $rejectUnauthorized = $("#node-config-input-rejectUnauthorized");
21
+ const $apiTokenRow = $apiToken.closest(".form-row");
22
+ const $securityRow = $rejectUnauthorized.closest(".form-row");
23
+ const $advancedRow = $("#node-config-row-advanced");
20
24
 
21
- function escapeHtml(value) {
22
- // The connection preview is rendered as HTML, so sanitize any
23
- // host text typed by the user first.
24
- return String(value || "")
25
- .replace(/&/g, "&amp;")
26
- .replace(/</g, "&lt;")
27
- .replace(/>/g, "&gt;")
28
- .replace(/"/g, "&quot;")
29
- .replace(/'/g, "&#39;");
30
- }
31
-
32
- function refreshConnectionHint() {
33
- const host = String($host.val() || "").trim();
34
- if (!host) {
35
- $connectionHint.html("<strong>Enter your controller address</strong>The node uses the standard UniFi Access API connection automatically.");
36
- return;
37
- }
38
-
39
- // UniFi Access defaults to port 12445. Show the fully resolved
40
- // host in the preview even when the user omitted the port.
41
- const normalizedHost = host.replace(/^https?:\/\//i, "").replace(/\/+$/, "");
42
- const hasPort = /:\d+$/.test(normalizedHost);
43
- const previewHost = hasPort ? normalizedHost : normalizedHost + ":12445";
44
- $connectionHint.html(
45
- "<strong>Connection preview</strong>Will connect to <code>https://" +
46
- escapeHtml(previewHost) +
47
- "</code>"
48
- );
25
+ function syncProgressiveRows() {
26
+ const hasHost = String($host.val() || "").trim() !== "";
27
+ $apiTokenRow.toggle(hasHost);
28
+ $securityRow.toggle(hasHost);
29
+ $advancedRow.toggle(hasHost);
49
30
  }
50
31
 
51
32
  try {
@@ -55,11 +36,10 @@
55
36
  } catch (error) {
56
37
  }
57
38
 
58
- refreshConnectionHint();
39
+ syncProgressiveRows();
59
40
 
60
41
  $host.on("change input", function () {
61
- // Keep the preview synchronized with the current host value.
62
- refreshConnectionHint();
42
+ syncProgressiveRows();
63
43
  });
64
44
  }
65
45
  });
@@ -70,12 +50,11 @@
70
50
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-access-black.svg" alt="UniFi Access logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
71
51
  </div>
72
52
  <div class="form-row unifi-ultimate-hero">
73
- <div class="unifi-ultimate-hero-panel">
74
- <strong>Connect Node-RED to your UniFi Access application.</strong>
75
- <span>Use the Access host or IP address and an Access API token.</span>
76
- </div>
53
+ <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
54
+ <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
55
+ <span>Youtube Tutorials</span>
56
+ </a>
77
57
  </div>
78
- <div class="unifi-ultimate-section-title">Connection</div>
79
58
  <div class="form-row">
80
59
  <label for="node-config-input-host"><i class="fa fa-globe"></i> Controller</label>
81
60
  <input type="text" id="node-config-input-host" placeholder="192.168.1.10 or access.local:12445">
@@ -89,9 +68,6 @@
89
68
  <input type="checkbox" id="node-config-input-rejectUnauthorized" style="display:inline-block; width:auto; vertical-align:top;">
90
69
  <span style="margin-left:8px;">Secure connection only</span>
91
70
  </div>
92
- <div class="form-row">
93
- <div id="node-config-input-connectionHint" class="unifi-ultimate-card"></div>
94
- </div>
95
71
  <div id="node-config-row-advanced" class="unifi-ultimate-advanced">
96
72
  <div class="form-row">
97
73
  <label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
@@ -101,6 +77,8 @@
101
77
  </script>
102
78
 
103
79
  <script type="text/html" data-help-name="unifi-access-config">
80
+ <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer"><img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" style="vertical-align:text-bottom; margin-right:6px;">Youtube Tutorials</a></p>
81
+
104
82
  <p>Shared connection for UniFi Access nodes.</p>
105
83
 
106
84
  <h3>Configuration</h3>
@@ -86,8 +86,10 @@
86
86
  const $capabilityConfigRow = $("#node-row-capabilityConfig");
87
87
  const $capabilityConfigContainer = $("#node-input-capabilityConfigContainer");
88
88
  const $refresh = $("#node-input-refreshDevices");
89
- const $selectionSummary = $("#node-input-selectionSummary");
90
- const $selectionDetail = $("#node-input-selectionDetail");
89
+ const $deviceTypeRow = $deviceType.closest(".form-row");
90
+ const $deviceIdRow = $deviceId.closest(".form-row");
91
+ const $capabilityRow = $capability.closest(".form-row");
92
+ const $advancedRow = $("#node-row-advanced");
91
93
  let capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
92
94
  let capabilityListRequestId = 0;
93
95
  let capabilityOptionsRequestId = 0;
@@ -95,6 +97,26 @@
95
97
  let isInitializingEditor = true;
96
98
  let deviceTypeDefinitions = [];
97
99
  let capabilityDefinitions = [];
100
+
101
+ function hasSelection($field) {
102
+ const value = String($field.val() || "").trim();
103
+ return value !== "" && value !== "_ADD_";
104
+ }
105
+
106
+ function syncProgressiveRows() {
107
+ const hasServer = hasSelection($server);
108
+ const hasDeviceType = hasSelection($deviceType);
109
+ const hasDevice = hasSelection($deviceId);
110
+ const hasCapability = hasSelection($capability);
111
+ const hasCapabilityFields = $capabilityConfigRow.data("has-fields") === true;
112
+
113
+ $deviceTypeRow.toggle(hasServer);
114
+ $deviceIdRow.toggle(hasServer && hasDeviceType);
115
+ $capabilityRow.toggle(hasServer && hasDeviceType && hasDevice);
116
+ $capabilityConfigRow.toggle(hasServer && hasDeviceType && hasDevice && hasCapability && hasCapabilityFields);
117
+ $advancedRow.toggle(hasServer && hasDeviceType && hasDevice && hasCapability);
118
+ }
119
+
98
120
  function parseCapabilityConfig(rawValue) {
99
121
  if (rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)) {
100
122
  return rawValue;
@@ -498,9 +520,7 @@
498
520
  } else if (capabilityDefinition && capabilityDefinition.description) {
499
521
  detail = capabilityDefinition.description;
500
522
  }
501
-
502
- $selectionSummary.text(summary);
503
- $selectionDetail.text(detail);
523
+ syncProgressiveRows();
504
524
  }
505
525
 
506
526
  function syncNameFromSelection() {
@@ -664,6 +684,7 @@
664
684
  $capabilityConfigContainer.empty();
665
685
 
666
686
  if (fields.length === 0) {
687
+ $capabilityConfigRow.data("has-fields", false);
667
688
  $capabilityConfigRow.hide();
668
689
  if (renderOptions.clearStoredConfig) {
669
690
  capabilityConfig = {};
@@ -679,6 +700,7 @@
679
700
  writeCapabilityConfig();
680
701
  }
681
702
 
703
+ $capabilityConfigRow.data("has-fields", true);
682
704
  $capabilityConfigRow.show();
683
705
  fields.forEach(function (field) {
684
706
  const fieldId = "node-input-capability-config-" + field.id;
@@ -764,8 +786,8 @@
764
786
  if (field.helpText) {
765
787
  $wrapper.append(
766
788
  $("<div></div>")
767
- .addClass("form-tips")
768
- .css({ marginLeft: "152px" })
789
+ .addClass("form-tips unifi-ultimate-info-tip")
790
+ .css({ marginLeft: "0", width: "100%", boxSizing: "border-box" })
769
791
  .text(field.helpText)
770
792
  );
771
793
  }
@@ -1027,41 +1049,32 @@
1027
1049
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-access-black.svg" alt="UniFi Access logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
1028
1050
  </div>
1029
1051
  <div class="form-row unifi-ultimate-hero">
1030
- <div class="unifi-ultimate-hero-panel">
1031
- <strong>Control doors and Access devices from a flow.</strong>
1032
- <span>Choose a door or device, then select the action to run when a message arrives.</span>
1033
- </div>
1052
+ <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
1053
+ <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
1054
+ <span>Youtube Tutorials</span>
1055
+ </a>
1034
1056
  </div>
1035
- <div class="unifi-ultimate-section-title">Connection</div>
1036
1057
  <div class="form-row">
1037
1058
  <label for="node-input-server"><i class="fa fa-cog"></i> Connection</label>
1038
1059
  <input type="text" id="node-input-server">
1039
1060
  </div>
1040
- <div class="unifi-ultimate-section-title">Target</div>
1041
1061
  <div class="form-row">
1042
1062
  <label for="node-input-deviceType"><i class="fa fa-cubes"></i> Control</label>
1043
1063
  <select id="node-input-deviceType"></select>
1044
1064
  </div>
1045
1065
  <div class="form-row">
1046
1066
  <label for="node-input-deviceId"><i class="fa fa-dot-circle-o"></i> Device</label>
1047
- <select id="node-input-deviceId" style="width:70%;"></select>
1067
+ <select id="node-input-deviceId" style="width:62%;"></select>
1048
1068
  <a href="#" id="node-input-refreshDevices" class="editor-button" style="margin-left:6px;" title="Refresh devices" aria-label="Refresh devices">
1049
1069
  <i class="fa fa-refresh"></i>
1050
1070
  </a>
1051
1071
  </div>
1052
- <div class="unifi-ultimate-section-title">Action</div>
1053
1072
  <div class="form-row">
1054
1073
  <label for="node-input-capability"><i class="fa fa-tasks"></i> Action</label>
1055
1074
  <select id="node-input-capability"></select>
1056
1075
  </div>
1057
- <div class="form-row">
1058
- <div class="unifi-ultimate-card">
1059
- <strong id="node-input-selectionSummary">Choose a connection to begin.</strong>
1060
- <div id="node-input-selectionDetail">The editor only shows actions supported by the selected UniFi Access device.</div>
1061
- </div>
1062
- </div>
1063
1076
  <div class="form-row" id="node-row-capabilityConfig" style="display:none;">
1064
- <label><i class="fa fa-sliders"></i> Action options</label>
1077
+ <label></label>
1065
1078
  <div id="node-input-capabilityConfigContainer" style="width:70%; display:inline-block;"></div>
1066
1079
  <input type="hidden" id="node-input-capabilityConfig">
1067
1080
  <input type="hidden" id="node-input-deviceName">
@@ -1079,15 +1092,17 @@
1079
1092
  </script>
1080
1093
 
1081
1094
  <script type="text/html" data-help-name="unifi-access-device">
1095
+ <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer"><img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" style="vertical-align:text-bottom; margin-right:6px;">Youtube Tutorials</a></p>
1096
+
1082
1097
  <p>Use this node to execute a configured UniFi Access action or listen for live Access events.</p>
1083
1098
 
1084
1099
  <h3>Configuration</h3>
1085
1100
  <p><b>Connection</b> selects the shared UniFi Access config node.</p>
1086
1101
  <p><b>Control</b> chooses the Access category. <b>Device</b> chooses the specific door or Access device. Device selectors are searchable and open with the complete list before filtering.</p>
1087
1102
  <p><b>Action</b> only shows actions supported by the selected item.</p>
1088
- <p><b>Action options</b> appears only when the selected action needs extra input, such as a temporary lock rule or a room name for doorbell actions.</p>
1103
+ <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>
1089
1104
  <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>
1090
- <p><code>Receive Events</code> fetches the current state once and then subscribes to events provided by the shared UniFi Access config node. The config node maintains the official notifications WebSocket and fans out events to runtime nodes. In <b>Action options</b>, <code>All</code> emits every event for the selected device/door. In this mode, the input pin is hidden and listening starts automatically after deploy/restart.</p>
1105
+ <p><code>Receive Events</code> fetches the current state once and then subscribes to events provided by the shared UniFi Access config node. The config node maintains the official notifications WebSocket and fans out events to runtime nodes. In this mode, <code>All</code> emits every event for the selected device/door. The input pin is hidden and listening starts automatically after deploy/restart.</p>
1091
1106
  <p><code>Trigger Doorbell</code> and <code>Cancel Doorbell</code> use a manual <code>Room Name</code> field when needed. The node does not currently discover Intercom directory names automatically.</p>
1092
1107
  <p><code>Cancel Doorbell</code> uses a shared safe-cancel guard in the UniFi Access config node with a 3 minute tracking window. Tracking is updated by websocket events and a fallback system-log poller.</p>
1093
1108
  <p><b>Name</b> is the node name shown in the editor and is updated only when you manually select a different item from the list. <b>Timeout</b> controls the request timeout in milliseconds for API calls.</p>
@@ -18,34 +18,20 @@
18
18
  },
19
19
  oneditprepare: function () {
20
20
  const $host = $("#node-config-input-host");
21
- const $connectionHint = $("#node-config-input-connectionHint");
21
+ const $apiKey = $("#node-config-input-apiKey");
22
+ const $rejectUnauthorized = $("#node-config-input-rejectUnauthorized");
23
+ const $powerObservationIntervalSeconds = $("#node-config-input-powerObservationIntervalSeconds");
24
+ const $apiKeyRow = $apiKey.closest(".form-row");
25
+ const $securityRow = $rejectUnauthorized.closest(".form-row");
26
+ const $powerObservationRow = $powerObservationIntervalSeconds.closest(".form-row");
27
+ const $advancedRow = $("#node-config-row-advanced");
22
28
 
23
- function escapeHtml(value) {
24
- // The preview is rendered as HTML, so sanitize user input before
25
- // echoing the controller host back into the hint box.
26
- return String(value || "")
27
- .replace(/&/g, "&amp;")
28
- .replace(/</g, "&lt;")
29
- .replace(/>/g, "&gt;")
30
- .replace(/\"/g, "&quot;")
31
- .replace(/'/g, "&#39;");
32
- }
33
-
34
- function refreshConnectionHint() {
35
- const host = String($host.val() || "").trim();
36
- if (!host) {
37
- $connectionHint.html("<strong>Enter your controller address</strong>The node builds the UniFi Network connection automatically.");
38
- return;
39
- }
40
-
41
- // The runtime accepts either a bare host or a full URL, but the
42
- // preview intentionally shows the normalized integration endpoint.
43
- const normalizedHost = host.replace(/^https?:\/\//i, "").replace(/\/+$/, "");
44
- $connectionHint.html(
45
- "<strong>Connection preview</strong>Will connect to <code>https://" +
46
- escapeHtml(normalizedHost) +
47
- "/proxy/network/integration</code>"
48
- );
29
+ function syncProgressiveRows() {
30
+ const hasHost = String($host.val() || "").trim() !== "";
31
+ $apiKeyRow.toggle(hasHost);
32
+ $securityRow.toggle(hasHost);
33
+ $powerObservationRow.toggle(hasHost);
34
+ $advancedRow.toggle(hasHost);
49
35
  }
50
36
 
51
37
  try {
@@ -55,10 +41,9 @@
55
41
  } catch (error) {
56
42
  }
57
43
 
58
- refreshConnectionHint();
44
+ syncProgressiveRows();
59
45
  $host.on("change input", function () {
60
- // Update the preview live as the user edits the controller host.
61
- refreshConnectionHint();
46
+ syncProgressiveRows();
62
47
  });
63
48
  }
64
49
  });
@@ -69,12 +54,11 @@
69
54
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-network-black.svg" alt="UniFi Network logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
70
55
  </div>
71
56
  <div class="form-row unifi-ultimate-hero">
72
- <div class="unifi-ultimate-hero-panel">
73
- <strong>Connect Node-RED to your UniFi Network application.</strong>
74
- <span>Use a local UniFi OS host or IP address and a Network API key.</span>
75
- </div>
57
+ <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
58
+ <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
59
+ <span>Youtube Tutorials</span>
60
+ </a>
76
61
  </div>
77
- <div class="unifi-ultimate-section-title">Connection</div>
78
62
  <div class="form-row">
79
63
  <label for="node-config-input-host"><i class="fa fa-globe"></i> Controller</label>
80
64
  <input type="text" id="node-config-input-host" placeholder="192.168.1.10">
@@ -92,9 +76,6 @@
92
76
  <label for="node-config-input-powerObservationIntervalSeconds"><i class="fa fa-repeat"></i> Power Poll (s)</label>
93
77
  <input type="text" id="node-config-input-powerObservationIntervalSeconds" placeholder="15">
94
78
  </div>
95
- <div class="form-row">
96
- <div id="node-config-input-connectionHint" class="unifi-ultimate-card"></div>
97
- </div>
98
79
  <div id="node-config-row-advanced" class="unifi-ultimate-advanced">
99
80
  <div class="form-row">
100
81
  <label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
@@ -104,6 +85,8 @@
104
85
  </script>
105
86
 
106
87
  <script type="text/html" data-help-name="unifi-network-config">
88
+ <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer"><img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" style="vertical-align:text-bottom; margin-right:6px;">Youtube Tutorials</a></p>
89
+
107
90
  <p>Shared connection for UniFi Network nodes.</p>
108
91
 
109
92
  <h3>Configuration</h3>
@@ -117,5 +100,5 @@
117
100
  <p>This config node is used by Network Device, Network Presence, and Control POE nodes.</p>
118
101
  <p>All UniFi Network requests are executed by this config node. Runtime nodes subscribe through <code>addClient/removeClient</code> and receive updates/events from here.</p>
119
102
  <p>Event streams and observation timers are centralized here (shared scheduler per config node), so runtime nodes do not open their own websocket channels or polling timers.</p>
120
- <p>The node uses the official Network integration API where available. For switch port/client mapping and PoE enable/disable, it also uses the local Network legacy API endpoints exposed through the UniFi OS proxy.</p>
103
+ <p>The node uses the official Network integration API where available and falls back automatically to local legacy endpoints when the official <code>/v1</code> routes are not exposed (for example on older local releases). For switch port/client mapping and PoE enable/disable, legacy endpoints are also used where needed.</p>
121
104
  </script>
@@ -216,7 +216,9 @@ module.exports = function(RED) {
216
216
  });
217
217
 
218
218
  if (response.statusCode < 200 || response.statusCode >= 300) {
219
- throw new Error(`Failed to load collection (${response.statusCode})`);
219
+ const statusError = new Error(`Failed to load collection (${response.statusCode})`);
220
+ statusError.statusCode = response.statusCode;
221
+ throw statusError;
220
222
  }
221
223
 
222
224
  const payload = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload)
@@ -255,11 +257,95 @@ module.exports = function(RED) {
255
257
  return collected;
256
258
  };
257
259
 
260
+ function getResponseStatusFromError(error) {
261
+ const directStatus = Number(error && error.statusCode);
262
+ if (Number.isFinite(directStatus)) {
263
+ return Math.trunc(directStatus);
264
+ }
265
+
266
+ const message = String(error && error.message || "");
267
+ const match = message.match(/\((\d{3})\)/);
268
+ if (!match) {
269
+ return NaN;
270
+ }
271
+
272
+ const parsed = Number(match[1]);
273
+ return Number.isFinite(parsed) ? Math.trunc(parsed) : NaN;
274
+ }
275
+
276
+ function shouldUseLegacyNetworkFallback(error) {
277
+ const statusCode = getResponseStatusFromError(error);
278
+ if (!Number.isFinite(statusCode)) {
279
+ return false;
280
+ }
281
+
282
+ // Older local Network releases may not expose the official
283
+ // integration endpoints and return explicit route/method errors.
284
+ return [403, 404, 405, 410, 501].includes(statusCode);
285
+ }
286
+
287
+ function mapLegacySiteToNormalizedShape(site) {
288
+ const item = site && typeof site === "object" && !Array.isArray(site)
289
+ ? site
290
+ : {};
291
+ const siteName = normalizeString(item.name || item.desc || "default");
292
+ const siteId = normalizeString(
293
+ item.external_id
294
+ || item.id
295
+ || item._id
296
+ || item.name
297
+ );
298
+
299
+ if (!siteId) {
300
+ return null;
301
+ }
302
+
303
+ return {
304
+ ...item,
305
+ id: siteId,
306
+ siteId,
307
+ name: siteName || siteId,
308
+ displayName: normalizeString(item.desc || item.displayName || siteName || siteId)
309
+ };
310
+ }
311
+
312
+ node.fetchLegacySites = async () => {
313
+ const response = await node.legacyApiRequest({
314
+ path: "/api/self/sites",
315
+ method: "GET"
316
+ });
317
+ if (response.statusCode < 200 || response.statusCode >= 300) {
318
+ const statusError = new Error(`Failed to load legacy sites (${response.statusCode})`);
319
+ statusError.statusCode = response.statusCode;
320
+ throw statusError;
321
+ }
322
+
323
+ const sites = normalizeNetworkCollection(response.payload)
324
+ .map((site) => mapLegacySiteToNormalizedShape(site))
325
+ .filter(Boolean);
326
+
327
+ const dedupById = new Map();
328
+ sites.forEach((site) => {
329
+ const key = normalizeString(site && site.id);
330
+ if (key && !dedupById.has(key)) {
331
+ dedupById.set(key, site);
332
+ }
333
+ });
334
+ return Array.from(dedupById.values());
335
+ };
336
+
258
337
  node.fetchSites = async () => {
259
338
  // Sites are the root scope for nearly all other Network resources.
260
- return node.fetchPagedCollection({
261
- path: "/v1/sites"
262
- });
339
+ try {
340
+ return await node.fetchPagedCollection({
341
+ path: "/v1/sites"
342
+ });
343
+ } catch (error) {
344
+ if (!shouldUseLegacyNetworkFallback(error)) {
345
+ throw error;
346
+ }
347
+ return node.fetchLegacySites();
348
+ }
263
349
  };
264
350
 
265
351
  node.fetchDevices = async (deviceType) => {
@@ -293,6 +379,55 @@ module.exports = function(RED) {
293
379
  siteName
294
380
  }));
295
381
  } catch (error) {
382
+ if (!shouldUseLegacyNetworkFallback(error)) {
383
+ return [];
384
+ }
385
+ try {
386
+ if (definition.type === "device") {
387
+ const legacyDevices = await fetchLegacyDevices(siteId);
388
+ return legacyDevices.map((item) => ({
389
+ ...item,
390
+ id: firstNonEmptyString([
391
+ item && item.id,
392
+ item && item.device_id,
393
+ item && item._id,
394
+ item && item.mac
395
+ ]),
396
+ siteId,
397
+ siteName
398
+ }));
399
+ }
400
+
401
+ if (definition.type === "client") {
402
+ const legacyClients = await fetchLegacyKnownClients(siteId);
403
+ return legacyClients.map((item) => ({
404
+ ...item,
405
+ id: firstNonEmptyString([
406
+ item && item.id,
407
+ item && item.clientId,
408
+ item && item.client_id,
409
+ item && item.user_id,
410
+ item && item._id,
411
+ item && item.macAddress,
412
+ item && item.mac
413
+ ]),
414
+ clientId: firstNonEmptyString([
415
+ item && item.clientId,
416
+ item && item.id,
417
+ item && item.client_id,
418
+ item && item.user_id,
419
+ item && item._id,
420
+ item && item.macAddress,
421
+ item && item.mac
422
+ ]),
423
+ siteId,
424
+ siteName
425
+ }));
426
+ }
427
+ } catch (legacyError) {
428
+ return [];
429
+ }
430
+
296
431
  return [];
297
432
  }
298
433
  }));
@@ -419,13 +554,55 @@ module.exports = function(RED) {
419
554
  .replace(/\{deviceId\}/g, encodeURIComponent(scoped.resourceId))
420
555
  .replace(/\{clientId\}/g, encodeURIComponent(scoped.resourceId));
421
556
 
422
- const response = await node.apiRequest({
423
- path: detailPath,
424
- method: "GET"
425
- });
557
+ let response;
558
+ try {
559
+ response = await node.apiRequest({
560
+ path: detailPath,
561
+ method: "GET"
562
+ });
563
+ } catch (error) {
564
+ if (!shouldUseLegacyNetworkFallback(error)) {
565
+ throw error;
566
+ }
567
+ }
426
568
 
427
- if (response.statusCode < 200 || response.statusCode >= 300) {
428
- throw new Error(`Failed to load ${deviceType} ${scoped.resourceId} (${response.statusCode})`);
569
+ if (!response || response.statusCode < 200 || response.statusCode >= 300) {
570
+ const statusError = new Error(`Failed to load ${deviceType} ${scoped.resourceId} (${response && response.statusCode ? response.statusCode : "n/a"})`);
571
+ statusError.statusCode = response && response.statusCode ? response.statusCode : undefined;
572
+ if (!shouldUseLegacyNetworkFallback(statusError)) {
573
+ throw statusError;
574
+ }
575
+
576
+ if (definition.type === "device") {
577
+ const legacyDevices = await fetchLegacyDevices(scoped.siteId);
578
+ return legacyDevices.find((legacyDevice) => {
579
+ const candidates = [
580
+ legacyDevice && legacyDevice.id,
581
+ legacyDevice && legacyDevice.device_id,
582
+ legacyDevice && legacyDevice._id,
583
+ legacyDevice && legacyDevice.mac
584
+ ];
585
+ return candidates.some((candidate) => normalizeIdentifierKey(candidate) === normalizeIdentifierKey(scoped.resourceId));
586
+ }) || null;
587
+ }
588
+
589
+ if (definition.type === "client") {
590
+ const legacyClients = await fetchLegacyKnownClients(scoped.siteId);
591
+ return legacyClients.find((legacyClient) => {
592
+ const candidates = [
593
+ legacyClient && legacyClient.id,
594
+ legacyClient && legacyClient.clientId,
595
+ legacyClient && legacyClient.client_id,
596
+ legacyClient && legacyClient.user_id,
597
+ legacyClient && legacyClient._id,
598
+ legacyClient && legacyClient.macAddress,
599
+ legacyClient && legacyClient.mac
600
+ ];
601
+ return candidates.some((candidate) => normalizeIdentifierKey(candidate) === normalizeIdentifierKey(scoped.resourceId));
602
+ }) || null;
603
+ }
604
+
605
+ throw statusError;
429
606
  }
430
607
 
431
608
  const payload = extractNetworkData(response.payload);