From 1ada10299ae5a935869fa37ebe5980a91d4db0ab Mon Sep 17 00:00:00 2001
From: Christopher Bailey <cbailey@mort.is>
Date: Thu, 14 Mar 2024 15:07:54 -0400
Subject: [PATCH] Check for EA release channel for UniFi Protect (#113432)

Co-authored-by: J. Nick Koston <nick@koston.org>
---
 homeassistant/components/unifiprotect/__init__.py | 13 +++++++------
 homeassistant/components/unifiprotect/const.py    |  2 +-
 homeassistant/components/unifiprotect/repairs.py  |  5 +++--
 .../components/unifiprotect/strings.json          | 12 ++++++------
 tests/components/unifiprotect/test_config_flow.py |  2 +-
 tests/components/unifiprotect/test_repairs.py     | 15 ++++++++++-----
 6 files changed, 28 insertions(+), 21 deletions(-)

diff --git a/homeassistant/components/unifiprotect/__init__.py b/homeassistant/components/unifiprotect/__init__.py
index 45d80b85c58..15784dbdeaf 100644
--- a/homeassistant/components/unifiprotect/__init__.py
+++ b/homeassistant/components/unifiprotect/__init__.py
@@ -7,6 +7,7 @@ import logging
 
 from aiohttp.client_exceptions import ServerDisconnectedError
 from pyunifiprotect.data import Bootstrap
+from pyunifiprotect.data.types import FirmwareReleaseChannel
 from pyunifiprotect.exceptions import ClientError, NotAuthorized
 
 # Import the test_util.anonymize module from the pyunifiprotect package
@@ -112,19 +113,19 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
         hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, data_service.async_stop)
     )
 
-    if (
-        not entry.options.get(CONF_ALLOW_EA, False)
-        and await nvr_info.get_is_prerelease()
+    if not entry.options.get(CONF_ALLOW_EA, False) and (
+        await nvr_info.get_is_prerelease()
+        or nvr_info.release_channel != FirmwareReleaseChannel.RELEASE
     ):
         ir.async_create_issue(
             hass,
             DOMAIN,
-            "ea_warning",
+            "ea_channel_warning",
             is_fixable=True,
             is_persistent=True,
             learn_more_url="https://www.home-assistant.io/integrations/unifiprotect#about-unifi-early-access",
             severity=IssueSeverity.WARNING,
-            translation_key="ea_warning",
+            translation_key="ea_channel_warning",
             translation_placeholders={"version": str(nvr_info.version)},
             data={"entry_id": entry.entry_id},
         )
@@ -150,7 +151,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
                     "version": str(nvr_info.version),
                 },
             )
-            ir.async_delete_issue(hass, DOMAIN, "ea_warning")
+            ir.async_delete_issue(hass, DOMAIN, "ea_channel_warning")
             _LOGGER.exception("Error setting up UniFi Protect integration: %s", err)
         raise
 
diff --git a/homeassistant/components/unifiprotect/const.py b/homeassistant/components/unifiprotect/const.py
index 2982ca29c4a..39be5f0e7cb 100644
--- a/homeassistant/components/unifiprotect/const.py
+++ b/homeassistant/components/unifiprotect/const.py
@@ -24,7 +24,7 @@ CONF_DISABLE_RTSP = "disable_rtsp"
 CONF_ALL_UPDATES = "all_updates"
 CONF_OVERRIDE_CHOST = "override_connection_host"
 CONF_MAX_MEDIA = "max_media"
-CONF_ALLOW_EA = "allow_ea"
+CONF_ALLOW_EA = "allow_ea_channel"
 
 CONFIG_OPTIONS = [
     CONF_ALL_UPDATES,
diff --git a/homeassistant/components/unifiprotect/repairs.py b/homeassistant/components/unifiprotect/repairs.py
index ddc0a257c14..254984da515 100644
--- a/homeassistant/components/unifiprotect/repairs.py
+++ b/homeassistant/components/unifiprotect/repairs.py
@@ -6,6 +6,7 @@ import logging
 from typing import cast
 
 from pyunifiprotect import ProtectApiClient
+from pyunifiprotect.data.types import FirmwareReleaseChannel
 import voluptuous as vol
 
 from homeassistant import data_entry_flow
@@ -68,7 +69,7 @@ class EAConfirm(ProtectRepair):
             )
 
         nvr = await self._api.get_nvr()
-        if await nvr.get_is_prerelease():
+        if nvr.release_channel != FirmwareReleaseChannel.RELEASE:
             return await self.async_step_confirm()
         await self.hass.config_entries.async_reload(self._entry.entry_id)
         return self.async_create_entry(data={})
@@ -124,7 +125,7 @@ async def async_create_fix_flow(
     data: dict[str, str | int | float | None] | None,
 ) -> RepairsFlow:
     """Create flow."""
-    if data is not None and issue_id == "ea_warning":
+    if data is not None and issue_id == "ea_channel_warning":
         entry_id = cast(str, data["entry_id"])
         if (entry := hass.config_entries.async_get_entry(entry_id)) is not None:
             api = async_create_api_client(hass, entry)
diff --git a/homeassistant/components/unifiprotect/strings.json b/homeassistant/components/unifiprotect/strings.json
index 97e68388dd9..b783bdf1a2c 100644
--- a/homeassistant/components/unifiprotect/strings.json
+++ b/homeassistant/components/unifiprotect/strings.json
@@ -61,16 +61,16 @@
     }
   },
   "issues": {
-    "ea_warning": {
-      "title": "UniFi Protect v{version} is an Early Access version",
+    "ea_channel_warning": {
+      "title": "UniFi Protect Early Access enabled",
       "fix_flow": {
         "step": {
           "start": {
-            "title": "v{version} is an Early Access version",
-            "description": "You are using v{version} of UniFi Protect which is an Early Access version. [Early Access versions are not supported by Home Assistant](https://www.home-assistant.io/integrations/unifiprotect#about-unifi-early-access) and it is recommended to go back to a stable release as soon as possible.\n\nBy submitting this form you have either [downgraded UniFi Protect](https://www.home-assistant.io/integrations/unifiprotect#downgrading-unifi-protect) or you agree to run an unsupported version of UniFi Protect."
+            "title": "UniFi Protect Early Access enabled",
+            "description": "You are either running an Early Access version of UniFi Protect (v{version}) or opt-ed into a release channel that is not the Official Release Channel. [Home Assistant does not support Early Access versions](https://www.home-assistant.io/integrations/unifiprotect#about-unifi-early-access), so you should immediately switch to the Official Release Channel. Accidentally upgrading to an Early Access version can break your UniFi Protect integration.\n\nBy submitting this form, you have switched back to the Official Release Channel or agree to run an unsupported version of UniFi Protect, which may break your Home Assistant integration at any time."
           },
           "confirm": {
-            "title": "[%key:component::unifiprotect::issues::ea_warning::fix_flow::step::start::title%]",
+            "title": "[%key:component::unifiprotect::issues::ea_channel_warning::fix_flow::step::start::title%]",
             "description": "Are you sure you want to run unsupported versions of UniFi Protect? This may cause your Home Assistant integration to break."
           }
         }
@@ -78,7 +78,7 @@
     },
     "ea_setup_failed": {
       "title": "Setup error using Early Access version",
-      "description": "You are using v{version} of UniFi Protect which is an Early Access version. An unrecoverable error occurred while trying to load the integration. Please [downgrade to a stable version](https://www.home-assistant.io/integrations/unifiprotect#downgrading-unifi-protect) of UniFi Protect to continue using the integration.\n\nError: {error}"
+      "description": "You are using v{version} of UniFi Protect which is an Early Access version. An unrecoverable error occurred while trying to load the integration. Please restore a backup of a stable release of UniFi Protect to continue using the integration.\n\nError: {error}"
     },
     "cloud_user": {
       "title": "Ubiquiti Cloud Users are not Supported",
diff --git a/tests/components/unifiprotect/test_config_flow.py b/tests/components/unifiprotect/test_config_flow.py
index a5fbdb8493f..f4ff4752baf 100644
--- a/tests/components/unifiprotect/test_config_flow.py
+++ b/tests/components/unifiprotect/test_config_flow.py
@@ -328,7 +328,7 @@ async def test_form_options(hass: HomeAssistant, ufp_client: ProtectApiClient) -
             "disable_rtsp": True,
             "override_connection_host": True,
             "max_media": 1000,
-            "allow_ea": False,
+            "allow_ea_channel": False,
         }
         await hass.config_entries.async_unload(mock_config.entry_id)
 
diff --git a/tests/components/unifiprotect/test_repairs.py b/tests/components/unifiprotect/test_repairs.py
index 41307029a0f..b75b025be11 100644
--- a/tests/components/unifiprotect/test_repairs.py
+++ b/tests/components/unifiprotect/test_repairs.py
@@ -46,12 +46,14 @@ async def test_ea_warning_ignore(
     assert len(msg["result"]["issues"]) > 0
     issue = None
     for i in msg["result"]["issues"]:
-        if i["issue_id"] == "ea_warning":
+        if i["issue_id"] == "ea_channel_warning":
             issue = i
     assert issue is not None
 
     url = RepairsFlowIndexView.url
-    resp = await client.post(url, json={"handler": DOMAIN, "issue_id": "ea_warning"})
+    resp = await client.post(
+        url, json={"handler": DOMAIN, "issue_id": "ea_channel_warning"}
+    )
     assert resp.status == HTTPStatus.OK
     data = await resp.json()
 
@@ -104,12 +106,14 @@ async def test_ea_warning_fix(
     assert len(msg["result"]["issues"]) > 0
     issue = None
     for i in msg["result"]["issues"]:
-        if i["issue_id"] == "ea_warning":
+        if i["issue_id"] == "ea_channel_warning":
             issue = i
     assert issue is not None
 
     url = RepairsFlowIndexView.url
-    resp = await client.post(url, json={"handler": DOMAIN, "issue_id": "ea_warning"})
+    resp = await client.post(
+        url, json={"handler": DOMAIN, "issue_id": "ea_channel_warning"}
+    )
     assert resp.status == HTTPStatus.OK
     data = await resp.json()
 
@@ -122,8 +126,9 @@ async def test_ea_warning_fix(
 
     new_nvr = copy(ufp.api.bootstrap.nvr)
     new_nvr.version = Version("2.2.6")
+    new_nvr.release_channel = "release"
     mock_msg = Mock()
-    mock_msg.changed_data = {"version": "2.2.6"}
+    mock_msg.changed_data = {"version": "2.2.6", "releaseChannel": "release"}
     mock_msg.new_obj = new_nvr
 
     ufp.api.bootstrap.nvr = new_nvr
-- 
GitLab