monsterwell/daemon.py

77 lines
2.6 KiB
Python
Raw Normal View History

2023-01-09 17:18:59 +00:00
from classes.config import Config
from pathlib import Path
from io import BytesIO
import time
from gnupg import GPG
if __name__ == "__main__":
config = Config.from_file(Path(__file__).parent / "settings.ini")
for directory in config.directories:
source = Path(directory.source)
for newfile in source.iterdir():
if newfile.is_file() and (time.time() - newfile.stat().st_mtime > 60):
try:
raw = newfile.read_text()
2023-01-09 18:03:43 +00:00
encrypted: str = GPG().encrypt(raw, config.server.theirkey, sign=config.server.ourkey, always_trust=True)
2023-01-09 17:51:26 +00:00
upfl = BytesIO(encrypted.data)
2023-01-09 17:45:22 +00:00
uppath = Path(config.server.inpath) / f"{directory.name}_{newfile.name}.pgp"
2023-01-09 17:18:59 +00:00
with config.server.get_sftp_client() as sftp:
2023-01-09 17:51:26 +00:00
sftp.putfo(upfl, str(uppath))
2023-01-09 17:18:59 +00:00
if directory.sourcebackup:
newfile.rename(Path(directory.sourcebackup) / newfile.name)
else:
newfile.unlink()
except Exception as e:
print(f"Something went wrong uploading file {newfile.name} from {directory.name}: {e}")
try:
with config.server.get_sftp_client() as sftp:
for response in sftp.listdir(config.server.outpath):
2023-01-09 17:41:18 +00:00
rpath = str(Path(config.server.outpath) / response)
if (time.time() - sftp.stat(rpath).st_mtime < 60):
2023-01-09 17:18:59 +00:00
continue
2023-01-09 17:41:18 +00:00
encrypted: bytes = sftp.open(rpath).read()
decrypted = GPG().decrypt(encrypted).data.decode()
2023-01-09 17:18:59 +00:00
2023-01-09 17:41:18 +00:00
dirname = response.split("_")[0]
2023-01-09 17:18:59 +00:00
founddir = None
for directory in config.directories:
if directory.name == dirname:
founddir = directory
break
if not founddir:
founddir = directory
2023-01-09 17:41:18 +00:00
if founddir.name == dirname:
outfile = response.split("_")[1:]
else:
outfile = response
2023-01-09 17:18:59 +00:00
2023-01-09 17:41:18 +00:00
outpath = Path(directory.destination) / outfile
2023-01-09 17:18:59 +00:00
2023-01-09 17:45:22 +00:00
if outpath.suffix == ".pgp":
outpath = outpath.with_suffix("")
2023-01-09 17:41:18 +00:00
assert not outpath.exists()
outpath.write_text(decrypted)
2023-01-09 17:18:59 +00:00
if founddir.destinationbackup:
2023-01-09 17:45:22 +00:00
(Path(founddir.destinationbackup) / outpath.name).write_text(decrypted)
2023-01-09 17:18:59 +00:00
2023-01-09 17:45:22 +00:00
sftp.remove(rpath)
2023-01-09 17:18:59 +00:00
2023-01-09 17:41:18 +00:00
except Exception as e:
print(f"Something went wrong downloading files from the server: {e}")