monsterwell/daemon.py

74 lines
2.5 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()
encrypted: str = GPG().encrypt(raw, config.server.theirkey, sign=config.server.ourkey)
upfl = BytesIO(encrypted.encode())
uppath = Path(config.server.inpath) / f"{directory.name}_{newfile.name}"
with config.server.get_sftp_client() as sftp:
sftp.putfo(upfl, 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):
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: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:41:18 +00:00
(Path(founddir.destinationbackup) / outfile).write_text(decrypted)
2023-01-09 17:18:59 +00:00
2023-01-09 17:41:18 +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}")