mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 12:50:45 -04:00
Install Marketplace dashboard cards shipped as a ZIP release (#191766)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
Martin Hjelmare
parent
17b78ab0ff
commit
170755d0dc
@@ -2,9 +2,13 @@
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from functools import partial
|
||||
import io
|
||||
from lzma import LZMAError
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, override
|
||||
from urllib.parse import quote
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
from homeassistant.components import lovelace
|
||||
from homeassistant.components.frontend import DATA_EXTRA_MODULE_URL
|
||||
@@ -14,23 +18,46 @@ from ..const import (
|
||||
DASHBOARD_RESOURCE_BASE,
|
||||
DOMAIN,
|
||||
LEGACY_DASHBOARD_RESOURCE_BASE,
|
||||
MAX_DOWNLOAD_SIZE,
|
||||
RESTART_ISSUE_PREFIX,
|
||||
)
|
||||
from ..enums import RepositoryCategory
|
||||
from ..exceptions import CatalogContentUnresolvedError, MarketplaceError
|
||||
from ..utils.decorator import concurrent
|
||||
from ..utils.file_system import async_run_to_completion
|
||||
from ..utils.path import resolve_in_directory
|
||||
from ..utils.tree import (
|
||||
tree_entry_directory,
|
||||
tree_entry_filename,
|
||||
tree_entry_is_directory,
|
||||
)
|
||||
from ..utils.url import github_release_asset, ref_version
|
||||
from .base import FileInformation, Repository
|
||||
from .base import FileInformation, Repository, _check_archive_size, _path_below
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from aiogithubapi.models.release import GitHubReleaseAssetModel
|
||||
|
||||
from ..base import MarketplaceManager
|
||||
|
||||
|
||||
def _archive_name(filename: str) -> str | None:
|
||||
"""Return the name of the ZIP release asset a dashboard resource can ship as."""
|
||||
if not filename.endswith(".js"):
|
||||
return None
|
||||
return f"{filename.removesuffix('.js')}.zip"
|
||||
|
||||
|
||||
def _check_no_file_is_a_folder(members: list[zipfile.ZipInfo]) -> None:
|
||||
"""Refuse members below a file, extracting them fails halfway through."""
|
||||
files = {member.filename for member in members if not member.is_dir()}
|
||||
for member in members:
|
||||
parts = member.filename.rstrip("/").split("/")
|
||||
# A folder entry is a folder itself, a file only its parents are
|
||||
for depth in range(1, len(parts) + member.is_dir()):
|
||||
if (parent := "/".join(parts[:depth])) in files:
|
||||
raise zipfile.BadZipFile(f"{parent} is both a file and a folder")
|
||||
|
||||
|
||||
class PluginRepository(Repository):
|
||||
"""Dashboard resource repository."""
|
||||
|
||||
@@ -70,6 +97,141 @@ class PluginRepository(Repository):
|
||||
f"{self.data.name}.umd.js",
|
||||
)
|
||||
|
||||
@override
|
||||
def _find_target_asset(
|
||||
self, assets: list[GitHubReleaseAssetModel] | None
|
||||
) -> GitHubReleaseAssetModel | None:
|
||||
"""Find the asset that is downloaded, the ZIP of the resource if there is one."""
|
||||
# Counted before the refresh resolves the file name, so taken from the assets
|
||||
names = {asset.name for asset in assets or []}
|
||||
if (filename := self._release_resource_filename(names)) and (
|
||||
archive_name := _archive_name(filename)
|
||||
):
|
||||
for asset in assets or []:
|
||||
if asset.name == archive_name:
|
||||
return asset
|
||||
return super()._find_target_asset(assets)
|
||||
|
||||
@override
|
||||
async def _async_download_files(self, contents: list[FileInformation]) -> None:
|
||||
"""Download the files, a ZIP of the resource instead of the release assets."""
|
||||
if (remaining := await self._async_try_resource_archive(contents)) is not None:
|
||||
await super()._async_download_files(remaining)
|
||||
|
||||
async def _async_try_resource_archive(
|
||||
self, contents: list[FileInformation]
|
||||
) -> list[FileInformation] | None:
|
||||
"""Install the ZIP of the resource, return what is left to download if not."""
|
||||
archive_name = _archive_name(self.data.file_name or "")
|
||||
if self.content.path.remote != "release" or not archive_name:
|
||||
return contents
|
||||
|
||||
for archive in contents:
|
||||
if archive.name != archive_name:
|
||||
continue
|
||||
remaining = [content for content in contents if content is not archive]
|
||||
try:
|
||||
await self._async_install_resource_archive(archive)
|
||||
except MarketplaceError as err:
|
||||
if not any(
|
||||
content.name == self.data.file_name for content in remaining
|
||||
):
|
||||
raise
|
||||
self.logger.warning(
|
||||
"%s %s is not usable, installing %s instead: %s",
|
||||
self.string,
|
||||
archive.name,
|
||||
self.data.file_name,
|
||||
err,
|
||||
)
|
||||
return remaining
|
||||
return None
|
||||
return contents
|
||||
|
||||
async def _async_install_resource_archive(self, archive: FileInformation) -> None:
|
||||
"""Download the ZIP of the resource and extract it."""
|
||||
if not (
|
||||
filecontent := await self.marketplace.async_download_file(
|
||||
archive.download_url, limit=MAX_DOWNLOAD_SIZE
|
||||
)
|
||||
):
|
||||
raise MarketplaceError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="file_not_downloaded",
|
||||
translation_placeholders={"file": archive.name},
|
||||
)
|
||||
await self._async_extract_resource_archive(archive.name, filecontent)
|
||||
|
||||
async def _async_extract_resource_archive(
|
||||
self, name: str, filecontent: bytes
|
||||
) -> None:
|
||||
"""Extract the ZIP of the resource into the local path."""
|
||||
try:
|
||||
await async_run_to_completion(
|
||||
self.marketplace.hass,
|
||||
partial(self._extract_resource_archive, name, filecontent),
|
||||
)
|
||||
except zipfile.BadZipFile as err:
|
||||
raise MarketplaceError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="resource_archive_unusable",
|
||||
translation_placeholders={"file": name},
|
||||
) from err
|
||||
self.logger.info("%s Download of %s completed", self.string, name)
|
||||
|
||||
def _extract_resource_archive(self, name: str, filecontent: bytes) -> None:
|
||||
"""Extract the ZIP of the resource into the local path, this does I/O."""
|
||||
with zipfile.ZipFile(io.BytesIO(filecontent)) as archive:
|
||||
_check_archive_size(archive)
|
||||
if (folder := self._resource_folder(archive.namelist())) is None:
|
||||
raise MarketplaceError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="resource_archive_without_resource",
|
||||
translation_placeholders={
|
||||
"file": name,
|
||||
"resource": self.data.file_name,
|
||||
},
|
||||
)
|
||||
# Read first, a broken member must not leave half an extraction behind
|
||||
try:
|
||||
bad_member = archive.testzip()
|
||||
except (
|
||||
NotImplementedError,
|
||||
RuntimeError,
|
||||
EOFError,
|
||||
OSError,
|
||||
LZMAError,
|
||||
zlib.error,
|
||||
) as err:
|
||||
# Unsupported compression, encrypted members, damaged compressed data
|
||||
raise zipfile.BadZipFile(str(err)) from err
|
||||
if bad_member:
|
||||
raise zipfile.BadZipFile(f"Bad CRC-32 for {bad_member}")
|
||||
members: list[zipfile.ZipInfo] = []
|
||||
for member in archive.infolist():
|
||||
# The folder entry itself and anything next to the folder stay out
|
||||
if not (relative := _path_below(member.filename, folder)):
|
||||
continue
|
||||
member.filename = relative
|
||||
resolve_in_directory(self.content.path.local, relative)
|
||||
members.append(member)
|
||||
_check_no_file_is_a_folder(members)
|
||||
archive.extractall(self.content.path.local, members)
|
||||
|
||||
def _resource_folder(self, names: list[str]) -> str | None:
|
||||
"""Return the folder of the ZIP with the resource, the root is an empty one."""
|
||||
if self.data.file_name in names:
|
||||
return ""
|
||||
# Archives often wrap the content in a single folder, like dist
|
||||
folders = [
|
||||
folder
|
||||
for name in names
|
||||
if name.count("/") == 1
|
||||
and (folder := name.split("/")[0])
|
||||
and name == f"{folder}/{self.data.file_name}"
|
||||
]
|
||||
return folders[0] if len(folders) == 1 else None
|
||||
|
||||
@override
|
||||
def gather_tree_files_to_download(self) -> list[FileInformation]:
|
||||
"""Return the dashboard resource files, from the root or the dist folder."""
|
||||
@@ -230,21 +392,43 @@ class PluginRepository(Repository):
|
||||
"""Resolve the dashboard resource of a catalog version."""
|
||||
if not commit and not self.repository_manifest.content_in_root:
|
||||
# Without the prefix to strip, the first two names are the same
|
||||
for filename in dict.fromkeys(self._valid_filenames()):
|
||||
if filecontent := await self.marketplace.async_download_file(
|
||||
github_release_asset(
|
||||
repository=self.data.full_name,
|
||||
version=version,
|
||||
filename=filename,
|
||||
),
|
||||
nolog=True,
|
||||
filenames = dict.fromkeys(self._valid_filenames())
|
||||
for filename in filenames:
|
||||
if filecontent := await self._async_probe_release_asset(
|
||||
version, filename
|
||||
):
|
||||
return await self._async_resolve_release_assets(
|
||||
version, filename, filecontent
|
||||
)
|
||||
for filename in filenames:
|
||||
if (archive_name := _archive_name(filename)) and (
|
||||
filecontent := await self._async_probe_release_asset(
|
||||
version, archive_name
|
||||
)
|
||||
):
|
||||
self.data.file_name = filename
|
||||
self.content.path.remote = "release"
|
||||
self.content.single = True
|
||||
return partial(
|
||||
self._async_extract_resource_archive,
|
||||
archive_name,
|
||||
filecontent,
|
||||
)
|
||||
|
||||
return await super()._async_resolve_catalog_content(version, commit=commit)
|
||||
|
||||
async def _async_probe_release_asset(
|
||||
self, version: str, filename: str
|
||||
) -> bytes | None:
|
||||
"""Download a release asset without the API, if the release has it."""
|
||||
return await self.marketplace.async_download_file(
|
||||
github_release_asset(
|
||||
repository=self.data.full_name, version=version, filename=filename
|
||||
),
|
||||
nolog=True,
|
||||
limit=MAX_DOWNLOAD_SIZE,
|
||||
)
|
||||
|
||||
async def _async_resolve_release_assets(
|
||||
self, version: str, filename: str, filecontent: bytes
|
||||
) -> Callable[[], Awaitable[None]]:
|
||||
@@ -270,8 +454,12 @@ class PluginRepository(Repository):
|
||||
self, contents: list[FileInformation], filename: str, filecontent: bytes
|
||||
) -> None:
|
||||
"""Download the release assets, the resource itself came with the probe."""
|
||||
# Before the probe is written, its .gz would outlive the resource from the ZIP
|
||||
if (remaining := await self._async_try_resource_archive(contents)) is None:
|
||||
return
|
||||
|
||||
other_assets: list[FileInformation] = []
|
||||
for content in contents:
|
||||
for content in remaining:
|
||||
if content.name == filename:
|
||||
await self._async_write_file(content, filecontent)
|
||||
else:
|
||||
@@ -303,13 +491,24 @@ class PluginRepository(Repository):
|
||||
name its file otherwise.
|
||||
"""
|
||||
contents = await super().release_contents(version)
|
||||
names = {content.name for content in contents or []}
|
||||
for filename in self._valid_filenames():
|
||||
if filename in names:
|
||||
self.data.file_name = filename
|
||||
break
|
||||
if filename := self._release_resource_filename(
|
||||
{content.name for content in contents or []}
|
||||
):
|
||||
self.data.file_name = filename
|
||||
return contents
|
||||
|
||||
def _release_resource_filename(self, asset_names: set[str]) -> str | None:
|
||||
"""Return the resource the release assets have, as a file or a ZIP."""
|
||||
# An unusable ZIP falls back to the file, so a file is the better match
|
||||
filenames = self._valid_filenames()
|
||||
for filename in filenames:
|
||||
if filename in asset_names:
|
||||
return filename
|
||||
for filename in filenames:
|
||||
if _archive_name(filename) in asset_names:
|
||||
return filename
|
||||
return None
|
||||
|
||||
@override
|
||||
def update_filenames(self) -> None:
|
||||
"""Get the filename to target."""
|
||||
@@ -322,16 +521,12 @@ class PluginRepository(Repository):
|
||||
return False
|
||||
|
||||
release = self.releases.objects[0]
|
||||
if release.assets:
|
||||
if assetnames := [
|
||||
filename
|
||||
for filename in self._valid_filenames()
|
||||
for asset in release.assets
|
||||
if filename == asset.name
|
||||
]:
|
||||
self.data.file_name = assetnames[0]
|
||||
self.content.path.remote = "release"
|
||||
return True
|
||||
if filename := self._release_resource_filename(
|
||||
{asset.name for asset in release.assets or []}
|
||||
):
|
||||
self.data.file_name = filename
|
||||
self.content.path.remote = "release"
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@@ -271,6 +271,12 @@
|
||||
"requires_newer_home_assistant": {
|
||||
"message": "This version requires Home Assistant {version} or newer."
|
||||
},
|
||||
"resource_archive_unusable": {
|
||||
"message": "{file} is not a valid ZIP archive."
|
||||
},
|
||||
"resource_archive_without_resource": {
|
||||
"message": "{file} has no {resource} in its root or in a folder at its root."
|
||||
},
|
||||
"restore_failed": {
|
||||
"message": "Could not read the stored data of the Marketplace."
|
||||
},
|
||||
|
||||
@@ -81,8 +81,11 @@
|
||||
dict({
|
||||
'https://github.com/hacs-test-org/plugin-basic/archive/refs/tags/1.0.0.zip': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/1.0.0/plugin-basic-bundle.js': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/1.0.0/plugin-basic-bundle.zip': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/1.0.0/plugin-basic.js': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/1.0.0/plugin-basic.umd.js': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/1.0.0/plugin-basic.umd.zip': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/1.0.0/plugin-basic.zip': 1,
|
||||
'https://raw.githubusercontent.com/hacs-test-org/plugin-basic/1.0.0/hacs.json': 1,
|
||||
})
|
||||
# ---
|
||||
|
||||
@@ -10,8 +10,11 @@
|
||||
dict({
|
||||
'https://github.com/hacs-test-org/plugin-basic/archive/refs/tags/2.0.0.zip': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/2.0.0/plugin-basic-bundle.js': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/2.0.0/plugin-basic-bundle.zip': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/2.0.0/plugin-basic.js': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/2.0.0/plugin-basic.umd.js': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/2.0.0/plugin-basic.umd.zip': 1,
|
||||
'https://github.com/hacs-test-org/plugin-basic/releases/download/2.0.0/plugin-basic.zip': 1,
|
||||
'https://raw.githubusercontent.com/hacs-test-org/plugin-basic/2.0.0/hacs.json': 1,
|
||||
})
|
||||
# ---
|
||||
|
||||
@@ -33,6 +33,7 @@ from yarl import URL
|
||||
|
||||
from homeassistant import loader
|
||||
from homeassistant.components.frontend import DATA_EXTRA_MODULE_URL, UrlManager
|
||||
from homeassistant.components.lovelace import LOVELACE_DATA
|
||||
from homeassistant.components.marketplace.base import (
|
||||
MarketplaceManager,
|
||||
RemovedRepository,
|
||||
@@ -117,6 +118,23 @@ def _zip_bytes(files: dict[str, str]) -> bytes:
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _damaged_zip_bytes(
|
||||
files: dict[str, str], compression: int = zipfile.ZIP_DEFLATED
|
||||
) -> bytes:
|
||||
"""Return a zip archive whose compressed data can not be decompressed."""
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", compression) as archive:
|
||||
for name, content in files.items():
|
||||
archive.writestr(name, content * 1000)
|
||||
info = archive.infolist()[0]
|
||||
content = bytearray(buffer.getvalue())
|
||||
# Past the LZMA properties header, into the compressed data itself
|
||||
data_start = info.header_offset + 30 + len(info.filename) + 16
|
||||
for index in range(data_start, data_start + 20):
|
||||
content[index] ^= 0xFF
|
||||
return bytes(content)
|
||||
|
||||
|
||||
def _installed_files(config_dir: Path) -> list[str]:
|
||||
"""Return every file below the configuration directory, sorted."""
|
||||
return sorted(
|
||||
@@ -3611,6 +3629,446 @@ async def test_integration_manifest_of_a_version(
|
||||
)
|
||||
|
||||
|
||||
PLUGIN_ASSET_URL = (
|
||||
f"https://github.com/{REPOSITORY_PLUGIN}/releases/download/1.0.0/plugin-basic"
|
||||
)
|
||||
ZIP_FALLBACK_FILES = [
|
||||
"www/community/plugin-basic/plugin-basic.js",
|
||||
"www/community/plugin-basic/plugin-basic.js.gz",
|
||||
"www/community/plugin-basic/plugin-basic.js.map",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("github_token", [None])
|
||||
@pytest.mark.parametrize(
|
||||
("zip_response", "resource", "installed"),
|
||||
[
|
||||
pytest.param(
|
||||
{
|
||||
"content": _zip_bytes(
|
||||
{"plugin-basic.js": "from zip", "translations/en.json": "{}"}
|
||||
)
|
||||
},
|
||||
"from zip",
|
||||
[
|
||||
"www/community/plugin-basic/plugin-basic.js",
|
||||
"www/community/plugin-basic/translations/en.json",
|
||||
],
|
||||
id="zip",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"content": _zip_bytes(
|
||||
{
|
||||
"dist/plugin-basic.js": "from zip",
|
||||
"dist/translations/en.json": "{}",
|
||||
"README.md": "",
|
||||
}
|
||||
)
|
||||
},
|
||||
"from zip",
|
||||
[
|
||||
"www/community/plugin-basic/plugin-basic.js",
|
||||
"www/community/plugin-basic/translations/en.json",
|
||||
],
|
||||
id="zip_with_the_resource_in_a_folder",
|
||||
),
|
||||
pytest.param(
|
||||
{"content": _zip_bytes({"dist/card/plugin-basic.js": "from zip"})},
|
||||
"asset",
|
||||
ZIP_FALLBACK_FILES,
|
||||
id="zip_with_the_resource_too_deep",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"content": _zip_bytes(
|
||||
{"a/plugin-basic.js": "from zip", "b/plugin-basic.js": "from zip"}
|
||||
)
|
||||
},
|
||||
"asset",
|
||||
ZIP_FALLBACK_FILES,
|
||||
id="zip_with_the_resource_in_two_folders",
|
||||
),
|
||||
*(
|
||||
pytest.param(
|
||||
{"content": _zip_bytes({"plugin-basic.js": "", **members})},
|
||||
"asset",
|
||||
ZIP_FALLBACK_FILES,
|
||||
id=f"zip_with_a_file_that_is_a_{kind}",
|
||||
)
|
||||
for kind, members in (
|
||||
("parent", {"translations": "", "translations/en.json": "{}"}),
|
||||
("folder_entry", {"translations": "", "translations/": ""}),
|
||||
)
|
||||
),
|
||||
pytest.param(
|
||||
{"content": _zip_bytes({"plugin-basic.js": "", "../outside.js": ""})},
|
||||
"asset",
|
||||
ZIP_FALLBACK_FILES,
|
||||
id="zip_with_a_member_outside_the_card",
|
||||
),
|
||||
pytest.param(
|
||||
{"content": b"not a zip"}, "asset", ZIP_FALLBACK_FILES, id="not_a_zip"
|
||||
),
|
||||
*(
|
||||
pytest.param(
|
||||
{
|
||||
"content": _damaged_zip_bytes(
|
||||
{"plugin-basic.js": "from zip"}, compression
|
||||
)
|
||||
},
|
||||
"asset",
|
||||
ZIP_FALLBACK_FILES,
|
||||
id=f"damaged_{name}_zip",
|
||||
)
|
||||
for name, compression in (
|
||||
("deflate", zipfile.ZIP_DEFLATED),
|
||||
("bzip2", zipfile.ZIP_BZIP2),
|
||||
("lzma", zipfile.ZIP_LZMA),
|
||||
)
|
||||
),
|
||||
pytest.param(
|
||||
{"status": HTTPStatus.NOT_FOUND},
|
||||
"asset",
|
||||
ZIP_FALLBACK_FILES,
|
||||
id="zip_not_downloaded",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_install_plugin_from_the_catalog_prefers_the_resource_zip(
|
||||
hass: HomeAssistant,
|
||||
marketplace: MarketplaceManager,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
response_mocker: MarketplaceResponses,
|
||||
config_dir: Path,
|
||||
zip_response: dict[str, Any],
|
||||
resource: str,
|
||||
installed: list[str],
|
||||
) -> None:
|
||||
"""Test a release with a ZIP named like the resource installs the ZIP if usable."""
|
||||
repository = marketplace.repositories.get_by_full_name(REPOSITORY_PLUGIN)
|
||||
release_url = (
|
||||
f"https://api.github.com/repos/{REPOSITORY_PLUGIN}/releases/tags/1.0.0"
|
||||
)
|
||||
for url, response in (
|
||||
(f"{PLUGIN_ASSET_URL}.js", {"content": b"asset"}),
|
||||
(f"{PLUGIN_ASSET_URL}.js.map", {"content": b"map"}),
|
||||
(f"{PLUGIN_ASSET_URL}.zip", zip_response),
|
||||
(
|
||||
release_url,
|
||||
{
|
||||
"json_content": {
|
||||
"assets": [
|
||||
{
|
||||
"name": name,
|
||||
"browser_download_url": f"{PLUGIN_ASSET_URL}{ext}",
|
||||
}
|
||||
for name, ext in (
|
||||
("plugin-basic.js", ".js"),
|
||||
("plugin-basic.js.map", ".js.map"),
|
||||
("plugin-basic.zip", ".zip"),
|
||||
)
|
||||
]
|
||||
}
|
||||
},
|
||||
),
|
||||
):
|
||||
response_mocker.add(url, mocked_response(url, **response))
|
||||
|
||||
assert (await _install(hass, hass_ws_client, repository.data.id))["success"]
|
||||
|
||||
assert _installed_files(config_dir) == installed
|
||||
assert (
|
||||
config_dir / "www/community/plugin-basic/plugin-basic.js"
|
||||
).read_text() == resource
|
||||
assert [
|
||||
item["url"] for item in hass.data[LOVELACE_DATA].resources.async_items()
|
||||
] == [_plugin_resource_url("plugin-basic.js")]
|
||||
|
||||
|
||||
def _plugin_resource_url(name: str) -> str:
|
||||
"""Return the URL of the dashboard resource the card registered."""
|
||||
return f"/local/community/plugin-basic/{name}?v=1296267-1.0.0"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("github_token", [None])
|
||||
@pytest.mark.parametrize(
|
||||
("members", "installed"),
|
||||
[
|
||||
pytest.param(
|
||||
{"plugin-basic.js": "from zip"},
|
||||
["www/community/plugin-basic/plugin-basic.js"],
|
||||
id="zip",
|
||||
),
|
||||
pytest.param(
|
||||
{"other.js": "from zip"},
|
||||
[
|
||||
"www/community/plugin-basic/plugin-basic.js",
|
||||
"www/community/plugin-basic/plugin-basic.js.gz",
|
||||
],
|
||||
id="zip_without_the_resource",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_install_plugin_from_github_prefers_the_resource_zip(
|
||||
hass: HomeAssistant,
|
||||
marketplace: MarketplaceManager,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
response_mocker: MarketplaceResponses,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
config_dir: Path,
|
||||
members: dict[str, str],
|
||||
installed: list[str],
|
||||
) -> None:
|
||||
"""Test the release assets the GitHub API lists are replaced by a usable ZIP."""
|
||||
repository = marketplace.repositories.get_by_full_name(REPOSITORY_PLUGIN)
|
||||
# Without a release in the catalog, the install goes through the GitHub API
|
||||
repository.data.last_version = None
|
||||
repository.data.last_commit = "abc1234"
|
||||
assets = [
|
||||
{
|
||||
"name": f"plugin-basic{ext}",
|
||||
"browser_download_url": f"{PLUGIN_ASSET_URL}{ext}",
|
||||
"download_count": download_count,
|
||||
}
|
||||
for ext, download_count in ((".js", 100), (".zip", 300))
|
||||
]
|
||||
releases_url = f"https://api.github.com/repos/{REPOSITORY_PLUGIN}/releases"
|
||||
for url, response in (
|
||||
(f"{PLUGIN_ASSET_URL}.js", {"content": b"asset"}),
|
||||
(f"{PLUGIN_ASSET_URL}.zip", {"content": _zip_bytes(members)}),
|
||||
(
|
||||
releases_url,
|
||||
{
|
||||
"json_content": [
|
||||
{"tag_name": "1.0.0", "prerelease": False, "assets": assets}
|
||||
]
|
||||
},
|
||||
),
|
||||
(f"{releases_url}/tags/1.0.0", {"json_content": {"assets": assets}}),
|
||||
):
|
||||
response_mocker.add(url, mocked_response(url, **response), keep=True)
|
||||
aioclient_mock.mock_calls.clear()
|
||||
|
||||
assert (await _install(hass, hass_ws_client, repository.data.id))["success"]
|
||||
client = await hass_ws_client(hass)
|
||||
await client.send_json_auto_id(
|
||||
{"type": "marketplace/repository/refresh", "repository": repository.data.id}
|
||||
)
|
||||
assert (await client.receive_json())["success"]
|
||||
|
||||
assert github_api_calls(aioclient_mock)
|
||||
assert _installed_files(config_dir) == installed
|
||||
assert [
|
||||
item["url"] for item in hass.data[LOVELACE_DATA].resources.async_items()
|
||||
] == [_plugin_resource_url("plugin-basic.js")]
|
||||
# Installs download the ZIP, so its downloads are the ones that count
|
||||
assert repository.data.downloads == 300
|
||||
|
||||
|
||||
@pytest.mark.parametrize("github_token", [None])
|
||||
async def test_plugin_downloads_are_counted_from_the_resource_zip(
|
||||
hass: HomeAssistant,
|
||||
marketplace: MarketplaceManager,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
response_mocker: MarketplaceResponses,
|
||||
) -> None:
|
||||
"""Test the first refresh counts the ZIP, before the resource is resolved."""
|
||||
repository = marketplace.repositories.get_by_full_name(REPOSITORY_PLUGIN)
|
||||
url = f"https://api.github.com/repos/{REPOSITORY_PLUGIN}/releases"
|
||||
response_mocker.add(
|
||||
url,
|
||||
mocked_response(
|
||||
url,
|
||||
json_content=[
|
||||
{
|
||||
"tag_name": "1.0.0",
|
||||
"prerelease": False,
|
||||
"assets": [
|
||||
{"name": "plugin-basic.js", "download_count": 100},
|
||||
{"name": "plugin-basic.zip", "download_count": 300},
|
||||
],
|
||||
}
|
||||
],
|
||||
),
|
||||
keep=True,
|
||||
)
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
await client.send_json_auto_id(
|
||||
{"type": "marketplace/repository/refresh", "repository": repository.data.id}
|
||||
)
|
||||
|
||||
assert (await client.receive_json())["success"]
|
||||
assert repository.data.downloads == 300
|
||||
|
||||
|
||||
@pytest.mark.parametrize("github_token", [None])
|
||||
async def test_install_plugin_from_github_prefers_a_file_over_a_zip_of_another_name(
|
||||
hass: HomeAssistant,
|
||||
marketplace: MarketplaceManager,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
response_mocker: MarketplaceResponses,
|
||||
config_dir: Path,
|
||||
) -> None:
|
||||
"""Test a ZIP named like another resource does not hide the resource file."""
|
||||
repository = marketplace.repositories.get_by_full_name(REPOSITORY_PLUGIN)
|
||||
repository.data.last_version = None
|
||||
repository.data.last_commit = "abc1234"
|
||||
assets = [
|
||||
{
|
||||
"name": f"plugin-basic{ext}",
|
||||
"browser_download_url": f"{PLUGIN_ASSET_URL}{ext}",
|
||||
}
|
||||
for ext in (".umd.js", ".zip")
|
||||
]
|
||||
releases_url = f"https://api.github.com/repos/{REPOSITORY_PLUGIN}/releases"
|
||||
for url, response in (
|
||||
(f"{PLUGIN_ASSET_URL}.umd.js", {"content": b"asset"}),
|
||||
(f"{PLUGIN_ASSET_URL}.zip", {"content": _zip_bytes({"other.js": ""})}),
|
||||
(
|
||||
releases_url,
|
||||
{
|
||||
"json_content": [
|
||||
{"tag_name": "1.0.0", "prerelease": False, "assets": assets}
|
||||
]
|
||||
},
|
||||
),
|
||||
(f"{releases_url}/tags/1.0.0", {"json_content": {"assets": assets}}),
|
||||
):
|
||||
response_mocker.add(url, mocked_response(url, **response), keep=True)
|
||||
|
||||
assert (await _install(hass, hass_ws_client, repository.data.id))["success"]
|
||||
|
||||
assert (
|
||||
config_dir / "www/community/plugin-basic/plugin-basic.umd.js"
|
||||
).read_text() == "asset"
|
||||
assert [
|
||||
item["url"] for item in hass.data[LOVELACE_DATA].resources.async_items()
|
||||
] == [_plugin_resource_url("plugin-basic.umd.js")]
|
||||
|
||||
|
||||
def _serve_plugin_zip_alone(
|
||||
response_mocker: MarketplaceResponses, archive: bytes
|
||||
) -> None:
|
||||
"""Serve a release that ships the dashboard resource only as a ZIP."""
|
||||
releases_url = f"https://api.github.com/repos/{REPOSITORY_PLUGIN}/releases"
|
||||
assets = [
|
||||
{
|
||||
"name": "plugin-basic.zip",
|
||||
"browser_download_url": f"{PLUGIN_ASSET_URL}.zip",
|
||||
"download_count": 300,
|
||||
}
|
||||
]
|
||||
for url, response in (
|
||||
(f"{PLUGIN_ASSET_URL}.js", {"status": HTTPStatus.NOT_FOUND}),
|
||||
(f"{PLUGIN_ASSET_URL}.zip", {"content": archive}),
|
||||
(
|
||||
releases_url,
|
||||
{
|
||||
"json_content": [
|
||||
{"tag_name": "1.0.0", "prerelease": False, "assets": assets}
|
||||
]
|
||||
},
|
||||
),
|
||||
(f"{releases_url}/tags/1.0.0", {"json_content": {"assets": assets}}),
|
||||
):
|
||||
response_mocker.add(url, mocked_response(url, **response), keep=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("github_token", [None])
|
||||
@pytest.mark.parametrize(
|
||||
("last_version", "api_calls"),
|
||||
[
|
||||
pytest.param("1.0.0", False, id="catalog"),
|
||||
# Without a release in the catalog, the install goes through the GitHub API
|
||||
pytest.param(None, True, id="github"),
|
||||
],
|
||||
)
|
||||
async def test_install_plugin_with_only_a_zip(
|
||||
hass: HomeAssistant,
|
||||
marketplace: MarketplaceManager,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
response_mocker: MarketplaceResponses,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
config_dir: Path,
|
||||
last_version: str | None,
|
||||
api_calls: bool,
|
||||
) -> None:
|
||||
"""Test a release with only a ZIP named like the resource installs the ZIP."""
|
||||
repository = marketplace.repositories.get_by_full_name(REPOSITORY_PLUGIN)
|
||||
repository.data.last_version = last_version
|
||||
repository.data.last_commit = "abc1234"
|
||||
_serve_plugin_zip_alone(
|
||||
response_mocker,
|
||||
_zip_bytes({"plugin-basic.js": "from zip", "translations/en.json": "{}"}),
|
||||
)
|
||||
aioclient_mock.mock_calls.clear()
|
||||
|
||||
assert (await _install(hass, hass_ws_client, repository.data.id))["success"]
|
||||
|
||||
assert bool(github_api_calls(aioclient_mock)) is api_calls
|
||||
assert _installed_files(config_dir) == [
|
||||
"www/community/plugin-basic/plugin-basic.js",
|
||||
"www/community/plugin-basic/translations/en.json",
|
||||
]
|
||||
assert [
|
||||
item["url"] for item in hass.data[LOVELACE_DATA].resources.async_items()
|
||||
] == [_plugin_resource_url("plugin-basic.js")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("github_token", [None])
|
||||
@pytest.mark.parametrize(
|
||||
"last_version",
|
||||
[
|
||||
pytest.param("1.0.0", id="catalog"),
|
||||
pytest.param(None, id="github"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("archive", "error"),
|
||||
[
|
||||
pytest.param(
|
||||
_zip_bytes({"dist/card/plugin-basic.js": "from zip"}),
|
||||
"plugin-basic.zip has no plugin-basic.js in its root or in a folder",
|
||||
id="without_the_resource",
|
||||
),
|
||||
pytest.param(
|
||||
_zip_bytes({"plugin-basic.js": "", "../outside.js": ""}),
|
||||
"../outside.js",
|
||||
id="member_outside_the_card",
|
||||
),
|
||||
pytest.param(
|
||||
_damaged_zip_bytes({"plugin-basic.js": "from zip"}),
|
||||
"plugin-basic.zip is not a valid ZIP archive",
|
||||
id="damaged",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_install_plugin_with_only_an_unusable_zip_is_refused(
|
||||
hass: HomeAssistant,
|
||||
marketplace: MarketplaceManager,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
response_mocker: MarketplaceResponses,
|
||||
config_dir: Path,
|
||||
last_version: str | None,
|
||||
archive: bytes,
|
||||
error: str,
|
||||
) -> None:
|
||||
"""Test a ZIP without a JavaScript asset to fall back to fails the install."""
|
||||
repository = marketplace.repositories.get_by_full_name(REPOSITORY_PLUGIN)
|
||||
repository.data.last_version = last_version
|
||||
repository.data.last_commit = "abc1234"
|
||||
_serve_plugin_zip_alone(response_mocker, archive)
|
||||
|
||||
response = await _install(hass, hass_ws_client, repository.data.id)
|
||||
|
||||
assert not response["success"]
|
||||
assert error in response["error"]["message"]
|
||||
assert repository.data.installed is False
|
||||
assert _installed_files(config_dir) == []
|
||||
|
||||
|
||||
async def test_catalog_zip_release_needs_a_domain(
|
||||
marketplace: MarketplaceManager,
|
||||
) -> None:
|
||||
|
||||
Reference in New Issue
Block a user