74 lines
3.2 KiB
Python
74 lines
3.2 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from pathlib import Path
|
||
|
|
from tkinter import messagebox, filedialog as fd
|
||
|
|
|
||
|
|
|
||
|
|
class IntegrityTools:
|
||
|
|
"""Операции сохранения и проверки хэша БД."""
|
||
|
|
|
||
|
|
def __init__(self, integrity_checker, audit_logger, db_path: str | None):
|
||
|
|
self.integrity_checker = integrity_checker
|
||
|
|
self.audit_logger = audit_logger
|
||
|
|
self.db_path = Path(db_path) if db_path else None
|
||
|
|
|
||
|
|
def set_db_path(self, db_path: str | None) -> None:
|
||
|
|
self.db_path = Path(db_path) if db_path else None
|
||
|
|
|
||
|
|
def _hash_path(self) -> Path:
|
||
|
|
return self.db_path.with_suffix(self.db_path.suffix + ".hash")
|
||
|
|
|
||
|
|
def save_db_hash(self):
|
||
|
|
if not self.db_path:
|
||
|
|
messagebox.showwarning("Сохранить хэш", "База данных не выбрана.")
|
||
|
|
return
|
||
|
|
if not self.db_path.exists():
|
||
|
|
messagebox.showwarning(
|
||
|
|
"Сохранить хэш", f"Файл БД не найден:\n{self.db_path}")
|
||
|
|
return
|
||
|
|
suggested = self.db_path.with_suffix(self.db_path.suffix + ".hash")
|
||
|
|
path = fd.asksaveasfilename(
|
||
|
|
title="Сохранить контрольную сумму БД",
|
||
|
|
defaultextension=".hash",
|
||
|
|
filetypes=[("Hash file", "*.hash"), ("All files", "*.*")],
|
||
|
|
initialdir=str(suggested.parent),
|
||
|
|
initialfile=suggested.name,
|
||
|
|
)
|
||
|
|
if not path:
|
||
|
|
return
|
||
|
|
try:
|
||
|
|
self.integrity_checker.save_hash(str(self.db_path), str(path))
|
||
|
|
except Exception as e:
|
||
|
|
messagebox.showerror("Сохранить хэш", f"Ошибка сохранения:\n{e}")
|
||
|
|
return
|
||
|
|
self.audit_logger.log(
|
||
|
|
f"Сохранена контрольная сумма БД → {Path(path).name}")
|
||
|
|
messagebox.showinfo("Сохранить хэш", f"Хэш сохранён в {path}")
|
||
|
|
|
||
|
|
def verify_db_hash(self):
|
||
|
|
if not self.db_path:
|
||
|
|
messagebox.showwarning(
|
||
|
|
"Проверка целостности", "База данных не выбрана.")
|
||
|
|
return
|
||
|
|
if not self.db_path.exists():
|
||
|
|
messagebox.showwarning(
|
||
|
|
"Проверка целостности", f"Файл БД не найден:\n{self.db_path}")
|
||
|
|
return
|
||
|
|
suggested = self.db_path.with_suffix(self.db_path.suffix + ".hash")
|
||
|
|
path = fd.askopenfilename(
|
||
|
|
title="Выбрать файл контрольной суммы БД",
|
||
|
|
filetypes=[("Hash file", "*.hash"), ("All files", "*.*")],
|
||
|
|
initialdir=str(suggested.parent),
|
||
|
|
initialfile=suggested.name,
|
||
|
|
)
|
||
|
|
if not path:
|
||
|
|
return
|
||
|
|
ok = self.integrity_checker.verify_hash(str(self.db_path), str(path))
|
||
|
|
self.audit_logger.log("Проверка целостности БД: " +
|
||
|
|
("OK" if ok else "НЕСОВПАДЕНИЕ"))
|
||
|
|
if ok:
|
||
|
|
messagebox.showinfo("Проверка целостности", "БД в целостности.")
|
||
|
|
else:
|
||
|
|
messagebox.showerror("Проверка целостности",
|
||
|
|
"БД была изменена извне.")
|