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):
|
|
|
|
if (time.time() - sftp.stat(response).st_mtime < 60):
|
|
|
|
continue
|
|
|
|
|
|
|
|
encrypted: bytes = sftp.open(response).read()
|
|
|
|
decrypted = GPG().decrypt(encrypted)
|
|
|
|
|
|
|
|
dirname = Path(outpath).name.split("_")[0]
|
|
|
|
|
|
|
|
founddir = None
|
|
|
|
|
|
|
|
for directory in config.directories:
|
|
|
|
if directory.name == dirname:
|
|
|
|
founddir = directory
|
|
|
|
break
|
|
|
|
|
|
|
|
if not founddir:
|
|
|
|
founddir = directory
|
|
|
|
|
|
|
|
outfile = Path("_".join(Path(outpath).name.split("_")[1:]))
|
|
|
|
|
|
|
|
assert not outfile.exists()
|
|
|
|
|
|
|
|
outfile.write_text(decrypted)
|
|
|
|
|
|
|
|
if founddir.destinationbackup:
|
|
|
|
(Path(founddir.destinationbackup) / outfile.name).write_text(decrypted)
|
|
|
|
|
|
|
|
sftp.remove(response)
|
|
|
|
|
|
|
|
except:
|
|
|
|
print(f"Something went wrong downloading files from the server.")
|