|
| 1 | +import logging |
| 2 | +import shutil |
| 3 | + |
| 4 | +from pysftp import Connection, CnOpts |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +LOGGER = logging.getLogger(__name__) |
| 8 | + |
| 9 | +class TorrentSftp: |
| 10 | + def __init__(self, conf, dest_folder, toaster): |
| 11 | + self.conf = conf |
| 12 | + self.dest = dest_folder |
| 13 | + self.sftp = self.get_client() |
| 14 | + self.toaster = toaster |
| 15 | + |
| 16 | + def get_client(self): |
| 17 | + cnopts = CnOpts() |
| 18 | + cnopts.hostkeys = None |
| 19 | + sftp = Connection( |
| 20 | + self.conf['domain'], |
| 21 | + username=self.conf['user'], |
| 22 | + password=self.conf['password'], |
| 23 | + cnopts=cnopts, |
| 24 | + default_path=self.conf['remote_path'] |
| 25 | + ) |
| 26 | + LOGGER.info("Successfully connected to '%s' SFTP server", self.conf['domain']) |
| 27 | + return sftp |
| 28 | + |
| 29 | + def download(self, fname): |
| 30 | + """ |
| 31 | + Download torrent to local workstation |
| 32 | + """ |
| 33 | + LOGGER.info("Retrieving '%s'" % fname) |
| 34 | + if self.sftp.isfile(fname): |
| 35 | + self.sftp.get(fname, localpath="%s/%s" %(self.dest, fname)) |
| 36 | + elif self.sftp.isdir(fname): |
| 37 | + # Cannot get folder if its already exists on local. |
| 38 | + # Therefore remove it before downloading again |
| 39 | + path = Path("%s/%s" % (self.dest, fname)) |
| 40 | + if path.exists(): |
| 41 | + shutil.rmtree(path) |
| 42 | + self.sftp.get_r(fname, self.dest) |
| 43 | + else: |
| 44 | + LOGGER.info("No file to download found") |
| 45 | + return |
| 46 | + self.toaster.notif("%s is downloaded" % (fname)) |
| 47 | + |
| 48 | + def close(self): |
| 49 | + self.sftp.close() |
0 commit comments