Add new "ui" type for plugins

This commit is contained in:
Théophile Diot 2024-08-19 16:49:52 +01:00
parent a681284bf7
commit 955f2a4cea
No known key found for this signature in database
GPG key ID: FA995104A0BA376A
7 changed files with 29 additions and 13 deletions

View file

@ -295,9 +295,7 @@ class CLI(ApiCaller):
command_path = (
Path(sep, "usr", "share", "bunkerweb", "core", plugin_id)
if plugin_type == "core"
else (
Path(sep, "etc", "bunkerweb", "plugins", plugin_id) if plugin_type == "external" else Path(sep, "etc", "bunkerweb", "pro", "plugins", plugin_id)
)
else (Path(sep, "etc", "bunkerweb", "pro", "plugins", plugin_id) if plugin_type == "pro" else Path(sep, "etc", "bunkerweb", "plugins", plugin_id))
).joinpath("bwcli", file_name)
if not command_path.is_file():

View file

@ -76,7 +76,7 @@ try:
data["pro_plugins"] = []
for plugin in JOB.db.get_plugins():
if plugin["type"] == "external":
if plugin["type"] in ("external", "ui"):
data["external_plugins"].append(f"{plugin['id']}/{plugin['version']}")
elif plugin["type"] == "pro":
data["pro_plugins"].append(f"{plugin['id']}/{plugin['version']}")

View file

@ -2151,9 +2151,9 @@ class Database:
self.logger.warning(f'Plugin "{plugin["id"]}" already exists, but the method is different, skipping update')
continue
if db_plugin.type not in ("external", "pro"):
if db_plugin.type not in ("external", "ui", "pro"):
self.logger.warning(
f"Plugin \"{plugin['id']}\" is not {_type}, skipping update (updating a non-external or non-pro plugin is forbidden for security reasons)", # noqa: E501
f"Plugin \"{plugin['id']}\" is not {_type}, skipping update (updating a non-external, non-ui or non-pro plugin is forbidden for security reasons)", # noqa: E501
)
continue
@ -2856,7 +2856,7 @@ class Database:
with suppress(ProgrammingError, OperationalError):
metadata = session.query(Metadata).get(1)
if metadata is not None:
if _type == "external":
if _type in ("external", "ui"):
metadata.external_plugins_changed = True
metadata.last_external_plugins_change = datetime.now(timezone.utc)
elif _type == "pro":
@ -2897,13 +2897,23 @@ class Database:
Template_custom_configs.template_id.in_(session.query(Templates).filter_by(plugin_id=plugin_id).with_entities(Templates.id))
).delete()
with suppress(ProgrammingError, OperationalError):
metadata = session.query(Metadata).get(1)
if metadata is not None:
if method in ("external", "ui"):
metadata.external_plugins_changed = True
metadata.last_external_plugins_change = datetime.now(timezone.utc)
elif method == "pro":
metadata.pro_plugins_changed = True
metadata.last_pro_plugins_change = datetime.now(timezone.utc)
try:
session.commit()
except BaseException as e:
return str(e)
return ""
def get_plugins(self, *, _type: Literal["all", "external", "pro"] = "all", with_data: bool = False) -> List[Dict[str, Any]]:
def get_plugins(self, *, _type: Literal["all", "external", "ui", "pro"] = "all", with_data: bool = False) -> List[Dict[str, Any]]:
"""Get all plugins from the database."""
plugins = []
with self._db_session() as session:
@ -2912,7 +2922,9 @@ class Database:
entities.append(Plugins.data) # type: ignore
db_plugins = session.query(Plugins).with_entities(*entities)
if _type != "all":
if _type == "external":
db_plugins = db_plugins.filter(Plugins.method.in_(["external", "ui"]))
elif _type != "all":
db_plugins = db_plugins.filter_by(type=_type)
for plugin in db_plugins:

View file

@ -621,7 +621,7 @@ if __name__ == "__main__":
# Check if any external or pro plugin has been added by the user
assert SCHEDULER is not None, "SCHEDULER is not defined"
LOGGER.info(f"Checking if there are any changes in {_type} plugins ...")
plugin_path = EXTERNAL_PLUGINS_PATH if _type == "external" else PRO_PLUGINS_PATH
plugin_path = PRO_PLUGINS_PATH if _type == "pro" else EXTERNAL_PLUGINS_PATH
db_plugins = SCHEDULER.db.get_plugins(_type=_type)
external_plugins = []
tmp_external_plugins = []

View file

@ -247,7 +247,7 @@ def plugins_page():
new_plugins.append(
plugin_file
| {
"type": "external",
"type": "ui",
"page": "ui" in listdir(str(temp_folder_path)),
"method": "ui",
"data": value,
@ -355,6 +355,12 @@ def delete_plugin():
if DB.readonly:
return {"status": "ko", "message": "Database is in read-only mode"}, 403
verify_data_in_form(
data={"csrf_token": None},
err_message="Missing csrf_token parameter on /plugins/delete.",
redirect_url="plugins",
next=True,
)
verify_data_in_form(
data={"plugin_name": None},
err_message="Missing plugin name parameter on /plugins/delete.",

View file

@ -121,7 +121,7 @@ def manage_bunkerweb(method: str, *args, operation: str = "reloads", is_draft: b
def verify_data_in_form(
data: Optional[Dict[str, Union[Tuple, Any]]] = None, err_message: str = "", redirect_url: str = "", next: bool = False
) -> Union[bool, Response]:
if not request.json:
if not request.form:
return handle_error("Invalid request", redirect_url, next, "error")
LOGGER.debug(f"Verifying data in form: {data}")

View file

@ -59,7 +59,7 @@ class Config:
**self.__settings,
}
def get_plugins(self, *, _type: Literal["all", "external", "pro"] = "all", with_data: bool = False) -> List[dict]:
def get_plugins(self, *, _type: Literal["all", "external", "ui", "pro"] = "all", with_data: bool = False) -> List[dict]:
plugins = self.__db.get_plugins(_type=_type, with_data=with_data)
plugins.sort(key=itemgetter("name"))