monsterwell/daemon.py
2023-01-09 18:03:43 +00:00

77 lines
2.6 KiB
Python

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()
encrypted: str = GPG().encrypt(raw, config.server.theirkey, sign=config.server.ourkey, always_trust=True)
upfl = BytesIO(encrypted.data)
uppath = Path(config.server.inpath) / f"{directory.name}_{newfile.name}.pgp"
with config.server.get_sftp_client() as sftp:
sftp.putfo(upfl, str(uppath))
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):
rpath = str(Path(config.server.outpath) / response)
if (time.time() - sftp.stat(rpath).st_mtime < 60):
continue
encrypted: bytes = sftp.open(rpath).read()
decrypted = GPG().decrypt(encrypted).data.decode()
dirname = response.split("_")[0]
founddir = None
for directory in config.directories:
if directory.name == dirname:
founddir = directory
break
if not founddir:
founddir = directory
if founddir.name == dirname:
outfile = response.split("_")[1:]
else:
outfile = response
outpath = Path(directory.destination) / outfile
if outpath.suffix == ".pgp":
outpath = outpath.with_suffix("")
assert not outpath.exists()
outpath.write_text(decrypted)
if founddir.destinationbackup:
(Path(founddir.destinationbackup) / outpath.name).write_text(decrypted)
sftp.remove(rpath)
except Exception as e:
print(f"Something went wrong downloading files from the server: {e}")