Добавил функцию удаления папок которых нет в списке для обновления. Организовал main. Пока остались тестовые комментарии.
204 lines
6.4 KiB
Python
204 lines
6.4 KiB
Python
import json
|
|
import shutil
|
|
from structs import CertInfo, DSMCredentials,ApplSettings
|
|
from pathlib import Path
|
|
from dataclasses import asdict
|
|
import logging
|
|
from configparser import ConfigParser
|
|
from caddy_worker import CaddyWorker
|
|
|
|
class ServiceFunctions:
|
|
|
|
def save_cert_info(self, cert_info: CertInfo, path_to_save_folder: Path):
|
|
data = asdict(cert_info)
|
|
|
|
save_dir = path_to_save_folder / cert_info.dir_caddy_cert.name
|
|
save_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
data["expires_at"] = cert_info.expires_at.isoformat()
|
|
data["path_to_key"] = str(cert_info.path_to_key)
|
|
data["dir_caddy_cert"] = str(cert_info.dir_caddy_cert)
|
|
|
|
(save_dir / cert_info.dir_caddy_cert.name).write_text(
|
|
json.dumps(data, indent=4, ensure_ascii=False),
|
|
encoding="utf-8"
|
|
)
|
|
return save_dir
|
|
|
|
|
|
@staticmethod
|
|
def get_login_pass_from_file(path_to_file: Path):
|
|
|
|
if not path_to_file.is_file():
|
|
logging.error(f"Secret file not found: {path_to_file}")
|
|
return None
|
|
|
|
try:
|
|
lines = path_to_file.read_text(encoding="utf-8").splitlines()
|
|
except OSError as e:
|
|
logging.error(f"Cannot read secret file {path_to_file}: {e}")
|
|
return None
|
|
|
|
secret = {}
|
|
|
|
for line in lines:
|
|
line = line.strip()
|
|
|
|
if not line or "=" not in line:
|
|
continue
|
|
|
|
key, value = line.split("=", 1)
|
|
secret[key.strip()] = value.strip()
|
|
|
|
user_name = secret.get("username")
|
|
password = secret.get("password")
|
|
|
|
if not user_name:
|
|
logging.error("user_name is not specified in secret")
|
|
return None
|
|
|
|
if not password:
|
|
logging.error("password is not specified in secret")
|
|
return None
|
|
|
|
return DSMCredentials(
|
|
user_name=user_name,
|
|
password=password,
|
|
)
|
|
|
|
|
|
def load_config(self):
|
|
|
|
config_path = Path(__file__).parent / "config.conf"
|
|
if not config_path.is_file():
|
|
logging.error(f"Config file not found: {config_path}")
|
|
raise FileNotFoundError(f"Config file not found: {config_path}")
|
|
|
|
config = ConfigParser(allow_no_value=True)
|
|
config.read(config_path, encoding="utf-8")
|
|
|
|
domains = list(config["ListDomains"].keys())
|
|
|
|
|
|
appl_settings = ApplSettings(
|
|
list_domains = domains,
|
|
path_to_caddy_cert = Path(config.get("Settings", "pathToCaddyCert")),
|
|
credentials = config.get("Settings", "pathToCredentials"),
|
|
path_to_save_folder = Path(config.get("Settings", "pathToSaveFolder")),
|
|
nas_url = config.get("Settings", "urlNas"),
|
|
)
|
|
return appl_settings
|
|
|
|
|
|
def search_caddy_cert(self, path_to_caddy_cert: Path, list_domains: list):
|
|
update_certs = []
|
|
|
|
if not path_to_caddy_cert.is_dir():
|
|
logging.error(f"Caddy cert folder <{path_to_caddy_cert}> not found")
|
|
return None
|
|
|
|
if not list_domains:
|
|
logging.error(f"List Domains is empty")
|
|
return None
|
|
|
|
|
|
for domain in list_domains:
|
|
folder = path_to_caddy_cert / domain
|
|
|
|
if folder.is_dir():
|
|
update_certs.append(domain)
|
|
else:
|
|
logging.warning(f"Cert <{domain}> not found in Caddy Folder")
|
|
|
|
return update_certs
|
|
|
|
@staticmethod
|
|
def remove_unnecessary_dsm_certs(path_to_dsm_certs_data: Path, list_domains: list):
|
|
|
|
if not path_to_dsm_certs_data.is_dir():
|
|
logging.error(f"DSM cert folder <{path_to_dsm_certs_data}> not found")
|
|
return False
|
|
|
|
if not list_domains:
|
|
logging.error(f"List Domains is empty")
|
|
return False
|
|
|
|
for folder in path_to_dsm_certs_data.iterdir():
|
|
|
|
if not folder.is_dir():
|
|
continue
|
|
|
|
if folder.name not in list_domains:
|
|
logging.info(
|
|
f"Removing unnecessary DSM certificate: {folder.name}"
|
|
)
|
|
|
|
try:
|
|
shutil.rmtree(folder)
|
|
except OSError as e:
|
|
logging.error(
|
|
f"Cannot remove folder {folder}: {e}"
|
|
)
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
def check_update_certs(self, path_to_dsm_certs_data: Path, path_to_caddy_certs: Path, candidates_update_certs: list):
|
|
|
|
if not path_to_dsm_certs_data.is_dir():
|
|
logging.error(f"Path to certs dir not found: {path_to_dsm_certs_data}")
|
|
return []
|
|
|
|
if not candidates_update_certs:
|
|
logging.error(f"List Update is empty: {candidates_update_certs}")
|
|
return []
|
|
|
|
need_update_certs = []
|
|
|
|
for cert in candidates_update_certs:
|
|
|
|
cert_folder = path_to_dsm_certs_data / cert
|
|
|
|
if not cert_folder.is_dir():
|
|
need_update_certs.append(cert)
|
|
continue
|
|
|
|
path_to_caddy_cert = CaddyWorker.search_cert_caddy(path_to_caddy_certs, cert)
|
|
|
|
if path_to_caddy_cert is None:
|
|
logging.error(f"Caddy cert not found: {cert}")
|
|
continue
|
|
|
|
caddy_cert_info = CaddyWorker.get_cert_info(path_to_caddy_cert)
|
|
if caddy_cert_info is None:
|
|
logging.error(f"Unable to read Caddy certificate: {cert}")
|
|
continue
|
|
|
|
#Информация о сертификате который загружен в DSM
|
|
dsm_cert_info = cert_folder / cert
|
|
|
|
if dsm_cert_info.is_file() is False:
|
|
logging.error(f"Cert not found: {dsm_cert_info}")
|
|
continue
|
|
|
|
with open(dsm_cert_info, "r", encoding='utf-8') as file:
|
|
data_dsm_cert = json.load(file)
|
|
|
|
if data_dsm_cert["domain_name"] != caddy_cert_info.domain_name:
|
|
logging.info(
|
|
f"Cert DSM: {data_dsm_cert['domain_name']} "
|
|
f"is not located in the caddy cert "
|
|
f"{caddy_cert_info.domain_name} folder"
|
|
)
|
|
continue
|
|
|
|
if data_dsm_cert["fingerprint"] != caddy_cert_info.fingerprint:
|
|
need_update_certs.append(cert)
|
|
logging.info(f"Cert: {cert} added to update")
|
|
else:
|
|
logging.info(f"Cert: {cert} does not require update")
|
|
|
|
return need_update_certs
|
|
|